forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolor.rs
More file actions
140 lines (129 loc) · 4.57 KB
/
color.rs
File metadata and controls
140 lines (129 loc) · 4.57 KB
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
//! Color handling.
//!
//! Uses a regular expression on the source text to handle `#define`s and
//! colors inside HTML blocks, which an annotation for strings or `rgb()` calls
//! would not catch.
use regex::Regex;
/// Extract ranges and colors from an input string.
pub fn extract_colors<'a>(input: &'a str) -> impl Iterator<Item=(usize, usize, [u8; 4])> + 'a {
COLOR_REGEX.captures_iter(input).flat_map(|capture| {
parse_capture(&capture).map(|rgba| {
let totality = capture.get(0).unwrap();
(totality.start(), totality.end(), rgba)
})
})
}
#[derive(Copy, Clone)]
pub enum ColorFormat {
Hex {
// TODO: uppercase
single_quoted: bool,
short: bool,
alpha: bool,
},
Rgb {
alpha: bool,
}
}
impl ColorFormat {
pub fn parse(input: &str) -> Option<ColorFormat> {
if input.starts_with("rgb") {
return Some(ColorFormat::Rgb {
alpha: input.chars().filter(|&c| c == ',').count() > 2,
});
};
let single_quoted = if input.starts_with("'#") && input.ends_with('\'') {
true
} else if input.starts_with("\"#") && input.ends_with('"') {
false
} else {
return None;
};
Some(ColorFormat::Hex {
single_quoted,
short: input.len() <= 7,
// "#rgba" or "#rrggbbaa"
alpha: input.len() == 7 || input.len() == 11,
})
}
pub fn format(self, [r, g, b, a]: [u8; 4]) -> String {
match self {
ColorFormat::Hex { single_quoted, short, alpha } => {
let q = if single_quoted { '\'' } else { '"' };
let short = short && r % 0x11 == 0 && g % 0x11 == 0 && b % 0x11 == 0 && a % 0x11 == 0;
let alpha = alpha || a != 255;
match (short, alpha) {
(false, false) => format!("{}#{:02x}{:02x}{:02x}{}", q, r, g, b, q),
(false, true) => format!("{}#{:02x}{:02x}{:02x}{:02x}{}", q, r, g, b, a, q),
(true, false) => format!("{}#{:x}{:x}{:x}{}", q, r / 0x11, g / 0x11, b / 0x11, q),
(true, true) => format!("{}#{:x}{:x}{:x}{:x}{}", q, r / 0x11, g / 0x11, b / 0x11, a / 0x11, q),
}
},
ColorFormat::Rgb { alpha } if alpha || a != 255 => format!("rgb({}, {}, {}, {})", r, g, b, a),
ColorFormat::Rgb { alpha: _ } => format!("rgb({}, {}, {})", r, g, b),
}
}
}
impl Default for ColorFormat {
fn default() -> ColorFormat {
ColorFormat::Hex { single_quoted: false, short: false, alpha: false }
}
}
lazy_static! {
// 3-8 digit hex colors within "#..." or '#...' and rgb() calls
static ref COLOR_REGEX: Regex = Regex::new(r##""#([0-9A-Fa-f]{3,8})"|'#([0-9A-Fa-f]{3,8})'|rgb\(\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*(\d{1,3}))?\s*\)"##).unwrap();
}
fn parse_capture(capture: ®ex::Captures) -> Option<[u8; 4]> {
// Tied closely to the regex above.
match (capture.get(1), capture.get(2), capture.get(3), capture.get(4), capture.get(5), capture.get(6)) {
(Some(cap), _, _, _, _, _) |
(_, Some(cap), _, _, _, _) => parse_hex(cap.as_str()),
(_, _, Some(r), Some(g), Some(b), a) => parse_rgba(r.as_str(), g.as_str(), b.as_str(), a.map(|a| a.as_str())),
_ => None
}
}
fn parse_hex(hex: &str) -> Option<[u8; 4]> {
let mut sum = 0;
for ch in hex.chars() {
sum = 16 * sum + ch.to_digit(16).unwrap_or(0);
}
if hex.len() == 8 { // #rrggbbaa
Some([
(sum >> 24) as u8,
(sum >> 16) as u8,
(sum >> 8) as u8,
sum as u8,
])
} else if hex.len() == 6 { // #rrggbb
Some([
(sum >> 16) as u8,
(sum >> 8) as u8,
sum as u8,
255,
])
} else if hex.len() == 4 { // #rgba
Some([
(0x11 * ((sum >> 12) & 0xf)) as u8,
(0x11 * ((sum >> 8) & 0xf)) as u8,
(0x11 * ((sum >> 4) & 0xf)) as u8,
(0x11 * (sum & 0xf)) as u8,
])
} else if hex.len() == 3 { // #rgb
Some([
(0x11 * ((sum >> 8) & 0xf)) as u8,
(0x11 * ((sum >> 4) & 0xf)) as u8,
(0x11 * (sum & 0xf)) as u8,
255,
])
} else {
None
}
}
fn parse_rgba(r: &str, g: &str, b: &str, a: Option<&str>) -> Option<[u8; 4]> {
Some([
r.parse::<u8>().ok()?,
g.parse::<u8>().ok()?,
b.parse::<u8>().ok()?,
a.and_then(|a| a.parse::<u8>().ok()).unwrap_or(255),
])
}