xmpp_parsers/
consistent_color.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (c) 2017 David Palm, as part of the rust-hsluv crate.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! XEP-0392: Consistent Color Generation
//!
//! This module contains helpers to generate unique colors for:
//!
//! - MUC user nicknames with [`Rgb::from_resource`]
//! - Roster contacts and non-anonymous MUC members with [`Rgb::from_barejid`]

use sha1::{Digest, Sha1};

use crate::jid::{BareJid, ResourceRef};

use core::{cmp::Ordering, convert::Infallible, f64::consts::PI, str::FromStr};

const EPSILON: f64 = 0.0088564516;
const KAPPA: f64 = 903.2962962;
const M: [[f64; 3]; 3] = [
    [3.240969941904521, -1.537383177570093, -0.498610760293],
    [-0.96924363628087, 1.87596750150772, 0.041555057407175],
    [0.055630079696993, -0.20397695888897, 1.056971514242878],
];

const REF_Y: f64 = 1.0;
const REF_U: f64 = 0.19783000664283;
const REF_V: f64 = 0.46831999493879;

/// Consistent color in RGB format, produced from a hashed string.
pub struct Rgb {
    /// Red component
    pub red: u8,
    /// Green component
    pub green: u8,
    /// Blue component
    pub blue: u8,
}

impl Rgb {
    fn new(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }

    /// Hash a [`ResourceRef`], usually a pseudonymous MUC nickname, to a RGB color.
    pub fn from_resource(nick: &ResourceRef) -> Self {
        // UNWRAP: 100% safe because it's infallible
        nick.as_str().parse().unwrap()
    }

    /// Hash a [`BareJid`] to a RGB color, usually a roster contact or a non-anonymous MUC member.
    pub fn from_barejid(jid: &BareJid) -> Self {
        // UNWRAP: 100% safe because it's infallible
        jid.as_str().parse().unwrap()
    }

    /// Format to hexadecimal string (eg. #abcdef)
    pub fn to_hex(&self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
    }
}

impl FromStr for Rgb {
    type Err = Infallible;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let hash = Sha1::digest(input.as_bytes());

        // Treat the output as little endian and extract the least-significant 16 bits. (These are the first two bytes of the output, with the second byte being the most significant one.)
        let mut hash_bytes = [0u8; 2];
        hash_bytes.copy_from_slice(&hash[..2]);

        // Divide the value by 65536 (use float division) and multiply it by 360 (to map it to degrees in a full circle).
        let hash_value = u16::from_le_bytes(hash_bytes);
        let hue_angle = hash_value as f64 / 65536.0 * 360.0;

        let (r, g, b) = hsluv_to_rgb((hue_angle, 100.0, 50.0));
        Ok(Self::new(r, g, b))
    }
}

/// Convert HSLUV to RGB
fn hsluv_to_rgb(hsl: (f64, f64, f64)) -> (u8, u8, u8) {
    // Floaty RGB
    let rgb = xyz_to_rgb(luv_to_xyz(lch_to_luv(hsluv_to_lch(hsl))));

    // Inty RGB
    (clamp(rgb.0), clamp(rgb.1), clamp(rgb.2))
}

fn clamp(v: f64) -> u8 {
    let mut rounded = (v * 1000.0).round() / 1000.0;
    if rounded < 0.0 {
        rounded = 0.0;
    }
    if rounded > 1.0 {
        rounded = 1.0;
    }
    (rounded * 255.0).round() as u8
}

fn hsluv_to_lch(hsl: (f64, f64, f64)) -> (f64, f64, f64) {
    let (h, s, l) = hsl;
    match l {
        l if l > 99.9999999 => (100.0, 0.0, h),
        l if l < 0.00000001 => (0.0, 0.0, h),
        _ => {
            let mx = max_chroma_for(l, h);
            let c = mx / 100.0 * s;
            (l, c, h)
        }
    }
}

fn max_chroma_for(l: f64, h: f64) -> f64 {
    let hrad = h / 360.0 * PI * 2.0;

    let mut lengths: Vec<f64> = get_bounds(l)
        .iter()
        .map(|line| length_of_ray_until_intersect(hrad, line))
        .filter(|length| length > &0.0)
        .collect();

    lengths.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
    lengths[0]
}

fn length_of_ray_until_intersect(theta: f64, line: &(f64, f64)) -> f64 {
    let (m1, b1) = *line;
    let length = b1 / (theta.sin() - m1 * theta.cos());
    if length < 0.0 {
        -0.0001
    } else {
        length
    }
}

fn luv_to_xyz(luv: (f64, f64, f64)) -> (f64, f64, f64) {
    let (l, u, v) = luv;

    if l == 0.0 {
        return (0.0, 0.0, 0.0);
    }

    let var_y = f_inv(l);
    let var_u = u / (13.0 * l) + REF_U;
    let var_v = v / (13.0 * l) + REF_V;

    let y = var_y * REF_Y;
    let x = 0.0 - (9.0 * y * var_u) / ((var_u - 4.0) * var_v - var_u * var_v);
    let z = (9.0 * y - (15.0 * var_v * y) - (var_v * x)) / (3.0 * var_v);

    (x, y, z)
}

fn lch_to_luv(lch: (f64, f64, f64)) -> (f64, f64, f64) {
    let (l, c, h) = lch;
    let hrad = degrees_to_radians(h);
    let u = hrad.cos() * c;
    let v = hrad.sin() * c;

    (l, u, v)
}

fn xyz_to_rgb(xyz: (f64, f64, f64)) -> (f64, f64, f64) {
    let xyz_vec = vec![xyz.0, xyz.1, xyz.2];
    let abc: Vec<f64> = M
        .iter()
        .map(|i| from_linear(dot_product(&i.to_vec(), &xyz_vec)))
        .collect();
    (abc[0], abc[1], abc[2])
}

fn dot_product(a: &[f64], b: &[f64]) -> f64 {
    a.iter().zip(b.iter()).map(|(i, j)| i * j).sum()
}

fn get_bounds(l: f64) -> Vec<(f64, f64)> {
    let sub1 = ((l + 16.0).powi(3)) / 1560896.0;
    let sub2 = match sub1 {
        s if s > EPSILON => s,
        _ => l / KAPPA,
    };

    let mut bounds = Vec::new();

    for ms in &M {
        let (m1, m2, m3) = (ms[0], ms[1], ms[2]);
        for t in 0..2 {
            let top1 = (284517.0 * m1 - 94839.0 * m3) * sub2;
            let top2 = (838422.0 * m3 + 769860.0 * m2 + 731718.0 * m1) * l * sub2
                - 769860.0 * f64::from(t) * l;
            let bottom = (632260.0 * m3 - 126452.0 * m2) * sub2 + 126452.0 * f64::from(t);

            bounds.push((top1 / bottom, top2 / bottom));
        }
    }
    bounds
}

fn f_inv(t: f64) -> f64 {
    if t > 8.0 {
        REF_Y * ((t + 16.0) / 116.0).powf(3.0)
    } else {
        REF_Y * t / KAPPA
    }
}

fn degrees_to_radians(deg: f64) -> f64 {
    deg * PI / 180.0
}

fn from_linear(c: f64) -> f64 {
    if c <= 0.0031308 {
        12.92 * c
    } else {
        1.055 * (c.powf(1.0 / 2.4)) - 0.055
    }
}

#[cfg(test)]
mod tests {
    use super::{clamp, Rgb};

    #[test]
    fn test_13_1() {
        struct TestVector<'a> {
            pub text: &'a str,
            #[allow(dead_code)]
            pub hextext: &'a str,
            #[allow(dead_code)]
            pub angle: f64,
            #[allow(dead_code)]
            pub hue: f64,
            pub r: f64,
            pub g: f64,
            pub b: f64,
        }

        impl<'a> TestVector<'a> {
            const fn new(
                text: &'a str,
                hextext: &'a str,
                angle: f64,
                hue: f64,
                r: f64,
                g: f64,
                b: f64,
            ) -> TestVector<'a> {
                TestVector {
                    text,
                    hextext,
                    angle,
                    hue,
                    r,
                    g,
                    b,
                }
            }
        }

        const VECTORS: &'static [&'static TestVector<'static>] = &[
            &TestVector::new(
                "Romeo",
                "526f6d656f",
                327.255249,
                327.255249,
                0.865,
                0.000,
                0.686,
            ),
            &TestVector::new(
                "juliet@capulet.lit",
                "6a756c69657440636170756c65742e6c6974",
                209.410400,
                209.410400,
                0.000,
                0.515,
                0.573,
            ),
            &TestVector::new(
                "😺", "f09f98ba", 331.199341, 331.199341, 0.872, 0.000, 0.659,
            ),
            &TestVector::new(
                "council",
                "636f756e63696c",
                359.994507,
                359.994507,
                0.918,
                0.000,
                0.394,
            ),
            &TestVector::new(
                "Board",
                "426f617264",
                171.430664,
                171.430664,
                0.000,
                0.527,
                0.457,
            ),
        ];

        for vector in VECTORS {
            let rgb: Rgb = vector.text.parse().unwrap();
            assert_eq!(rgb.red, clamp(vector.r));
            assert_eq!(rgb.green, clamp(vector.g));
            assert_eq!(rgb.blue, clamp(vector.b));
        }
    }
}