Skip to main content

azalea_chat/
style.rs

1use std::{
2    collections::HashMap,
3    fmt::{self, Debug, Display},
4    sync::LazyLock,
5};
6
7#[cfg(feature = "azalea-buf")]
8use azalea_buf::AzBuf;
9use azalea_codec::Codec;
10
11use crate::{click_event::ClickEvent, hover_event::HoverEvent};
12
13#[derive(Clone, Debug, Eq, Hash, PartialEq)]
14pub struct TextColor {
15    pub value: u32,
16    pub name: Option<String>,
17}
18impl<O: azalea_codec::Ops> Codec<O> for TextColor {
19    fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
20        TextColor::parse(&ops.get_string()?)
21            .ok_or_else(|| azalea_codec::error::ReadError::custom("not a color"))
22    }
23    fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
24        self.serialize().codec_write()
25    }
26}
27
28impl TextColor {
29    fn new(value: u32, name: Option<String>) -> Self {
30        Self { value, name }
31    }
32
33    fn serialize(&self) -> String {
34        if let Some(name) = &self.name {
35            name.to_ascii_lowercase()
36        } else {
37            self.format_value()
38        }
39    }
40
41    pub fn format_value(&self) -> String {
42        format!("#{:06X}", self.value)
43    }
44
45    /// Parse a text component in the same way that Minecraft does.
46    ///
47    /// This supports named colors and hex codes.
48    pub fn parse(value: &str) -> Option<TextColor> {
49        if value.starts_with('#') {
50            let n = value.chars().skip(1).collect::<String>();
51            let n = u32::from_str_radix(&n, 16).ok()?;
52            return Some(TextColor::from_rgb(n));
53        }
54        let color_option = NAMED_COLORS.get(&value.to_ascii_lowercase());
55        if let Some(color) = color_option {
56            return Some(color.clone());
57        }
58        None
59    }
60
61    fn from_rgb(value: u32) -> TextColor {
62        TextColor { value, name: None }
63    }
64}
65
66impl Display for TextColor {
67    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68        write!(f, "{}", self.serialize())
69    }
70}
71
72static LEGACY_FORMAT_TO_COLOR: LazyLock<HashMap<&'static ChatFormatting, TextColor>> =
73    LazyLock::new(|| {
74        let mut legacy_format_to_color = HashMap::new();
75        for formatter in &ChatFormatting::FORMATTERS {
76            if formatter.is_format() || *formatter == ChatFormatting::Reset {
77                continue;
78            }
79            legacy_format_to_color.insert(
80                formatter,
81                TextColor {
82                    value: formatter.color().unwrap(),
83                    name: Some(formatter.name().to_owned()),
84                },
85            );
86        }
87        legacy_format_to_color
88    });
89static NAMED_COLORS: LazyLock<HashMap<String, TextColor>> = LazyLock::new(|| {
90    let mut named_colors = HashMap::new();
91    for color in LEGACY_FORMAT_TO_COLOR.values() {
92        named_colors.insert(color.name.clone().unwrap(), color.clone());
93    }
94    named_colors
95});
96
97pub struct Ansi;
98impl Ansi {
99    pub const BOLD: &'static str = "\u{1b}[1m";
100    pub const ITALIC: &'static str = "\u{1b}[3m";
101    pub const UNDERLINED: &'static str = "\u{1b}[4m";
102    pub const STRIKETHROUGH: &'static str = "\u{1b}[9m";
103    // "Conceal or hide"
104    pub const OBFUSCATED: &'static str = "\u{1b}[8m";
105    pub const RESET: &'static str = "\u{1b}[m";
106
107    pub fn rgb(value: u32) -> String {
108        format!(
109            "\u{1b}[38;2;{};{};{}m",
110            (value >> 16) & 0xFF,
111            (value >> 8) & 0xFF,
112            value & 0xFF
113        )
114    }
115}
116
117#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
118#[cfg_attr(feature = "azalea-buf", derive(AzBuf))]
119pub enum ChatFormatting {
120    Black,
121    DarkBlue,
122    DarkGreen,
123    DarkAqua,
124    DarkRed,
125    DarkPurple,
126    Gold,
127    Gray,
128    DarkGray,
129    Blue,
130    Green,
131    Aqua,
132    Red,
133    LightPurple,
134    Yellow,
135    White,
136    Obfuscated,
137    Strikethrough,
138    Bold,
139    Underline,
140    Italic,
141    Reset,
142}
143
144impl ChatFormatting {
145    pub const FORMATTERS: [Self; 22] = [
146        Self::Black,
147        Self::DarkBlue,
148        Self::DarkGreen,
149        Self::DarkAqua,
150        Self::DarkRed,
151        Self::DarkPurple,
152        Self::Gold,
153        Self::Gray,
154        Self::DarkGray,
155        Self::Blue,
156        Self::Green,
157        Self::Aqua,
158        Self::Red,
159        Self::LightPurple,
160        Self::Yellow,
161        Self::White,
162        Self::Obfuscated,
163        Self::Strikethrough,
164        Self::Bold,
165        Self::Underline,
166        Self::Italic,
167        Self::Reset,
168    ];
169
170    pub fn name(&self) -> &'static str {
171        match self {
172            Self::Black => "black",
173            Self::DarkBlue => "dark_blue",
174            Self::DarkGreen => "dark_green",
175            Self::DarkAqua => "dark_aqua",
176            Self::DarkRed => "dark_red",
177            Self::DarkPurple => "dark_purple",
178            Self::Gold => "gold",
179            Self::Gray => "gray",
180            Self::DarkGray => "dark_gray",
181            Self::Blue => "blue",
182            Self::Green => "green",
183            Self::Aqua => "aqua",
184            Self::Red => "red",
185            Self::LightPurple => "light_purple",
186            Self::Yellow => "yellow",
187            Self::White => "white",
188            Self::Obfuscated => "obfuscated",
189            Self::Strikethrough => "strikethrough",
190            Self::Bold => "bold",
191            Self::Underline => "underline",
192            Self::Italic => "italic",
193            Self::Reset => "reset",
194        }
195    }
196
197    pub fn from_name(name: &str) -> Option<&'static Self> {
198        Self::FORMATTERS
199            .iter()
200            .find(|&formatter| formatter.name() == name)
201    }
202
203    pub fn code(&self) -> char {
204        match self {
205            Self::Black => '0',
206            Self::DarkBlue => '1',
207            Self::DarkGreen => '2',
208            Self::DarkAqua => '3',
209            Self::DarkRed => '4',
210            Self::DarkPurple => '5',
211            Self::Gold => '6',
212            Self::Gray => '7',
213            Self::DarkGray => '8',
214            Self::Blue => '9',
215            Self::Green => 'a',
216            Self::Aqua => 'b',
217            Self::Red => 'c',
218            Self::LightPurple => 'd',
219            Self::Yellow => 'e',
220            Self::White => 'f',
221            Self::Obfuscated => 'k',
222            Self::Strikethrough => 'm',
223            Self::Bold => 'l',
224            Self::Underline => 'n',
225            Self::Italic => 'o',
226            Self::Reset => 'r',
227        }
228    }
229
230    pub fn from_code(code: char) -> Option<Self> {
231        Some(match code {
232            '0' => Self::Black,
233            '1' => Self::DarkBlue,
234            '2' => Self::DarkGreen,
235            '3' => Self::DarkAqua,
236            '4' => Self::DarkRed,
237            '5' => Self::DarkPurple,
238            '6' => Self::Gold,
239            '7' => Self::Gray,
240            '8' => Self::DarkGray,
241            '9' => Self::Blue,
242            'a' => Self::Green,
243            'b' => Self::Aqua,
244            'c' => Self::Red,
245            'd' => Self::LightPurple,
246            'e' => Self::Yellow,
247            'f' => Self::White,
248            'k' => Self::Obfuscated,
249            'm' => Self::Strikethrough,
250            'l' => Self::Bold,
251            'n' => Self::Underline,
252            'o' => Self::Italic,
253            'r' => Self::Reset,
254            _ => return None,
255        })
256    }
257
258    pub fn is_format(&self) -> bool {
259        matches!(
260            self,
261            Self::Obfuscated
262                | Self::Strikethrough
263                | Self::Bold
264                | Self::Underline
265                | Self::Italic
266                | Self::Reset
267        )
268    }
269
270    pub fn color(&self) -> Option<u32> {
271        Some(match self {
272            Self::Black => 0,
273            Self::DarkBlue => 170,
274            Self::DarkGreen => 43520,
275            Self::DarkAqua => 43690,
276            Self::DarkRed => 11141120,
277            Self::DarkPurple => 11141290,
278            Self::Gold => 16755200,
279            Self::Gray => 11184810,
280            Self::DarkGray => 5592405,
281            Self::Blue => 5592575,
282            Self::Green => 5635925,
283            Self::Aqua => 5636095,
284            Self::Red => 16733525,
285            Self::LightPurple => 16733695,
286            Self::Yellow => 16777045,
287            Self::White => 16777215,
288            _ => return None,
289        })
290    }
291}
292
293// from ChatFormatting to TextColor
294impl TryFrom<ChatFormatting> for TextColor {
295    type Error = String;
296
297    fn try_from(formatter: ChatFormatting) -> Result<Self, Self::Error> {
298        if formatter.is_format() {
299            return Err(format!("{} is not a color", formatter.name()));
300        }
301        let color = formatter.color().unwrap_or(0);
302        Ok(Self::new(color, Some(formatter.name().to_owned())))
303    }
304}
305
306macro_rules! define_style_struct {
307    ($($(#[$doc:meta])* $field:ident : $type:ty),* $(,)?) => {
308        #[derive(Clone, Default, PartialEq, Codec)]
309        #[non_exhaustive]
310        pub struct Style {
311            $(
312                #[codec(optional)]
313                $(#[$doc])*
314                pub $field: Option<$type>,
315            )*
316        }
317
318        impl Style {
319            $(
320                pub fn $field(mut self, value: impl Into<Option<$type>>) -> Self {
321                    self.$field = value.into();
322                    self
323                }
324            )*
325
326            /// Apply another style to this one
327            pub fn apply(&mut self, style: &Style) {
328                $(
329                    if let Some(value) = &style.$field {
330                        self.$field = Some(value.clone());
331                    }
332                )*
333            }
334        }
335
336        // don't include all the None values in there
337        impl Debug for Style {
338            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339                let mut s = f.debug_struct("Style");
340                let mut is_plain = true;
341                $(
342                    if let Some($field) = &self.$field {
343                        is_plain = false;
344                        s.field(stringify!($field), $field);
345                    }
346                )*
347                if is_plain {
348                    s = f.debug_struct("(plain)");
349                }
350                s.finish()
351            }
352        }
353    };
354}
355
356define_style_struct! {
357    color: TextColor,
358    shadow_color: u32,
359    bold: bool,
360    italic: bool,
361    underlined: bool,
362    strikethrough: bool,
363    obfuscated: bool,
364    click_event: ClickEvent,
365    hover_event: HoverEvent,
366    insertion: String,
367    /// Represented as an `Identifier`.
368    font: String,
369}
370
371impl Style {
372    pub fn new() -> Self {
373        Self::default()
374    }
375
376    pub fn empty() -> Self {
377        Self::default()
378    }
379
380    /// Check if a style has no attributes set
381    pub fn is_empty(&self) -> bool {
382        self.color.is_none()
383            && self.bold.is_none()
384            && self.italic.is_none()
385            && self.underlined.is_none()
386            && self.strikethrough.is_none()
387            && self.obfuscated.is_none()
388    }
389
390    /// find the necessary ansi code to get from this style to another
391    pub fn compare_ansi(&self, after: &Style) -> String {
392        let should_reset =
393            // if any property used to be true and now it's not, reset
394            (self.bold.unwrap_or_default() && !after.bold.unwrap_or_default()) ||
395            (self.italic.unwrap_or_default() && !after.italic.unwrap_or_default()) ||
396            (self.underlined.unwrap_or_default() && !after.underlined.unwrap_or_default()) ||
397            (self.strikethrough.unwrap_or_default() && !after.strikethrough.unwrap_or_default()) ||
398            (self.obfuscated.unwrap_or_default() && !after.obfuscated.unwrap_or_default());
399
400        let mut ansi_codes = String::new();
401
402        let empty_style = Style::empty();
403
404        let before = if should_reset {
405            ansi_codes.push_str(Ansi::RESET);
406            &empty_style
407        } else {
408            self
409        };
410
411        // if any property was false/default and now it's true, add the right
412        // ansi codes
413        if !before.bold.unwrap_or_default() && after.bold.unwrap_or_default() {
414            ansi_codes.push_str(Ansi::BOLD);
415        }
416        if !before.italic.unwrap_or_default() && after.italic.unwrap_or_default() {
417            ansi_codes.push_str(Ansi::ITALIC);
418        }
419        if !before.underlined.unwrap_or_default() && after.underlined.unwrap_or_default() {
420            ansi_codes.push_str(Ansi::UNDERLINED);
421        }
422        if !before.strikethrough.unwrap_or_default() && after.strikethrough.unwrap_or_default() {
423            ansi_codes.push_str(Ansi::STRIKETHROUGH);
424        }
425        if !before.obfuscated.unwrap_or_default() && after.obfuscated.unwrap_or_default() {
426            ansi_codes.push_str(Ansi::OBFUSCATED);
427        }
428
429        // if the new color is different and not none, set color
430        let color_changed = {
431            if before.color.is_none() && after.color.is_some() {
432                true
433            } else if let Some(before_color) = &before.color
434                && let Some(after_color) = &after.color
435            {
436                before_color.value != after_color.value
437            } else {
438                false
439            }
440        };
441
442        if color_changed {
443            let after_color = after.color.as_ref().unwrap();
444            ansi_codes.push_str(&Ansi::rgb(after_color.value));
445        }
446
447        ansi_codes
448    }
449
450    /// Returns a new style that is a merge of self and other.
451    /// For any field that `other` does not specify (is None), self's value is
452    /// used.
453    pub fn merged_with(&self, other: &Style) -> Style {
454        Style {
455            color: other.color.clone().or(self.color.clone()),
456            shadow_color: other.shadow_color.or(self.shadow_color),
457            bold: other.bold.or(self.bold),
458            italic: other.italic.or(self.italic),
459            underlined: other.underlined.or(self.underlined),
460            strikethrough: other.strikethrough.or(self.strikethrough),
461            obfuscated: other.obfuscated.or(self.obfuscated),
462            click_event: other.click_event.clone().or(self.click_event.clone()),
463            hover_event: other.hover_event.clone().or(self.hover_event.clone()),
464            insertion: other.insertion.clone().or(self.insertion.clone()),
465            font: other.font.clone().or(self.font.clone()),
466        }
467    }
468
469    /// Apply a [`ChatFormatting`] to this style.
470    pub fn apply_formatting(&mut self, formatting: &ChatFormatting) {
471        match *formatting {
472            ChatFormatting::Bold => self.bold = Some(true),
473            ChatFormatting::Italic => self.italic = Some(true),
474            ChatFormatting::Underline => self.underlined = Some(true),
475            ChatFormatting::Strikethrough => self.strikethrough = Some(true),
476            ChatFormatting::Obfuscated => self.obfuscated = Some(true),
477            ChatFormatting::Reset => {
478                self.color = None;
479                self.bold = None;
480                self.italic = None;
481                self.underlined = None;
482                self.strikethrough = None;
483                self.obfuscated = None;
484            }
485            formatter => {
486                // if it's a color, set it
487                if let Some(color) = formatter.color() {
488                    self.color = Some(TextColor::from_rgb(color));
489                }
490            }
491        }
492    }
493
494    pub fn get_html_style(&self) -> String {
495        let mut style = String::new();
496        if let Some(color) = &self.color {
497            style.push_str(&format!("color:{};", color.format_value()));
498        }
499        if let Some(bold) = self.bold {
500            style.push_str(&format!(
501                "font-weight:{};",
502                if bold { "bold" } else { "normal" }
503            ));
504        }
505        if let Some(italic) = self.italic {
506            style.push_str(&format!(
507                "font-style:{};",
508                if italic { "italic" } else { "normal" }
509            ));
510        }
511        if let Some(underlined) = self.underlined {
512            style.push_str(&format!(
513                "text-decoration:{};",
514                if underlined { "underline" } else { "none" }
515            ));
516        }
517        if let Some(strikethrough) = self.strikethrough {
518            style.push_str(&format!(
519                "text-decoration:{};",
520                if strikethrough {
521                    "line-through"
522                } else {
523                    "none"
524                }
525            ));
526        }
527        if let Some(obfuscated) = self.obfuscated
528            && obfuscated
529        {
530            style.push_str("filter:blur(2px);");
531        }
532
533        style
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn text_color_named_colors() {
543        assert_eq!(TextColor::parse("red").unwrap().value, 16733525);
544    }
545    #[test]
546    fn text_color_hex_colors() {
547        assert_eq!(TextColor::parse("#a1b2c3").unwrap().value, 10597059);
548    }
549
550    #[test]
551    fn ansi_difference_should_reset() {
552        let style_a = Style {
553            bold: Some(true),
554            italic: Some(true),
555            ..Style::default()
556        };
557        let style_b = Style {
558            bold: Some(false),
559            italic: Some(true),
560            ..Style::default()
561        };
562        let ansi_difference = style_a.compare_ansi(&style_b);
563        assert_eq!(
564            ansi_difference,
565            format!(
566                "{reset}{italic}",
567                reset = Ansi::RESET,
568                italic = Ansi::ITALIC
569            )
570        )
571    }
572    #[test]
573    fn ansi_difference_shouldnt_reset() {
574        let style_a = Style {
575            bold: Some(true),
576            ..Style::default()
577        };
578        let style_b = Style {
579            bold: Some(true),
580            italic: Some(true),
581            ..Style::default()
582        };
583        let ansi_difference = style_a.compare_ansi(&style_b);
584        assert_eq!(ansi_difference, Ansi::ITALIC)
585    }
586
587    #[test]
588    fn test_from_code() {
589        assert_eq!(
590            ChatFormatting::from_code('a').unwrap(),
591            ChatFormatting::Green
592        );
593    }
594
595    #[test]
596    fn test_apply_formatting() {
597        let mut style = Style::default();
598        style.apply_formatting(&ChatFormatting::Bold);
599        style.apply_formatting(&ChatFormatting::Red);
600        assert_eq!(style.color, Some(TextColor::from_rgb(16733525)));
601    }
602}