Skip to main content

atmos/os_lib/css/
filters.rs

1// arm/v1/src/os_lib/css/filters.rs(2026-11-19 web_engine/css_filters.rs から移動。canvas2d が web_engine を import しないため)
2//! CSS `filter` プロパティの解析およびピクセル色変換ロジック。
3//! W3C CSS Filter Effects Module Level 1 準拠。
4//!
5//! 純粋な計算ロジックとして分離され、画像描画(<img>)、背景描画、
6//! および Canvas 2D (`ctx.filter`) で共有される。
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11/// CSS `filter` の1関数トークン(例 "grayscale(1)")を (種別文字列, 引数) にパースする。
12/// 引数省略時は 1.0(各フィルタの完全適用値)とする。`%` サフィックスは 0-1 に正規化。
13pub fn parse_filter_tokens(filter: &str) -> Vec<(String, f32)> {
14    let mut out = Vec::new();
15    let lower = filter.to_ascii_lowercase();
16    let mut rest = lower.as_str();
17    #[allow(clippy::string_slice)] // find() で ASCII バイト位置を特定済み
18    while let Some(paren) = rest.find('(') {
19        let name = rest[..paren].trim();
20        if name.is_empty() {
21            break;
22        }
23        let Some(close) = rest[paren..].find(')') else {
24            break;
25        };
26        let arg = rest[paren + 1..paren + close].trim();
27        // 引数省略時の既定値: `grayscale()`/`invert()`/`sepia()`/`contrast()`/`brightness()`/
28        // `saturate()` は仕様上 100%(=1.0) だが、`hue-rotate()` だけは角度(deg)であり
29        // 仕様上の既定は 0deg。
30        let empty_default = if name == "hue-rotate" { 0.0 } else { 1.0 };
31        let value = if arg.is_empty() {
32            empty_default
33        } else if let Some(pct) = arg.strip_suffix('%') {
34            pct.parse::<f32>().unwrap_or(100.0) / 100.0
35        } else if name == "hue-rotate" {
36            crate::os_lib::css::units::parse_angle_to_deg(arg).unwrap_or(0.0)
37        } else if let Some(px) = arg.strip_suffix("px") {
38            px.parse::<f32>().unwrap_or(0.0)
39        } else {
40            arg.parse::<f32>().unwrap_or(empty_default)
41        };
42        out.push((String::from(name), value));
43        rest = &rest[paren + close + 1..];
44    }
45    out
46}
47
48/// `filter` 文字列から `blur(Npx)` の半径を px 単位で抽出する(無ければ 0)。
49/// パフォーマンス上の理由で半径は 1〜8px にクランプする簡略実装。
50pub fn parse_blur_radius(filter: &str) -> i32 {
51    let lower = filter.to_ascii_lowercase();
52    let Some(start) = lower.find("blur(") else {
53        return 0;
54    };
55    #[allow(clippy::string_slice)] // find() で ASCII バイト位置を特定済み
56    let rest = &lower[start + 5..];
57    let Some(close) = rest.find(')') else {
58        return 0;
59    };
60    #[allow(clippy::string_slice)]
61    let arg = rest[..close].trim();
62    let num = arg.strip_suffix("px").unwrap_or(arg).trim();
63    match num.parse::<f32>() {
64        Ok(v) => (v.max(0.0) as i32).clamp(0, 8),
65        Err(_) => 0,
66    }
67}
68
69/// grayscale/brightness/invert/sepia/contrast/saturate/hue-rotate を順に適用する。
70pub fn apply_css_filters(filter: &str, r: u8, g: u8, b: u8) -> (u8, u8, u8) {
71    if filter.is_empty() || filter.trim().eq_ignore_ascii_case("none") {
72        return (r, g, b);
73    }
74    let (mut rf, mut gf, mut bf) = (r as f32, g as f32, b as f32);
75    for (name, amount) in parse_filter_tokens(filter) {
76        match name.as_str() {
77            "grayscale" => {
78                let amount = amount.clamp(0.0, 1.0);
79                let gray = 0.299 * rf + 0.587 * gf + 0.114 * bf;
80                rf = rf + (gray - rf) * amount;
81                gf = gf + (gray - gf) * amount;
82                bf = bf + (gray - bf) * amount;
83            }
84            "brightness" => {
85                let amount = amount.max(0.0);
86                rf *= amount;
87                gf *= amount;
88                bf *= amount;
89            }
90            "invert" => {
91                let amount = amount.clamp(0.0, 1.0);
92                rf = rf + (255.0 - rf - rf) * amount;
93                gf = gf + (255.0 - gf - gf) * amount;
94                bf = bf + (255.0 - bf - bf) * amount;
95            }
96            "sepia" => {
97                let amount = amount.clamp(0.0, 1.0);
98                let sr = 0.393 * rf + 0.769 * gf + 0.189 * bf;
99                let sg = 0.349 * rf + 0.686 * gf + 0.168 * bf;
100                let sb = 0.272 * rf + 0.534 * gf + 0.131 * bf;
101                rf = rf + (sr - rf) * amount;
102                gf = gf + (sg - gf) * amount;
103                bf = bf + (sb - bf) * amount;
104            }
105            "contrast" => {
106                let amount = amount.max(0.0);
107                rf = (rf - 128.0) * amount + 128.0;
108                gf = (gf - 128.0) * amount + 128.0;
109                bf = (bf - 128.0) * amount + 128.0;
110            }
111            "saturate" => {
112                let amount = amount.max(0.0);
113                let gray = 0.299 * rf + 0.587 * gf + 0.114 * bf;
114                rf = gray + (rf - gray) * amount;
115                gf = gray + (gf - gray) * amount;
116                bf = gray + (bf - gray) * amount;
117            }
118            "hue-rotate" => {
119                let deg = amount;
120
121                let r = rf / 255.0;
122                let g = gf / 255.0;
123                let b = bf / 255.0;
124
125                let max = r.max(g).max(b);
126                let min = r.min(g).min(b);
127                let l = (max + min) / 2.0;
128
129                let (mut h, s) = if max == min {
130                    (0.0, 0.0)
131                } else {
132                    let d = max - min;
133                    let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
134                    let mut h = if max == r {
135                        (g - b) / d + (if g < b { 6.0 } else { 0.0 })
136                    } else if max == g {
137                        (b - r) / d + 2.0
138                    } else {
139                        (r - g) / d + 4.0
140                    };
141                    h /= 6.0;
142                    (h, s)
143                };
144
145                h = (h * 360.0 + deg) % 360.0;
146                if h < 0.0 { h += 360.0; }
147                h /= 360.0;
148
149                let hue2rgb = |p: f32, q: f32, mut t: f32| -> f32 {
150                    if t < 0.0 { t += 1.0; }
151                    if t > 1.0 { t -= 1.0; }
152                    if t < 1.0 / 6.0 { return p + (q - p) * 6.0 * t; }
153                    if t < 1.0 / 2.0 { return q; }
154                    if t < 2.0 / 3.0 { return p + (q - p) * (2.0 / 3.0 - t) * 6.0; }
155                    p
156                };
157
158                if s == 0.0 {
159                    rf = l * 255.0;
160                    gf = l * 255.0;
161                    bf = l * 255.0;
162                } else {
163                    let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
164                    let p = 2.0 * l - q;
165                    rf = hue2rgb(p, q, h + 1.0 / 3.0) * 255.0;
166                    gf = hue2rgb(p, q, h) * 255.0;
167                    bf = hue2rgb(p, q, h - 1.0 / 3.0) * 255.0;
168                }
169            }
170            _ => {} // blur / drop-shadow 等は色変換側では無視
171        }
172    }
173    (
174        rf.clamp(0.0, 255.0) as u8,
175        gf.clamp(0.0, 255.0) as u8,
176        bf.clamp(0.0, 255.0) as u8,
177    )
178}
179
180/// 0xAARRGGBB 形式の色に `apply_css_filters` を適用する(アルファは不変)。
181pub fn apply_css_filters_argb(filter: &str, argb: u32) -> u32 {
182    if filter.is_empty() || filter.trim().eq_ignore_ascii_case("none") {
183        return argb;
184    }
185    let a = argb & 0xFF00_0000;
186    let r = ((argb >> 16) & 0xFF) as u8;
187    let g = ((argb >> 8) & 0xFF) as u8;
188    let b = (argb & 0xFF) as u8;
189    let (r2, g2, b2) = apply_css_filters(filter, r, g, b);
190    a | ((r2 as u32) << 16) | ((g2 as u32) << 8) | (b2 as u32)
191}