src/config/theme.rs
1216 lines · 35118 bytes
1//! # Logic for parsing styling configuration into [Style].
2use std::collections::hash_map::DefaultHasher;
3use std::hash::{Hash, Hasher};
4
5use anyhow::Context;
6use palette::Hsl;
7use ratatui::widgets::BorderType;
8use serde::de::Error as SerdeError;
9use serde::de::Visitor;
10use serde::{Deserialize, Deserializer};
11
12use crate::prelude::*;
13
14pub fn default_theme() -> Theme {
15 Theme {
16 selected: Stylable::with_modifiers(StyleModifier::REVERSED),
17 messages: ThemeMessages {
18 blockquote: LineStylable {
19 line: Some(LineName::Thick),
20 stylable: Stylable::fg(Color::Cyan),
21 },
22 code: Stylable::fg(Color::Cyan),
23 code_block: LineStylable {
24 line: Some(LineName::Plain),
25 stylable: Stylable::default(),
26 },
27 emphasis: Stylable::with_modifiers(StyleModifier::ITALIC),
28 strikethrough: Stylable::with_modifiers(StyleModifier::CROSSED_OUT),
29 strong: Stylable::with_modifiers(StyleModifier::BOLD),
30 underlined: Stylable::with_modifiers(StyleModifier::UNDERLINED),
31 ..Default::default()
32 },
33 encryption: ThemeEncryption {
34 icon_encrypted: Stylable::fg(Color::LightGreen),
35 icon_unencrypted: Stylable::fg(Color::Red),
36 icon_unknown: Stylable::fg(Color::Yellow),
37 ..Default::default()
38 },
39 tabs: ThemeTabs {
40 title: Stylable::with_modifiers(StyleModifier::DIM | StyleModifier::BOLD),
41 title_focused: Stylable::without_modifiers(StyleModifier::DIM),
42 },
43 windows: ThemeWindows {
44 border: Stylable::with_modifiers(StyleModifier::DIM).into(),
45 border_focused: Stylable::without_modifiers(StyleModifier::DIM).into(),
46 title: Stylable::with_modifiers(StyleModifier::BOLD),
47 ..Default::default()
48 },
49 completion: ThemeCompletion {
50 default: Stylable {
51 color: Some(Color::Reset),
52 background: Some(Color::Reset),
53 modifiers: vec![
54 ModifierChange::Remove(StyleModifier::all()),
55 ModifierChange::Insert(StyleModifier::REVERSED),
56 ],
57 },
58 selected: Stylable {
59 color: Some(Color::Yellow),
60 background: Some(Color::Black),
61 modifiers: vec![ModifierChange::Remove(StyleModifier::REVERSED)],
62 },
63 },
64 cmdbar: ThemeCommandBar {
65 error: Stylable::fg(Color::Red),
66 ..Default::default()
67 },
68 timeline: ThemeTimeline {
69 date: Stylable::with_modifiers(StyleModifier::BOLD),
70 unread_marker: Stylable::with_modifiers(StyleModifier::DIM),
71 ..Default::default()
72 },
73 rooms: ThemeRooms {
74 unread: ThemeRoomsUnreads {
75 name: Stylable::fg(Color::Cyan),
76 number: Stylable::fg(Color::Gray),
77 ..Default::default()
78 },
79 notification: ThemeRoomsUnreads {
80 name: Stylable::with_modifiers(StyleModifier::BOLD),
81 number: Stylable::fg(Color::Yellow),
82 ..Default::default()
83 },
84 mention: ThemeRoomsUnreads {
85 name: Stylable::with_modifiers(StyleModifier::BOLD),
86 number: Stylable::fg(Color::Red),
87 ..Default::default()
88 },
89 marked_unread: ThemeRoomsUnreads {
90 name: Stylable::with_modifiers(StyleModifier::BOLD),
91 number: Stylable::fg(Color::Green),
92 ..Default::default()
93 },
94 ..Default::default()
95 },
96 users: ThemeUsers {
97 colors: Some(UserColors::Palette(vec![
98 Color::Blue,
99 Color::Cyan,
100 Color::Green,
101 Color::LightBlue,
102 Color::LightGreen,
103 Color::LightCyan,
104 Color::LightMagenta,
105 Color::LightRed,
106 Color::LightYellow,
107 Color::Magenta,
108 Color::Red,
109 Color::Reset,
110 Color::Yellow,
111 ])),
112 stylable: Stylable::with_modifiers(StyleModifier::BOLD),
113 },
114 ..Default::default()
115 }
116}
117
118pub fn find_themes(dir: &Path) -> anyhow::Result<Vec<(String, Theme)>> {
119 let Ok(entries) = std::fs::read_dir(dir) else {
120 return Ok(vec![]);
121 };
122
123 let mut themes = vec![];
124
125 for res in entries {
126 let Ok(entry) = res else {
127 continue;
128 };
129
130 let path = entry.path();
131
132 if !path.is_file() {
133 // Skip non-files.
134 continue;
135 }
136
137 if path.extension().is_none_or(|ext| ext != "toml") {
138 // Skip non-`.toml` files.
139 continue;
140 }
141
142 let Some(name) = path.file_stem() else {
143 continue;
144 };
145
146 match ThemeFile::load(&path) {
147 Ok(file) => {
148 let name = name.to_string_lossy().into_owned();
149 themes.push((name, file.theme));
150 },
151 Err(err) => {
152 tracing::error!(?err, "failed to load theme file at {}", path.display());
153 },
154 };
155 }
156
157 Ok(themes)
158}
159
160/// A restricted subset of `config.toml` that only allows specifying themes.
161///
162/// This exists mainly to prevent people from thinking that values they put
163/// into the theme files are taking effect when they aren't: theme files are
164/// only used for sourcing theme information to prevent any weirdness around
165/// what happens when changing the theme with `:theme`.
166#[derive(Clone, Debug, Default, Deserialize)]
167#[serde(deny_unknown_fields)]
168pub struct ThemeFile {
169 pub theme: Theme,
170}
171
172impl ThemeFile {
173 pub fn load(path: &Path) -> anyhow::Result<Self> {
174 let input = std::fs::read_to_string(path)
175 .with_context(|| format!("failed to read {}", path.display()))?;
176 toml::de::from_str(&input).with_context(|| format!("failed to read {}", path.display()))
177 }
178}
179
180/// Internal variant to get lowercase, hyphenated config options.
181#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
182#[serde(rename_all = "kebab-case")]
183pub enum LineName {
184 #[default]
185 Plain,
186 Rounded,
187 Double,
188 Thick,
189 DoubleDashedLight,
190 DoubleDashedHeavy,
191 TripleDashedLight,
192 TripleDashedHeavy,
193 QuadrupleDashedLight,
194 QuadrupleDashedHeavy,
195}
196
197impl LineName {
198 pub fn to_table_set(&self) -> &'static ratatui::symbols::line::Set<'static> {
199 match self {
200 Self::Plain => &ratatui::symbols::line::NORMAL,
201 Self::Rounded => &ratatui::symbols::line::ROUNDED,
202 Self::Double => &ratatui::symbols::line::DOUBLE,
203 Self::Thick => &ratatui::symbols::line::THICK,
204 Self::DoubleDashedLight => &ratatui::symbols::line::LIGHT_DOUBLE_DASHED,
205 Self::DoubleDashedHeavy => &ratatui::symbols::line::HEAVY_DOUBLE_DASHED,
206 Self::TripleDashedLight => &ratatui::symbols::line::LIGHT_TRIPLE_DASHED,
207 Self::TripleDashedHeavy => &ratatui::symbols::line::HEAVY_TRIPLE_DASHED,
208 Self::QuadrupleDashedLight => &ratatui::symbols::line::LIGHT_QUADRUPLE_DASHED,
209 Self::QuadrupleDashedHeavy => &ratatui::symbols::line::HEAVY_QUADRUPLE_DASHED,
210 }
211 }
212}
213
214impl From<LineName> for BorderType {
215 fn from(name: LineName) -> Self {
216 match name {
217 LineName::Plain => Self::Plain,
218 LineName::Rounded => Self::Rounded,
219 LineName::Double => Self::Double,
220 LineName::Thick => Self::Thick,
221 LineName::DoubleDashedLight => Self::LightDoubleDashed,
222 LineName::DoubleDashedHeavy => Self::HeavyDoubleDashed,
223 LineName::TripleDashedLight => Self::LightTripleDashed,
224 LineName::TripleDashedHeavy => Self::HeavyTripleDashed,
225 LineName::QuadrupleDashedLight => Self::LightQuadrupleDashed,
226 LineName::QuadrupleDashedHeavy => Self::HeavyQuadrupleDashed,
227 }
228 }
229}
230
231#[derive(Clone, Copy, Debug)]
232enum ModifierChange {
233 Insert(StyleModifier),
234 Remove(StyleModifier),
235}
236
237impl ModifierChange {
238 fn apply(self, style: &mut Style) {
239 *style = match self {
240 Self::Insert(m) => style.add_modifier(m),
241 Self::Remove(m) => style.remove_modifier(m),
242 };
243 }
244}
245
246struct ModifierChangeVisitor;
247
248impl<'de> Deserialize<'de> for ModifierChange {
249 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
250 where
251 D: Deserializer<'de>,
252 {
253 deserializer.deserialize_str(ModifierChangeVisitor)
254 }
255}
256
257impl Visitor<'_> for ModifierChangeVisitor {
258 type Value = ModifierChange;
259
260 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
261 formatter.write_str("a valid style modifier (e.g. \"bold\" or \"~reversed\")")
262 }
263
264 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
265 where
266 E: SerdeError,
267 {
268 let name = value.strip_prefix("~");
269 let remove = name.is_some();
270
271 let modifier = match name.unwrap_or(value) {
272 "bold" => StyleModifier::BOLD,
273 "crossed-out" => StyleModifier::CROSSED_OUT,
274 "dim" => StyleModifier::DIM,
275 "hidden" => StyleModifier::HIDDEN,
276 "italic" => StyleModifier::ITALIC,
277 "rapid-blink" => StyleModifier::RAPID_BLINK,
278 "reversed" => StyleModifier::REVERSED,
279 "slow-blink" => StyleModifier::SLOW_BLINK,
280 "underlined" => StyleModifier::UNDERLINED,
281 other => {
282 let msg = format!("{other:?} is not a valid style modifier");
283 let err = E::custom(msg);
284 return Err(err);
285 },
286 };
287
288 if remove {
289 Ok(ModifierChange::Remove(modifier))
290 } else {
291 Ok(ModifierChange::Insert(modifier))
292 }
293 }
294}
295
296#[derive(Clone, Debug, Default, Deserialize)]
297struct Stylable {
298 background: Option<Color>,
299 color: Option<Color>,
300 #[serde(default)]
301 modifiers: Vec<ModifierChange>,
302}
303
304impl Stylable {
305 fn fg(c: Color) -> Self {
306 Self {
307 background: None,
308 color: Some(c),
309 modifiers: vec![],
310 }
311 }
312
313 fn with_modifiers(m: StyleModifier) -> Self {
314 Self {
315 background: None,
316 color: None,
317 modifiers: vec![ModifierChange::Insert(m)],
318 }
319 }
320
321 fn without_modifiers(m: StyleModifier) -> Self {
322 Self {
323 background: None,
324 color: None,
325 modifiers: vec![ModifierChange::Remove(m)],
326 }
327 }
328
329 fn merge(self, other: Self) -> Self {
330 Self {
331 background: self.background.or(other.background),
332 color: self.color.or(other.color),
333 modifiers: other.modifiers.iter().chain(&self.modifiers).copied().collect(),
334 }
335 }
336}
337
338impl From<Stylable> for Style {
339 fn from(styled: Stylable) -> Self {
340 let mut style = Style::default();
341
342 if let Some(bg) = styled.background {
343 style = style.bg(bg);
344 }
345
346 if let Some(fg) = styled.color {
347 style = style.fg(fg);
348 }
349
350 for m in styled.modifiers.iter() {
351 m.apply(&mut style);
352 }
353
354 style
355 }
356}
357
358#[derive(Clone, Debug, Default, Deserialize)]
359struct LineStylable {
360 #[serde(rename = "line")]
361 line: Option<LineName>,
362 #[serde(flatten)]
363 stylable: Stylable,
364}
365
366impl LineStylable {
367 fn merge(self, other: Self) -> Self {
368 Self {
369 line: self.line.or(other.line),
370 stylable: self.stylable.merge(other.stylable),
371 }
372 }
373}
374
375impl From<Stylable> for LineStylable {
376 fn from(stylable: Stylable) -> Self {
377 Self { stylable, line: None }
378 }
379}
380
381#[derive(Clone, Debug, Default, Deserialize)]
382pub struct Theme {
383 /// Default styling when others aren't specified.
384 #[serde(default)]
385 default: Stylable,
386
387 /// Default styling to layer on top of selected list items.
388 #[serde(default)]
389 selected: Stylable,
390
391 /// Configuration for styling the command bar.
392 #[serde(default)]
393 cmdbar: ThemeCommandBar,
394
395 /// Configuration for styling the encryption indicators.
396 #[serde(default)]
397 encryption: ThemeEncryption,
398
399 /// Configuration for styling the message bar.
400 #[serde(default)]
401 msgbar: ThemeMessageBar,
402
403 /// Configuration specificaly for messages shown within a room's timeline.
404 #[serde(default)]
405 messages: ThemeMessages,
406
407 /// Configuration for styling a room's timeline.
408 #[serde(default)]
409 timeline: ThemeTimeline,
410
411 /// Configuration for styling items within room lists.
412 #[serde(default)]
413 rooms: ThemeRooms,
414
415 /// Configuration for styling tabs.
416 #[serde(default)]
417 tabs: ThemeTabs,
418
419 /// Configuration for styling users.
420 #[serde(default)]
421 users: ThemeUsers,
422
423 /// Configuration for styling windows.
424 #[serde(default)]
425 windows: ThemeWindows,
426
427 /// Configuration for the completion menu.
428 #[serde(default)]
429 completion: ThemeCompletion,
430}
431
432impl Theme {
433 pub fn merge(self, other: Self) -> Self {
434 Self {
435 default: self.default.merge(other.default),
436 selected: self.selected.merge(other.selected),
437 cmdbar: self.cmdbar.merge(other.cmdbar),
438 encryption: self.encryption.merge(other.encryption),
439 msgbar: self.msgbar.merge(other.msgbar),
440 messages: self.messages.merge(other.messages),
441 tabs: self.tabs.merge(other.tabs),
442 timeline: self.timeline.merge(other.timeline),
443 rooms: self.rooms.merge(other.rooms),
444 users: self.users.merge(other.users),
445 windows: self.windows.merge(other.windows),
446 completion: self.completion.merge(other.completion),
447 }
448 }
449
450 pub fn values(self) -> ThemeValues {
451 let base = Style::from(self.default);
452
453 ThemeValues {
454 default: base,
455 selected: Style::from(self.selected),
456 cmdbar: self.cmdbar.values(base),
457 encryption: self.encryption.values(base),
458 msgbar: self.msgbar.values(base),
459 messages: self.messages.values(base),
460 timeline: self.timeline.values(base),
461 rooms: self.rooms.values(base),
462 tabs: self.tabs.values(base),
463 users: self.users.values(base),
464 windows: self.windows.values(base),
465 completion: self.completion.values(base),
466 }
467 }
468}
469
470#[derive(Clone, Debug, Default)]
471pub struct ThemeValues {
472 /// Styling to use when nothing more specific applies.
473 pub default: Style,
474
475 /// Styling to patch on top of selected list items.
476 pub selected: Style,
477
478 /// Styling for the command bar.
479 pub cmdbar: ThemeCommandBarValues,
480
481 /// Styling for the encryption indicators.
482 pub encryption: ThemeEncryptionValues,
483
484 /// Styling for the message bar.
485 pub msgbar: ThemeMessageBarValues,
486
487 /// Styling specificaly for messages shown within a room's timeline.
488 pub messages: ThemeMessagesValues,
489
490 /// Styling for a room's timeline.
491 pub timeline: ThemeTimelineValues,
492
493 /// Styling for items within room lists.
494 pub rooms: ThemeRoomsValues,
495
496 /// Styling for rendering tabs.
497 pub tabs: ThemeTabsValues,
498
499 /// Styling for rendering users.
500 pub users: ThemeUsersValues,
501
502 /// Styling for rendering windows.
503 pub windows: ThemeWindowsValues,
504
505 /// Styling for the completion menu.
506 pub completion: ThemeCompletionValues,
507}
508
509impl ThemeValues {
510 pub fn selected(&self, style: Style, selected: bool) -> Style {
511 if selected {
512 style.patch(self.selected)
513 } else {
514 style
515 }
516 }
517}
518
519#[derive(Clone, Debug, Default, Deserialize)]
520struct ThemeMessages {
521 #[serde(default)]
522 default: Stylable,
523
524 #[serde(default)]
525 blockquote: LineStylable,
526
527 #[serde(default)]
528 code: Stylable,
529
530 #[serde(default)]
531 code_block: LineStylable,
532
533 #[serde(default)]
534 ruler: LineStylable,
535
536 #[serde(default)]
537 table: LineStylable,
538
539 #[serde(default)]
540 emphasis: Stylable,
541
542 #[serde(default)]
543 strikethrough: Stylable,
544
545 #[serde(default)]
546 strong: Stylable,
547
548 #[serde(default)]
549 underlined: Stylable,
550}
551
552impl ThemeMessages {
553 fn merge(self, other: Self) -> Self {
554 Self {
555 default: self.default.merge(other.default),
556 blockquote: self.blockquote.merge(other.blockquote),
557 code: self.code.merge(other.code),
558 code_block: self.code_block.merge(other.code_block),
559 ruler: self.ruler.merge(other.ruler),
560 table: self.table.merge(other.table),
561 emphasis: self.emphasis.merge(other.emphasis),
562 strong: self.strong.merge(other.strong),
563 strikethrough: self.strikethrough.merge(other.strikethrough),
564 underlined: self.underlined.merge(other.underlined),
565 }
566 }
567
568 fn values(self, base: Style) -> ThemeMessagesValues {
569 let default = base.patch(self.default);
570 let blockquote = default.patch(self.blockquote.stylable);
571 let ruler = default.patch(self.ruler.stylable);
572 let table = default.patch(self.table.stylable);
573 let emphasis = default.patch(self.emphasis);
574 let strong = default.patch(self.strong);
575 let strikethrough = default.patch(self.strikethrough);
576 let underlined = default.patch(self.underlined);
577
578 let code = default.patch(self.code);
579 let code_block = code.patch(self.code_block.stylable);
580
581 let blockquote_line = self.blockquote.line.unwrap_or_default();
582 let code_block_line = self.code_block.line.unwrap_or_default().into();
583 let ruler_line = self.ruler.line.unwrap_or_default();
584 let table_line = self.table.line.unwrap_or_default();
585
586 ThemeMessagesValues {
587 default,
588 blockquote,
589 blockquote_line,
590 code,
591 code_block,
592 code_block_line,
593 ruler,
594 ruler_line,
595 table,
596 table_line,
597 emphasis,
598 strong,
599 strikethrough,
600 underlined,
601 }
602 }
603}
604
605#[derive(Clone, Debug, Default)]
606pub struct ThemeMessagesValues {
607 pub default: Style,
608 pub blockquote: Style,
609 pub blockquote_line: LineName,
610 pub code: Style,
611 pub code_block: Style,
612 pub code_block_line: BorderType,
613 pub ruler: Style,
614 pub ruler_line: LineName,
615 pub table: Style,
616 pub table_line: LineName,
617 pub emphasis: Style,
618 pub strong: Style,
619 pub strikethrough: Style,
620 pub underlined: Style,
621}
622
623#[derive(Clone, Debug, Default, Deserialize)]
624struct ThemeRooms {
625 #[serde(default)]
626 default: Stylable,
627
628 #[serde(default)]
629 labels: Stylable,
630
631 #[serde(default)]
632 unread: ThemeRoomsUnreads,
633
634 #[serde(default)]
635 notification: ThemeRoomsUnreads,
636
637 #[serde(default)]
638 mention: ThemeRoomsUnreads,
639
640 #[serde(default)]
641 marked_unread: ThemeRoomsUnreads,
642}
643
644impl ThemeRooms {
645 fn merge(self, other: Self) -> Self {
646 Self {
647 default: self.default.merge(other.default),
648 labels: self.labels.merge(other.labels),
649 unread: self.unread.merge(other.unread),
650 notification: self.notification.merge(other.notification),
651 mention: self.mention.merge(other.mention),
652 marked_unread: self.marked_unread.merge(other.marked_unread),
653 }
654 }
655
656 fn values(self, base: Style) -> ThemeRoomsValues {
657 let default = base.patch(self.default);
658 let labels = default.patch(self.labels);
659
660 // Apply any inherited unread styling to the more specific notification types:
661 let unread = self.unread;
662 let notification = self.notification.merge(unread.clone()).values(default, labels);
663 let mention = self.mention.merge(unread.clone()).values(default, labels);
664 let marked_unread = self.marked_unread.merge(unread.clone()).values(default, labels);
665 let unread = unread.values(default, labels);
666
667 ThemeRoomsValues {
668 default,
669 labels,
670 unread,
671 notification,
672 mention,
673 marked_unread,
674 }
675 }
676}
677
678#[derive(Clone, Debug, Default)]
679pub struct ThemeRoomsValues {
680 pub default: Style,
681 pub labels: Style,
682 pub unread: ThemeRoomsUnreadsValues,
683 pub notification: ThemeRoomsUnreadsValues,
684 pub mention: ThemeRoomsUnreadsValues,
685 pub marked_unread: ThemeRoomsUnreadsValues,
686}
687
688#[derive(Clone, Debug, Default, Deserialize)]
689struct ThemeRoomsUnreads {
690 #[serde(default)]
691 name: Stylable,
692
693 #[serde(default)]
694 number: Stylable,
695
696 #[serde(default)]
697 labels: Stylable,
698}
699
700impl ThemeRoomsUnreads {
701 fn merge(self, other: Self) -> Self {
702 Self {
703 name: self.name.merge(other.name),
704 number: self.number.merge(other.number),
705 labels: self.labels.merge(other.labels),
706 }
707 }
708
709 fn values(self, base: Style, labels_base: Style) -> ThemeRoomsUnreadsValues {
710 let name = base.patch(self.name);
711 let number = base.patch(self.number);
712 let labels = labels_base.patch(self.labels);
713
714 ThemeRoomsUnreadsValues { name, number, labels }
715 }
716}
717
718#[derive(Clone, Debug, Default)]
719pub struct ThemeRoomsUnreadsValues {
720 pub name: Style,
721 pub number: Style,
722 pub labels: Style,
723}
724
725#[derive(Clone, Debug, Default, Deserialize)]
726struct ThemeTabs {
727 #[serde(default)]
728 title: Stylable,
729
730 #[serde(default)]
731 title_focused: Stylable,
732}
733
734impl ThemeTabs {
735 fn merge(self, other: Self) -> Self {
736 Self {
737 title: self.title.merge(other.title),
738 title_focused: self.title_focused.merge(other.title_focused),
739 }
740 }
741
742 fn values(self, base: Style) -> ThemeTabsValues {
743 let title = base.patch(self.title);
744 let title_focused = title.patch(self.title_focused);
745
746 ThemeTabsValues { title, title_focused }
747 }
748}
749
750#[derive(Clone, Debug, Default)]
751pub struct ThemeTabsValues {
752 pub title: Style,
753 pub title_focused: Style,
754}
755
756#[derive(Clone, Debug, Default, Deserialize)]
757struct ThemeEncryption {
758 #[serde(default)]
759 default: Stylable,
760
761 #[serde(default)]
762 icon_encrypted: Stylable,
763
764 #[serde(default)]
765 icon_unencrypted: Stylable,
766
767 #[serde(default)]
768 icon_unknown: Stylable,
769}
770
771impl ThemeEncryption {
772 fn merge(self, other: Self) -> Self {
773 Self {
774 default: self.default.merge(other.default),
775 icon_encrypted: self.icon_encrypted.merge(other.icon_encrypted),
776 icon_unencrypted: self.icon_unencrypted.merge(other.icon_unencrypted),
777 icon_unknown: self.icon_unknown.merge(other.icon_unknown),
778 }
779 }
780
781 fn values(self, base: Style) -> ThemeEncryptionValues {
782 let default = base.patch(self.default);
783 let icon_encrypted = default.patch(self.icon_encrypted);
784 let icon_unencrypted = default.patch(self.icon_unencrypted);
785 let icon_unknown = default.patch(self.icon_unknown);
786
787 ThemeEncryptionValues {
788 default,
789 icon_encrypted,
790 icon_unencrypted,
791 icon_unknown,
792 }
793 }
794}
795
796#[derive(Clone, Debug, Default)]
797pub struct ThemeEncryptionValues {
798 pub default: Style,
799 pub icon_encrypted: Style,
800 pub icon_unencrypted: Style,
801 pub icon_unknown: Style,
802}
803
804#[derive(Clone, Debug, Default, Deserialize)]
805struct ThemeMessageBar {
806 #[serde(default)]
807 default: Stylable,
808}
809
810impl ThemeMessageBar {
811 fn merge(self, other: Self) -> Self {
812 Self { default: self.default.merge(other.default) }
813 }
814
815 fn values(self, base: Style) -> ThemeMessageBarValues {
816 let default = base.patch(self.default);
817
818 ThemeMessageBarValues { default }
819 }
820}
821
822#[derive(Clone, Debug, Default)]
823pub struct ThemeMessageBarValues {
824 pub default: Style,
825}
826
827#[derive(Clone, Debug, Default, Deserialize)]
828struct ThemeCommandBar {
829 #[serde(default)]
830 default: Stylable,
831
832 #[serde(default)]
833 completions: Stylable,
834
835 #[serde(default)]
836 prompt: Stylable,
837
838 #[serde(default)]
839 info: Stylable,
840
841 #[serde(default)]
842 error: Stylable,
843}
844
845impl ThemeCommandBar {
846 fn merge(self, other: Self) -> Self {
847 Self {
848 default: self.default.merge(other.default),
849 completions: self.completions.merge(other.completions),
850 prompt: self.prompt.merge(other.prompt),
851 info: self.info.merge(other.info),
852 error: self.error.merge(other.error),
853 }
854 }
855
856 fn values(self, base: Style) -> ThemeCommandBarValues {
857 let default = base.patch(self.default);
858 let completions = default.patch(self.completions);
859 let prompt = default.patch(self.prompt);
860 let info = default.patch(self.info);
861 let error = default.patch(self.error);
862 ThemeCommandBarValues { default, completions, prompt, info, error }
863 }
864}
865
866#[derive(Clone, Debug, Default)]
867pub struct ThemeCommandBarValues {
868 pub default: Style,
869 pub completions: Style,
870 pub prompt: Style,
871 pub info: Style,
872 pub error: Style,
873}
874
875#[derive(Clone, Debug, Default, Deserialize)]
876struct ThemeTimeline {
877 #[serde(default)]
878 default: Stylable,
879
880 #[serde(default)]
881 date: Stylable,
882
883 #[serde(default)]
884 time: Stylable,
885
886 #[serde(default)]
887 state: Stylable,
888
889 #[serde(default)]
890 sticker: Stylable,
891
892 #[serde(default)]
893 poll: Stylable,
894
895 #[serde(default)]
896 notice: Stylable,
897
898 #[serde(default)]
899 redacted: Stylable,
900
901 #[serde(default)]
902 unread_marker: Stylable,
903}
904
905impl ThemeTimeline {
906 fn merge(self, other: Self) -> Self {
907 Self {
908 default: self.default.merge(other.default),
909 date: self.date.merge(other.date),
910 time: self.time.merge(other.time),
911 state: self.state.merge(other.state),
912 sticker: self.sticker.merge(other.sticker),
913 poll: self.poll.merge(other.poll),
914 notice: self.notice.merge(other.notice),
915 redacted: self.redacted.merge(other.redacted),
916 unread_marker: self.unread_marker.merge(other.unread_marker),
917 }
918 }
919
920 fn values(self, base: Style) -> ThemeTimelineValues {
921 let default = base.patch(self.default);
922 let date = default.patch(self.date);
923 let time = default.patch(self.time);
924 let state = default.patch(self.state);
925 let sticker = default.patch(self.sticker);
926 let poll = default.patch(self.poll);
927 let notice = default.patch(self.notice);
928 let redacted = default.patch(self.redacted);
929 let unread_marker = default.patch(self.unread_marker);
930
931 ThemeTimelineValues {
932 default,
933 date,
934 time,
935 state,
936 sticker,
937 poll,
938 notice,
939 redacted,
940 unread_marker,
941 }
942 }
943}
944
945#[derive(Clone, Debug, Default)]
946pub struct ThemeTimelineValues {
947 pub default: Style,
948 pub date: Style,
949 pub time: Style,
950 pub state: Style,
951 pub sticker: Style,
952 pub poll: Style,
953 pub notice: Style,
954 pub redacted: Style,
955 pub unread_marker: Style,
956}
957
958#[derive(Clone, Debug, Default, Deserialize)]
959struct ThemeCompletion {
960 #[serde(default)]
961 default: Stylable,
962
963 #[serde(default)]
964 selected: Stylable,
965}
966
967impl ThemeCompletion {
968 fn merge(self, other: Self) -> Self {
969 Self {
970 default: self.default.merge(other.default),
971 selected: self.selected.merge(other.selected),
972 }
973 }
974
975 fn values(self, base: Style) -> ThemeCompletionValues {
976 let default = base.patch(self.default);
977 let selected = default.patch(self.selected);
978
979 ThemeCompletionValues { default, selected }
980 }
981}
982
983#[derive(Clone, Debug, Default)]
984pub struct ThemeCompletionValues {
985 pub default: Style,
986 pub selected: Style,
987}
988
989#[derive(Clone, Debug, Default, Deserialize)]
990struct ThemeWindows {
991 #[serde(default)]
992 default: Stylable,
993
994 #[serde(default)]
995 border: LineStylable,
996
997 #[serde(default)]
998 border_focused: LineStylable,
999
1000 #[serde(default)]
1001 title: Stylable,
1002}
1003
1004impl ThemeWindows {
1005 fn merge(self, other: Self) -> Self {
1006 Self {
1007 default: self.default.merge(other.default),
1008 border: self.border.merge(other.border),
1009 border_focused: self.border_focused.merge(other.border_focused),
1010 title: self.title.merge(other.title),
1011 }
1012 }
1013
1014 fn values(self, base: Style) -> ThemeWindowsValues {
1015 let default = base.patch(self.default);
1016 let border = default.patch(self.border.stylable);
1017 let border_focused = border.patch(self.border_focused.stylable);
1018 let title = default.patch(self.title);
1019 let border_line: BorderType = self.border.line.unwrap_or_default().into();
1020 let border_focused_line =
1021 self.border_focused.line.map(BorderType::from).unwrap_or(border_line);
1022
1023 ThemeWindowsValues {
1024 default,
1025 border,
1026 border_line,
1027 border_focused,
1028 border_focused_line,
1029 title,
1030 }
1031 }
1032}
1033
1034#[derive(Clone, Debug, Default)]
1035pub struct ThemeWindowsValues {
1036 pub default: Style,
1037 pub border: Style,
1038 pub border_line: BorderType,
1039 pub border_focused: Style,
1040 pub border_focused_line: BorderType,
1041 pub title: Style,
1042}
1043
1044#[derive(Clone, Debug, Default, Deserialize)]
1045#[serde(rename_all = "kebab-case")]
1046enum UserColors {
1047 RainbowDark,
1048 RainbowLight,
1049 #[default]
1050 #[serde(skip)]
1051 Unset,
1052 #[serde(untagged)]
1053 Palette(Vec<Color>),
1054}
1055
1056impl UserColors {
1057 fn hash(user_id: &str) -> u64 {
1058 let mut hasher = DefaultHasher::new();
1059 user_id.hash(&mut hasher);
1060 hasher.finish()
1061 }
1062
1063 fn hash_to_color(hash: f64, l_base: f64) -> Color {
1064 let h = hash % 360.0;
1065 let s = hash % 60.0 + 40.0;
1066 let l = hash % 35.0 + l_base;
1067 let hsl: Hsl = Hsl::new(h as f32, s as f32 / 100.0, l as f32 / 100.0);
1068 Color::from_hsl(hsl)
1069 }
1070
1071 fn color(&self, user_id: &str) -> Option<Color> {
1072 let color = match self {
1073 Self::Unset => return None,
1074 Self::Palette(colors) => {
1075 if colors.is_empty() {
1076 return None;
1077 } else {
1078 let hash = Self::hash(user_id) as usize;
1079 colors[hash % colors.len()]
1080 }
1081 },
1082 Self::RainbowDark => {
1083 let hash = Self::hash(user_id);
1084 Self::hash_to_color(hash as f64, 15.0)
1085 },
1086 Self::RainbowLight => {
1087 let hash = Self::hash(user_id);
1088 Self::hash_to_color(hash as f64, 50.0)
1089 },
1090 };
1091
1092 Some(color)
1093 }
1094}
1095
1096#[derive(Clone, Debug, Default, Deserialize)]
1097struct ThemeUsers {
1098 colors: Option<UserColors>,
1099 #[serde(flatten)]
1100 stylable: Stylable,
1101}
1102
1103impl ThemeUsers {
1104 fn merge(self, other: Self) -> Self {
1105 Self {
1106 colors: self.colors.or(other.colors),
1107 stylable: self.stylable.merge(other.stylable),
1108 }
1109 }
1110
1111 fn values(self, base: Style) -> ThemeUsersValues {
1112 let style = base.patch(self.stylable);
1113 let colors = self.colors.unwrap_or_default();
1114
1115 ThemeUsersValues { colors, style }
1116 }
1117}
1118
1119#[derive(Clone, Debug, Default)]
1120pub struct ThemeUsersValues {
1121 colors: UserColors,
1122 style: Style,
1123}
1124
1125impl ThemeUsersValues {
1126 pub fn color(&self, user_id: &str) -> Color {
1127 self.colors.color(user_id).or(self.style.fg).unwrap_or(Color::Reset)
1128 }
1129
1130 pub fn style(&self, user_id: &str, explicit: Option<Color>) -> Style {
1131 let style = self.style;
1132
1133 if let Some(c) = explicit {
1134 // Use explicit color from config file:
1135 style.fg(c)
1136 } else if let Some(c) = self.colors.color(user_id) {
1137 // Apply the user color we hashed to:
1138 style.fg(c)
1139 } else {
1140 style
1141 }
1142 }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147 use super::*;
1148
1149 #[test]
1150 fn test_remove_modifier() {
1151 let res: Theme = serde_json::from_str(
1152 r#"
1153 {
1154 "default": {
1155 "color":"red",
1156 "modifiers":["bold"]
1157 },
1158 "windows":{
1159 "border": {"color":"green"},
1160 "border_focused": {"modifiers":["~bold"]}
1161 }
1162 }"#,
1163 )
1164 .unwrap();
1165 let values = res.values();
1166 assert_eq!(values.default, Style::default().fg(Color::Red).bold());
1167 assert_eq!(values.windows.border, Style::default().fg(Color::Green).bold());
1168 assert_eq!(values.windows.border_focused, Style::default().fg(Color::Green).not_bold());
1169 assert_eq!(values.windows.title, Style::default().fg(Color::Red).bold());
1170 }
1171
1172 #[test]
1173 fn test_border_names() {
1174 let res: LineName = serde_json::from_str(r#""plain""#).unwrap();
1175 assert_eq!(res, LineName::Plain);
1176
1177 let res: LineName = serde_json::from_str(r#""rounded""#).unwrap();
1178 assert_eq!(res, LineName::Rounded);
1179
1180 let res: LineName = serde_json::from_str(r#""double-dashed-light""#).unwrap();
1181 assert_eq!(res, LineName::DoubleDashedLight);
1182
1183 let res: LineName = serde_json::from_str(r#""double-dashed-heavy""#).unwrap();
1184 assert_eq!(res, LineName::DoubleDashedHeavy);
1185 }
1186
1187 #[test]
1188 fn test_load_packaged_themes() {
1189 let dir = Path::new("themes");
1190 let mut count = 0;
1191
1192 for entry in std::fs::read_dir(dir).expect("can read themes") {
1193 let path = entry.expect("can read theme file").path();
1194
1195 if path.extension().is_none_or(|ext| ext != "toml") {
1196 continue;
1197 }
1198
1199 let file = ThemeFile::load(&path)
1200 .with_context(|| format!("failed to parse {}", path.display()))
1201 .expect("parsed theme");
1202 assert!(file.theme.default.background.is_some());
1203 assert!(file.theme.default.color.is_some());
1204
1205 count += 1;
1206 }
1207
1208 // We don't hardcode the theme count so that adding new themes doesn't
1209 // require updating this test every time, but we do check that we have
1210 // seen enough that if something major changes (like renaming every
1211 // file to no longer end in `.toml`) then we will notice and fix this
1212 // test to account for it and continue asserting that the tests remain
1213 // valid.
1214 assert!(count > 40, "we should process >40 themes");
1215 }
1216}