Skip to main content

atmos/os_lib/web_engine/
inline_svg.rs

1//! 文書内の `<svg>`(インライン SVG)を、SVG ラスタライザ(`os_lib::svg`)へ渡すマークアップへ直す。
2//!
3//! 【2026-10-24】インライン SVG は描画経路が無く(`<img src="*.svg">` だけ対応)、YouTube の操作バーの
4//! アイコン(`<svg class="ytp-svg-fill" viewBox="0 -960 960 960"><path d=…/></svg>`、塗りは CSS の
5//! `.ytp-svg-fill{fill:#fff}`)が描かれなかった。ラスタライザは要素ごとの `fill` 属性しか見ないため、
6//! CSS の `fill`・親からの継承・`currentColor` をここで解決し、各要素に `fill` 属性として書き出す。
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11/// インライン SVG の 1 要素(DOM とスタイルから組み立てる)。
12#[derive(Debug, Clone)]
13pub struct SvgNode {
14    pub tag: String,
15    /// 属性(出現順)。
16    pub attrs: Vec<(String, String)>,
17    /// CSS で指定された `fill`(無ければ None。表示属性の `fill` より強い)。
18    pub css_fill: Option<String>,
19    pub children: Vec<SvgNode>,
20}
21
22/// `root` を `fill` を解決したマークアップにする。`current_color` は `currentColor` の置き換え先(CSS の color)。
23pub fn serialize_svg(root: &SvgNode, current_color: &str) -> String {
24    serialize_svg_inheriting(root, None, current_color)
25}
26
27/// `serialize_svg` に、svg の外(HTML の祖先)から継承した `fill` を与える版。継承値は表示属性より弱い。
28pub fn serialize_svg_inheriting(root: &SvgNode, inherited_fill: Option<&str>, current_color: &str) -> String {
29    let mut out = String::new();
30    write_node(root, inherited_fill, current_color, &mut out);
31    out
32}
33
34/// 描画結果を画像キャッシュに置くときの鍵(内容と描画サイズで変わる)。
35pub fn cache_key(markup: &str, w: i32, h: i32) -> String {
36    // FNV-1a(64bit)。暗号強度は要らず、同じ内容・サイズなら同じ鍵になればよい。
37    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
38    for b in markup.bytes() {
39        hash ^= u64::from(b);
40        hash = hash.wrapping_mul(0x0100_0000_01b3);
41    }
42    alloc::format!("inline-svg:{:016x}:{}x{}:{}", hash, w, h, markup.len())
43}
44
45fn normalize_svg_tag(tag: &str) -> &str {
46    if tag.eq_ignore_ascii_case("lineargradient") {
47        "linearGradient"
48    } else if tag.eq_ignore_ascii_case("radialgradient") {
49        "radialGradient"
50    } else if tag.eq_ignore_ascii_case("clippath") {
51        "clipPath"
52    } else {
53        tag
54    }
55}
56
57fn normalize_svg_attr(k: &str) -> &str {
58    if k.eq_ignore_ascii_case("viewbox") {
59        "viewBox"
60    } else if k.eq_ignore_ascii_case("gradientunits") {
61        "gradientUnits"
62    } else if k.eq_ignore_ascii_case("gradienttransform") {
63        "gradientTransform"
64    } else {
65        k
66    }
67}
68
69fn write_node(node: &SvgNode, inherited_fill: Option<&str>, current_color: &str, out: &mut String) {
70    let is_def_container = node.tag.eq_ignore_ascii_case("defs")
71        || node.tag.eq_ignore_ascii_case("symbol")
72        || node.tag.eq_ignore_ascii_case("lineargradient")
73        || node.tag.eq_ignore_ascii_case("radialgradient")
74        || node.tag.eq_ignore_ascii_case("stop");
75
76    let attr_fill = node
77        .attrs
78        .iter()
79        .find(|(k, _)| k.eq_ignore_ascii_case("fill"))
80        .map(|(_, v)| v.as_str());
81    let fill = if is_def_container {
82        None
83    } else {
84        node.css_fill
85            .as_deref()
86            .map(str::trim)
87            .filter(|v| !v.is_empty() && *v != "inherit")
88            .or(attr_fill)
89            .or(inherited_fill)
90            .map(|f| {
91                if f.trim().eq_ignore_ascii_case("currentcolor") {
92                    current_color
93                } else {
94                    f
95                }
96            })
97    };
98
99    let tag_out = normalize_svg_tag(&node.tag);
100    out.push('<');
101    out.push_str(tag_out);
102    for (k, v) in &node.attrs {
103        if k.eq_ignore_ascii_case("fill") && !is_def_container {
104            continue;
105        }
106        let k_norm = normalize_svg_attr(k);
107        let v_resolved = if (k.eq_ignore_ascii_case("stroke") || k.eq_ignore_ascii_case("stop-color"))
108            && v.trim().eq_ignore_ascii_case("currentcolor")
109        {
110            current_color
111        } else {
112            v.as_str()
113        };
114        push_attr(out, k_norm, v_resolved);
115    }
116    if let Some(f) = fill {
117        push_attr(out, "fill", f);
118    }
119    if node.children.is_empty() {
120        out.push_str("/>");
121        return;
122    }
123    out.push('>');
124    // <defs> や <symbol> の子には外側の inherited_fill を焼き込まない(<use> 側の塗りを優先できるようにする)。
125    let child_inherited_fill = if is_def_container { None } else { fill };
126    for c in &node.children {
127        write_node(c, child_inherited_fill, current_color, out);
128    }
129    out.push_str("</");
130    out.push_str(tag_out);
131    out.push('>');
132}
133
134fn push_attr(out: &mut String, k: &str, v: &str) {
135    out.push(' ');
136    out.push_str(k);
137    out.push_str("=\"");
138    for ch in v.chars() {
139        match ch {
140            '"' => out.push_str("&quot;"),
141            '<' => out.push_str("&lt;"),
142            '&' => out.push_str("&amp;"),
143            _ => out.push(ch),
144        }
145    }
146    out.push('"');
147}