Skip to main content

atmos/os_lib/css/
color.rs

1// 分割: css.rs より機械的に移動(2026-07-16 リファクタ フェーズ3)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5/// `rgb()`/`rgba()` の1成分を 0-255 の整数へ解決する。CSS1 の頃から有効な構文である
6/// パーセント表記(`100%`→255、`50%`→128)と、通常の整数表記(`0`〜`255`、範囲外はクランプ)
7/// の両方に対応する。
8pub(crate) fn parse_rgb_component(s: &str) -> u32 {
9    let t = s.trim();
10    if let Some(pct) = t.strip_suffix('%') {
11        let p = pct.trim().parse::<f32>().unwrap_or(0.0);
12        let p = if p.is_finite() { p } else { 0.0 };
13        ((p / 100.0) * 255.0).clamp(0.0, 255.0) as u32
14    } else {
15        let val = t.parse::<f32>().unwrap_or(0.0);
16        let val = if val.is_finite() { val } else { 0.0 };
17        val.clamp(0.0, 255.0) as u32
18    }
19}
20
21fn unescape_css_ident_color(s: &str) -> String {
22    let mut out = String::with_capacity(s.len());
23    let mut chars = s.chars().peekable();
24    while let Some(c) = chars.next() {
25        if c != '\\' {
26            out.push(c);
27            continue;
28        }
29        let Some(&next) = chars.peek() else { break };
30        if next.is_ascii_hexdigit() {
31            let mut hex = String::with_capacity(6);
32            while hex.len() < 6 {
33                match chars.peek() {
34                    Some(&h) if h.is_ascii_hexdigit() => {
35                        hex.push(h);
36                        chars.next();
37                    }
38                    _ => break,
39                }
40            }
41            if let Ok(code) = u32::from_str_radix(&hex, 16) {
42                if let Some(ch) = char::from_u32(code) {
43                    out.push(ch);
44                }
45            }
46            if let Some(&w) = chars.peek() {
47                if w.is_ascii_whitespace() {
48                    chars.next();
49                }
50            }
51        } else {
52            out.push(next);
53            chars.next();
54        }
55    }
56    out
57}
58
59pub fn parse_color(s: &str) -> Option<u32> {
60    let s_trim = s.trim();
61    if s_trim.is_empty() {
62        return None;
63    }
64    let unescaped_buf;
65    let s_trim = if s_trim.contains('\\') {
66        unescaped_buf = unescape_css_ident_color(s_trim);
67        unescaped_buf.trim()
68    } else {
69        s_trim
70    };
71
72    // #RRGGBB, #RGB, #RRGGBBAA, #RGBA
73    if let Some(hex) = s_trim.strip_prefix('#') {
74        let bytes = hex.as_bytes();
75        let from_hex_digit = |b: u8| -> Option<u32> {
76            match b {
77                b'0'..=b'9' => Some((b - b'0') as u32),
78                b'a'..=b'f' => Some((b - b'a' + 10) as u32),
79                b'A'..=b'F' => Some((b - b'A' + 10) as u32),
80                _ => None,
81            }
82        };
83
84        if bytes.len() == 8 {
85            let mut val = 0u32;
86            for &b in bytes {
87                val = (val << 4) | from_hex_digit(b)?;
88            }
89            let r = (val >> 24) & 0xFF;
90            let g = (val >> 16) & 0xFF;
91            let b = (val >> 8) & 0xFF;
92            let a = val & 0xFF;
93            return Some((a << 24) | (r << 16) | (g << 8) | b);
94        } else if bytes.len() == 6 {
95            let mut val = 0u32;
96            for &b in bytes {
97                val = (val << 4) | from_hex_digit(b)?;
98            }
99            return Some(0xFF000000 | val);
100        } else if bytes.len() == 3 {
101            let r = from_hex_digit(bytes[0])?;
102            let g = from_hex_digit(bytes[1])?;
103            let b = from_hex_digit(bytes[2])?;
104            let r_byte = (r << 4) | r;
105            let g_byte = (g << 4) | g;
106            let b_byte = (b << 4) | b;
107            return Some(0xFF000000 | (r_byte << 16) | (g_byte << 8) | b_byte);
108        } else if bytes.len() == 4 {
109            let r = from_hex_digit(bytes[0])?;
110            let g = from_hex_digit(bytes[1])?;
111            let b = from_hex_digit(bytes[2])?;
112            let a = from_hex_digit(bytes[3])?;
113            let r_byte = (r << 4) | r;
114            let g_byte = (g << 4) | g;
115            let b_byte = (b << 4) | b;
116            let a_byte = (a << 4) | a;
117            return Some((a_byte << 24) | (r_byte << 16) | (g_byte << 8) | b_byte);
118        }
119        return None;
120    }
121
122    // ASCII だけ小文字にする(Unicode の大文字小文字写像だと `blacK`(ケルビン記号)が `black` になってしまう)。
123    let s_lower = s_trim.to_ascii_lowercase();
124
125    // light-dark(light-color, dark-color) — CSS Color Module Level 5。丸ごと未対応
126    // だった。`prefers-color-scheme` メディアクエリと同じ `PREFERS_DARK` を真実源とし、
127    // 現在の配色設定に応じてどちらか一方の色式(ネストした `light-dark()` も可)を
128    // 選んで再帰的に解決する。
129    if let Some(inner) = s_lower.strip_prefix("light-dark(").and_then(|s| s.strip_suffix(')')) {
130        let mut depth = 0i32;
131        let mut split_at = None;
132        for (i, ch) in inner.char_indices() {
133            match ch {
134                '(' => depth += 1,
135                ')' => depth -= 1,
136                ',' if depth == 0 => {
137                    split_at = Some(i);
138                    break;
139                }
140                _ => {}
141            }
142        }
143        if let Some(i) = split_at {
144            let light = inner.get(..i).unwrap_or("").trim();
145            let dark = inner.get(i + 1..).unwrap_or("").trim();
146            let is_dark = PREFERS_DARK.load(AtomicOrd::Relaxed);
147            return parse_color(if is_dark { dark } else { light });
148        }
149        return None;
150    }
151
152    // 色の関数表記(rgb/hsl/hwb/lab/lch/oklab/oklch/color/color-mix/相対色/alpha)は `color4.rs` が
153    // CSS Color 4/5 の構文どおりに解析する(2026-11-19、TODO S2 手順 4)。不正な表記は `None`。
154    if let Some(r) = super::color4::parse_color_fn(&s_lower) {
155        return r;
156    }
157
158    // 名前付き色 (CSS Level 1-4 から実用的なものを網羅)
159    match s_lower.as_str() {
160        "black" => Some(0xFF000000),
161        "white" => Some(0xFFFFFFFF),
162        "red" => Some(0xFFFF0000),
163        "lime" => Some(0xFF00FF00),
164        "blue" => Some(0xFF0000FF),
165        "yellow" => Some(0xFFFFFF00),
166        "cyan" | "aqua" => Some(0xFF00FFFF),
167        "magenta" | "fuchsia" => Some(0xFFFF00FF),
168        "silver" => Some(0xFFC0C0C0),
169        "gray" | "grey" => Some(0xFF808080),
170        "maroon" => Some(0xFF800000),
171        "olive" => Some(0xFF808000),
172        "green" => Some(0xFF008000),
173        "purple" => Some(0xFF800080),
174        "teal" => Some(0xFF008080),
175        "navy" => Some(0xFF000080),
176        "orange" => Some(0xFFFFA500),
177        "pink" => Some(0xFFFFC0CB),
178        "brown" => Some(0xFFA52A2A),
179        "coral" => Some(0xFFFF7F50),
180        "tomato" => Some(0xFFFF6347),
181        "gold" => Some(0xFFFFD700),
182        "indigo" => Some(0xFF4B0082),
183        "violet" => Some(0xFFEE82EE),
184        "crimson" => Some(0xFFDC143C),
185        "darkred" => Some(0xFF8B0000),
186        "darkgreen" => Some(0xFF006400),
187        "darkblue" => Some(0xFF00008B),
188        "darkgray" | "darkgrey" => Some(0xFFA9A9A9),
189        "lightgray" | "lightgrey" => Some(0xFFD3D3D3),
190        "lightblue" => Some(0xFFADD8E6),
191        "lightgreen" => Some(0xFF90EE90),
192        "lightyellow" => Some(0xFFFFFFE0),
193        "steelblue" => Some(0xFF4682B4),
194        "slategray" | "slategrey" => Some(0xFF708090),
195        "indianred" => Some(0xFFCD5C5C),
196        "royalblue" => Some(0xFF4169E1),
197        "dodgerblue" => Some(0xFF1E90FF),
198        "skyblue" => Some(0xFF87CEEB),
199        "whitesmoke" => Some(0xFFF5F5F5),
200        "wheat" => Some(0xFFF5DEB3),
201        "tan" => Some(0xFFD2B48C),
202        "salmon" => Some(0xFFFA8072),
203        "plum" => Some(0xFFDDA0DD),
204        "orchid" => Some(0xFFDA70D6),
205        "linen" => Some(0xFFFAF0E6),
206        "khaki" => Some(0xFFF0E68C),
207        "ivory" => Some(0xFFFFFFF0),
208        "honeydew" => Some(0xFFF0FFF0),
209        "hotpink" => Some(0xFFFF69B4),
210        "deeppink" => Some(0xFFFF1493),
211        "beige" => Some(0xFFF5F5DC),
212        "aliceblue" => Some(0xFFF0F8FF),
213        "transparent" => Some(0x00000000),
214        // CSS Level 4 extended colors
215        "rebeccapurple" => Some(0xFF663399),
216        "mintcream" => Some(0xFFF5FFFA),
217        "azure" => Some(0xFFF0FFFF),
218        "floralwhite" => Some(0xFFFFFAF0),
219        "ghostwhite" => Some(0xFFF8F8FF),
220        "seashell" => Some(0xFFFFF5EE),
221        "oldlace" => Some(0xFFFDF5E6),
222        "antiquewhite" => Some(0xFFFAEBD7),
223        "bisque" => Some(0xFFFFE4C4),
224        "moccasin" => Some(0xFFFFE4B5),
225        "navajowhite" => Some(0xFFFFDEAD),
226        "papayawhip" => Some(0xFFFFEFD5),
227        "peachpuff" => Some(0xFFFFDAB9),
228        "mistyrose" => Some(0xFFFFE4E1),
229        "lavender" => Some(0xFFE6E6FA),
230        "lavenderblush" => Some(0xFFFFF0F5),
231        "thistle" => Some(0xFFD8BFD8),
232        "powderblue" => Some(0xFFB0E0E6),
233        "lightcyan" => Some(0xFFE0FFFF),
234        "paleturquoise" => Some(0xFFAFEEEE),
235        "turquoise" => Some(0xFF40E0D0),
236        "mediumturquoise" => Some(0xFF48D1CC),
237        "darkturquoise" => Some(0xFF00CED1),
238        "cadetblue" => Some(0xFF5F9EA0),
239        "darkcyan" => Some(0xFF008B8B),
240        "lightseagreen" => Some(0xFF20B2AA),
241        "mediumaquamarine" => Some(0xFF66CDAA),
242        "aquamarine" => Some(0xFF7FFFD4),
243        "springgreen" => Some(0xFF00FF7F),
244        "mediumspringgreen" => Some(0xFF00FA9A),
245        "lawngreen" => Some(0xFF7CFC00),
246        "chartreuse" => Some(0xFF7FFF00),
247        "greenyellow" => Some(0xFFADFF2F),
248        "yellowgreen" => Some(0xFF9ACD32),
249        "darkolivegreen" => Some(0xFF556B2F),
250        "olivedrab" => Some(0xFF6B8E23),
251        "palegreen" => Some(0xFF98FB98),
252        "mediumseagreen" => Some(0xFF3CB371),
253        "seagreen" => Some(0xFF2E8B57),
254        "forestgreen" => Some(0xFF228B22),
255        "limegreen" => Some(0xFF32CD32),
256        "darkkhaki" => Some(0xFFBDB76B),
257        "goldenrod" => Some(0xFFDAA520),
258        "darkgoldenrod" => Some(0xFFB8860B),
259        "saddlebrown" => Some(0xFF8B4513),
260        "sienna" => Some(0xFFA0522D),
261        "peru" => Some(0xFFCD853F),
262        "burlywood" => Some(0xFFDEB887),
263        "sandybrown" => Some(0xFFF4A460),
264        "chocolate" => Some(0xFFD2691E),
265        "rosybrown" => Some(0xFFBC8F8F),
266        "darkmagenta" => Some(0xFF8B008B),
267        "darkviolet" => Some(0xFF9400D3),
268        "blueviolet" => Some(0xFF8A2BE2),
269        "mediumvioletred" => Some(0xFFC71585),
270        "palevioletred" => Some(0xFFDB7093),
271        "mediumorchid" => Some(0xFFBA55D3),
272        "mediumpurple" => Some(0xFF9370DB),
273        "slateblue" => Some(0xFF6A5ACD),
274        "mediumslateblue" => Some(0xFF7B68EE),
275        "darkslateblue" => Some(0xFF483D8B),
276        "midnightblue" => Some(0xFF191970),
277        "cornflowerblue" => Some(0xFF6495ED),
278        "deepskyblue" => Some(0xFF00BFFF),
279        "lightskyblue" => Some(0xFF87CEFA),
280        "lightsteelblue" => Some(0xFFB0C4DE),
281        "darkslategray" | "darkslategrey" => Some(0xFF2F4F4F),
282        "dimgray" | "dimgrey" => Some(0xFF696969),
283        "gainsboro" => Some(0xFFDCDCDC),
284        "snow" => Some(0xFFFFFAFA),
285        "lightcoral" => Some(0xFFF08080),
286        "darksalmon" => Some(0xFFE9967A),
287        "lightsalmon" => Some(0xFFFFA07A),
288        "orangered" => Some(0xFFFF4500),
289        "darkorange" => Some(0xFFFF8C00),
290        "firebrick" => Some(0xFFB22222),
291        "currentcolor" => None, // コンテキスト依存のため呼び出し側で処理
292        other => super::color4::extra_named(other)
293            .or_else(|| super::color4::system_color(other, PREFERS_DARK.load(AtomicOrd::Relaxed))),
294    }
295}
296