Skip to main content

atmos/os_lib/web_engine/
layout.rs

1// web_engine/layout.rs - parse_and_layout and flatten_layout impl blocks
2#![allow(dead_code, unused_variables, unused_imports)]
3
4use crate::kernel::draw;
5use crate::kernel::vector_font;
6use alloc::string::String;
7use alloc::vec::Vec;
8
9use super::draw_helpers::{extract_border_color, extract_border_style};
10use super::helpers::{
11    ascii_eq_ignore_case, extract_all_url_paths, extract_list_style, extract_list_style_image,
12    extract_list_style_inside, extract_url_path,
13    get_base_path,
14    parse_bg_position, parse_bg_repeat, parse_bg_size, parse_font_size, parse_object_fit,
15    parse_object_position, parse_outline, parse_px_val, parse_text_decoration_shorthand,
16    parse_transform, parse_transform_with_size, parse_transform_origin, resolve_dom_paths, resolve_relative_path,
17};
18use super::{HyperlinkArea, RenderElement, MAX_HTML_BYTES, MAX_RENDER_ELEMENTS};
19use super::scrollbar::{parse_scrollbar_color, ScrollbarColorMode, ScrollbarWidth};
20use crate::os_lib::css::parse_color;
21
22// --- flatten_layout サブツリー再利用(FLATTEN_MEMO / TODO P5c) ----------------
23// LAYOUT_MEMO がレイアウト(寸法計算)をスキップしても flatten_layout は毎回全要素を
24// 作り直す。DOM 変更・タイマー更新等で変わらなかった部分木について前回生成した
25// RenderElement を再利用(位置同一の場合のみ。翻訳なし)し、flatten の走査を省く。
26// 継承状態(color・font_size・z・stack_prefix 等)と位置が前回と一致すれば安全。
27use alloc::collections::BTreeMap;
28
29#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
30struct FlattenMemoKey {
31    subtree_hash: (u64, u64),
32    inherited_hash: u64,
33    x: i32,
34    y: i32,
35    env_hash: u64,
36}
37
38struct FlattenMemoEntry {
39    elements: Vec<RenderElement>,
40    /// 子孫の再帰で push された abs_marks(部分木先頭からの相対位置)。
41    abs_marks: Vec<(usize, usize, u32)>,
42}
43
44/// 【2026-11-18】項目は量の上限つきの表(`flatten_memo_budget::BudgetLru`)に入れる。
45/// 使った時(LRU)・入れたアプリの組(TODO R2 (c) ③)・量の見積もりは表の側が持つ。
46struct FlattenMemo {
47    map: super::flatten_memo_budget::BudgetLru<FlattenMemoKey, FlattenMemoEntry>,
48    hits: u64,
49    misses: u64,
50}
51
52impl FlattenMemo {
53    /// 1 項目の要素の数の上限(量を数える前の早い足切り)。
54    const MAX_ELEMENTS: usize = 20000;
55    const fn new() -> Self {
56        Self {
57            map: super::flatten_memo_budget::BudgetLru::new(super::flatten_memo_budget::Limits::FLATTEN_MEMO),
58            hits: 0,
59            misses: 0,
60        }
61    }
62}
63
64static GLOBAL_FLATTEN_MEMO: spin::Mutex<FlattenMemo> = spin::Mutex::new(FlattenMemo::new());
65
66/// flatten 使い回し表を空にする。
67pub fn clear_flatten_memo() {
68    let mut g = GLOBAL_FLATTEN_MEMO.lock();
69    g.map.clear();
70    g.hits = 0;
71    g.misses = 0;
72}
73
74/// 閉じたアプリの組の項目を捨てる必要があるか(TODO R2 (c) ③、2026-11-18)。
75///
76/// 【2026-11-18】この表はアプリをまたいだ大域の置き場で、閉じたアプリ・止めたアプリのページの
77/// `RenderElement` を、次に同じ表があふれるまで持ち続けていた。3MB の文字の塊のページ
78/// (約 1.6 万行)では、`<p>`・`<body>`・`<html>` の部分木ごとに同じ行の要素の写しが入り、
79/// アプリを止めた後も約 140MB が残っていた(`about:blank` を開き直しても残る)。
80/// 組を閉じたら印を立て、表の錠を取った者が閉じた組の項目を捨てる。
81static FLATTEN_MEMO_PURGE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
82
83/// 閉じた組の項目を捨てる(錠の中で呼ぶ)。捨てた要素の数を返す。
84fn purge_closed_groups(g: &mut FlattenMemo) -> usize {
85    if !FLATTEN_MEMO_PURGE.swap(false, core::sync::atomic::Ordering::AcqRel) {
86        return 0;
87    }
88    let mut dropped = 0;
89    g.map.retain(|group, e| {
90        let keep = !crate::kernel::window_mgr::group_stopped(group);
91        if !keep {
92            dropped += e.elements.len();
93        }
94        keep
95    });
96    dropped
97}
98
99/// アプリの組を閉じたときに呼ぶ(`window_mgr::on_group_closed`。止めたスレッドの上からも呼ぶので錠は待たない)。
100/// 今すぐ捨てられたら捨てた要素の数、表が塞がっていたら `None`(次に表の錠を取った者が捨てる)。
101pub fn forget_flatten_memo_of_closed_groups() -> Option<usize> {
102    FLATTEN_MEMO_PURGE.store(true, core::sync::atomic::Ordering::Release);
103    let mut g = GLOBAL_FLATTEN_MEMO.try_lock()?;
104    Some(purge_closed_groups(&mut g))
105}
106
107/// flatten 使い回し表の統計 `(hits, misses, entries, bytes)`。
108pub fn flatten_memo_stats() -> (u64, u64, usize, usize) {
109    let g = GLOBAL_FLATTEN_MEMO.lock();
110    (g.hits, g.misses, g.map.len(), g.map.total_bytes())
111}
112
113/// `RenderElement` 1 個が使うヒープのおおよその量(構造体そのもの+主な文字列・配列の中身)。
114/// 使い回し表の量の上限に使う(2026-11-18)。写し(`clone`)は中身の長さちょうどで確保するので長さで数える。
115/// 中身の無い文字列は確保しないので 0、ある物は確保の端数として 16 を足す。
116fn render_element_bytes(el: &RenderElement) -> usize {
117    #[inline]
118    fn s(x: &str) -> usize {
119        if x.is_empty() { 0 } else { x.len() + 16 }
120    }
121    #[inline]
122    fn v<T>(x: &[T]) -> usize {
123        if x.is_empty() { 0 } else { core::mem::size_of_val(x) + 16 }
124    }
125    core::mem::size_of::<RenderElement>()
126        + s(&el.text) + s(&el.href) + s(&el.element_id) + s(&el.onclick)
127        + s(&el.decoration_style) + s(&el.placeholder) + s(&el.img_alt)
128        + s(&el.video_src) + s(&el.video_poster) + s(&el.iframe_src)
129        + s(&el.input_value) + s(&el.radio_group) + s(&el.label_for)
130        + s(&el.form_action) + s(&el.form_method) + s(&el.list_style_image)
131        + s(&el.bg_clip) + s(&el.bg_origin) + s(&el.bg_attachment) + s(&el.background_blend_mode)
132        + el.bg_image.as_deref().map_or(0, s)
133        + el.marker_content.as_deref().map_or(0, s)
134        + v(&el.bg_images) + el.bg_images.iter().map(|x| s(x)).sum::<usize>()
135        + v(&el.select_options) + el.select_options.iter().map(|(a, b)| s(a) + s(b)).sum::<usize>()
136        + v(&el.bg_layers) + v(&el.box_shadow) + v(&el.stack_path) + v(&el.text_shadow)
137        + s(&el.before_content) + s(&el.after_content) + s(&el.font_family) + s(&el.before_font_family)
138        + s(&el.text_emphasis_style) + s(&el.cursor_style) + s(&el.scroll_container_id)
139        + s(&el.clip_path) + s(&el.outline_style) + s(&el.filter) + s(&el.mix_blend_mode)
140        + s(&el.backdrop_filter) + s(&el.image_rendering)
141}
142
143/// flatten_layout に渡る継承状態とスタッキング文脈のハッシュ。
144fn hash_flatten_inherited(
145    form_action: &str,
146    form_method: &str,
147    href: &str,
148    font_bold: bool,
149    font_italic: bool,
150    underline: bool,
151    line_through: bool,
152    color: Option<u32>,
153    font_size: u32,
154    parent_id: &str,
155    list_state: Option<(bool, u32)>,
156    parent_tag: &str,
157    decoration_color: Option<u32>,
158    decoration_style: &str,
159    decoration_thickness: i32,
160    decoration_underline_offset: i32,
161    overline: bool,
162    pointer_events_none: bool,
163    paint_z: i32,
164    paint_depth: u32,
165    positioned: bool,
166    pos_count: u32,
167    stack_prefix: &[super::paint_order::StackStep],
168) -> u64 {
169    let mut h = 0xcbf29ce484222325u64;
170    let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x100000001b3);
171    for s in [form_action, form_method, href, parent_id, parent_tag, decoration_style] {
172        mix(s.len() as u64);
173        for b in s.bytes() {
174            mix(b as u64);
175        }
176    }
177    mix(font_bold as u64);
178    mix(font_italic as u64);
179    mix(underline as u64);
180    mix(line_through as u64);
181    mix(color.unwrap_or(0) as u64);
182    mix(font_size as u64);
183    match list_state {
184        Some((is_ol, count)) => {
185            mix(1);
186            mix(is_ol as u64);
187            mix(count as u64);
188        }
189        None => mix(0),
190    }
191    mix(decoration_color.unwrap_or(0) as u64);
192    mix(decoration_thickness as u64);
193    mix(decoration_underline_offset as u64);
194    mix(overline as u64);
195    mix(pointer_events_none as u64);
196    mix(paint_z as u64);
197    mix(paint_depth as u64);
198    mix(positioned as u64);
199    mix(pos_count as u64);
200    // スタッキング文脈の段の列(seq は位置依存なので除外)
201    mix(stack_prefix.len() as u64);
202    for &(z, stage, _seq, depth) in stack_prefix {
203        mix(z as u64);
204        mix(stage as u64);
205        mix(depth as u64);
206    }
207    h
208}
209
210fn flatten_env_hash() -> u64 {
211    let vw = crate::os_lib::layout::VIEWPORT_HINT_W
212        .load(core::sync::atomic::Ordering::Relaxed) as u32 as u64;
213    let vh = crate::os_lib::layout::VIEWPORT_HINT_H
214        .load(core::sync::atomic::Ordering::Relaxed) as u32 as u64;
215    let rem = super::css_units::root_font_px().to_bits() as u64;
216    let fgen = crate::os_lib::layout::CUSTOM_FONT_GEN
217        .load(core::sync::atomic::Ordering::Relaxed) as u64;
218    let mut h = 0xcbf29ce484222325u64;
219    for v in [vw, vh, rem, fgen] {
220        h = (h ^ v).wrapping_mul(0x0000_0100_0000_01b3);
221    }
222    h
223}
224
225/// LayoutBox から StyledNode を取り出し部分木情報を計算。
226fn flatten_subtree_info(
227    layout: &crate::os_lib::layout::LayoutBox,
228) -> Option<(u64, u64, bool)> {
229    use crate::os_lib::layout::BoxType;
230    let styled = match &layout.box_type {
231        BoxType::BlockNode(n)
232        | BoxType::InlineNode(n)
233        | BoxType::InlineBlockNode(n)
234        | BoxType::FlexNode(n)
235        | BoxType::GridNode(n)
236        | BoxType::TableNode(n)
237        | BoxType::TableRowGroupNode(n)
238        | BoxType::TableRowNode(n)
239        | BoxType::TableCellNode(n) => *n,
240        BoxType::AnonymousBlock => return None,
241    };
242    Some(styled.layout_subtree_info())
243}
244
245/// `line-height`(丸ごと未対応だった単位あり。以前は `px`(絶対値)と裸数値
246/// (`font-size`への倍率。仕様どおり子要素へも同じ倍率が継承される)の2種
247/// のみ対応で、`%`(`line-height:150%`)/`em`(`line-height:1.5em`)は
248/// `t.parse::<f32>()`が単位付き文字列を数値としてパースできず静かに失敗し、
249/// `(font_size + 4)`という汎用フォールバック値へ落ちていた(エラーになら
250/// ず一見動いているように見えるため気づきにくいバグだった)。`%`/`em`は
251/// どちらも意味上「font-sizeへの倍率」で裸数値と等価のため、同じ倍率計算
252/// 式へ合流させる。2026-07-17 発見・実装(自己テストのため`parse_and_
253/// layout`内のネスト関数からモジュールトップレベルへ移動。ロジック不変)。
254pub(crate) fn parse_line_height(s: &str, font_size: u32) -> i32 {
255    let t = s.trim();
256    if let Some(num) = t.strip_suffix("px") {
257        if let Ok(px) = num.trim().parse::<f32>() {
258            return px as i32;
259        }
260    }
261    if let Some(num) = t.strip_suffix('%') {
262        if let Ok(pct) = num.trim().parse::<f32>() {
263            return (font_size as f32 * pct / 100.0) as i32;
264        }
265    }
266    if let Some(num) = t.strip_suffix("em") {
267        if let Ok(ratio) = num.trim().parse::<f32>() {
268            return (font_size as f32 * ratio) as i32;
269        }
270    }
271    if let Ok(ratio) = t.parse::<f32>() {
272        return (font_size as f32 * ratio) as i32;
273    }
274    (font_size + 4) as i32
275}
276
277/// `text-indent`(丸ごと未対応だった単位あり。以前は`px`と裸数値〔`px`
278/// 扱い〕のみ対応で、`%`(包含ブロック幅基準)/`em`(font-size基準)は
279/// `t.parse::<f32>()`が単位付き文字列を数値としてパースできず静かに
280/// 失敗し、インデント無し(0)へフォールバックしていた。古典的な段落
281/// インデントの定番`text-indent:2em`や、レスポンシブな`text-indent:5%`
282/// が効かなくなっていた(エラーにならず一見正常に描画されるため気づき
283/// にくいバグだった)。2026-07-17 発見・実装(自己テストのためモジュール
284/// トップレベル関数として新設。呼び出し元は1箇所のみ)。
285pub(crate) fn resolve_text_indent(s: &str, container_width: i32, font_size: u32) -> i32 {
286    super::css_units::resolve_text_indent(s, container_width, font_size)
287}
288
289/// `box-shadow`/`text-shadow`のオフセット/ぼかし長さトークンを解決する
290/// (丸ごと未対応だった単位あり。以前は`px`のみ対応で、`rem`(`box-shadow:
291/// 0.5rem 0.5rem 1rem red`のような相対単位指定)は`token.strip_suffix
292/// ("px")`に一致せず数値パースにも失敗するため、呼び出し元の位置カウンタ
293/// `px_count`が進まないまま静かに無視されていた——エラーにはならず`color`
294/// だけ正しく拾われるため、「オフセット0・ぼかし0の見えない影」という
295/// 気づきにくい壊れ方をしていた。`em`は要素自身の算出フォントサイズが
296/// この関数の引数だけでは解決できないため対象外のまま(`resolve_
297/// translate_len`と同じ判断)。2026-07-17 発見・実装(自己テストのため
298/// モジュールトップレベル関数として新設。呼び出し元は`box-shadow`/
299/// `text-shadow`の2箇所)。
300pub(crate) fn parse_shadow_len_tok_with_font(token: &str, font_px: f32) -> Option<i32> {
301    super::box_shadow::parse_len_with_font(token, font_px)
302}
303
304pub(crate) fn parse_shadow_len_tok(token: &str) -> Option<i32> {
305    super::box_shadow::parse_len(token)
306}
307
308/// `aspect-ratio`(CSS Box Sizing Level 4。`16 / 9`, `4/3`, `1`, `auto 16/9` 等)を解釈する。
309pub(crate) fn parse_aspect_ratio(val: &str) -> Option<f32> {
310    let s = val.trim().to_lowercase();
311    if s.is_empty() || s == "auto" || s == "none" {
312        return None;
313    }
314    let s_ref = if s.starts_with("auto ") {
315        s.trim_start_matches("auto ").trim()
316    } else {
317        s.as_str()
318    };
319    if let Some((num_str, den_str)) = s_ref.split_once('/') {
320        let num: f32 = num_str.trim().parse().ok()?;
321        let den: f32 = den_str.trim().parse().ok()?;
322        if den != 0.0 {
323            return Some(num / den);
324        }
325    } else if let Ok(v) = s_ref.parse::<f32>() {
326        if v > 0.0 {
327            return Some(v);
328        }
329    }
330    None
331}
332
333pub(crate) use crate::os_lib::layout::{
334    parse_pos_len, resolve_border_radius, resolve_border_radius_with_font,
335};
336
337/// DOM ツリーを走査して外部 `<link rel="stylesheet" href="...">` の href を集める。
338/// href は resolve_dom_paths 済み(絶対パス or 完全URL)。以前はインライン `<style>`
339/// しか集めておらず、外部 CSS ファイルを一切取得・適用していなかったため、CSS を
340/// 全て外部ファイルに置くサイト(一般的な構成)ではスタイルが丸ごと無視され、
341/// 素の HTML 同然の表示になっていた。`rel` に `stylesheet` を含むもの、または
342/// `rel` 未指定で href が `.css` で終わるものを対象とする(`preload`/`icon` 等は除外)。
343fn collect_external_css_urls(node: &crate::os_lib::dom::Node) -> alloc::vec::Vec<String> {
344    let mut out = alloc::vec::Vec::new();
345    fn walk(node: &crate::os_lib::dom::Node, out: &mut alloc::vec::Vec<String>) {
346        if let crate::os_lib::dom::NodeType::Element {
347            tag_name,
348            attributes,
349            ..
350        } = &node.node_type
351        {
352            if tag_name == "link" {
353                let rel = attributes
354                    .get("rel")
355                    .map(|s| s.to_lowercase())
356                    .unwrap_or_default();
357                let href = attributes.get("href").cloned().unwrap_or_default();
358                let is_css = rel.contains("stylesheet")
359                    || (rel.is_empty() && href.to_lowercase().ends_with(".css"));
360                if is_css && !href.is_empty() {
361                    out.push(href);
362                }
363            }
364        }
365        for child in &node.children {
366            walk(child, out);
367        }
368    }
369    walk(node, &mut out);
370    out
371}
372
373/// `<script type>` が JavaScript か(属性なし・空・JS の MIME タイプ・`module`)。
374pub(crate) fn is_js_script_type(t: Option<&str>) -> bool {
375    let Some(t) = t else { return true };
376    let t = t.trim().to_ascii_lowercase();
377    let essence = t.split(';').next().unwrap_or("").trim();
378    essence.is_empty()
379        || essence == "module"
380        || matches!(
381            essence,
382            "text/javascript"
383                | "application/javascript"
384                | "application/ecmascript"
385                | "application/x-ecmascript"
386                | "application/x-javascript"
387                | "text/ecmascript"
388                | "text/jscript"
389                | "text/livescript"
390                | "text/x-ecmascript"
391                | "text/x-javascript"
392                | "text/javascript1.0"
393                | "text/javascript1.1"
394                | "text/javascript1.2"
395                | "text/javascript1.3"
396                | "text/javascript1.4"
397                | "text/javascript1.5"
398        )
399}
400
401/// 数 MB になりうる `String` へ `add` バイト足す前の確保。倍にせず、少なくとも 1/4 ずつ伸ばす
402/// (外部 CSS を連結して 4MB を超えるとき、倍々で 8MB の一括確保になるのを避ける。TODO A7、2026-11-19)。
403fn reserve_gentle(s: &mut String, add: usize) {
404    if s.capacity() - s.len() >= add {
405        return;
406    }
407    if s.len() + add < 1024 * 1024 {
408        s.reserve(add);
409    } else {
410        let _ = s.try_reserve_exact(add.max(s.len() / 4));
411    }
412}
413
414/// DOM ツリーを走査して全 `<script>` 要素を集める。`src` 属性があれば
415/// (Some(resolved_src), "", is_module) を、無ければインライン本文 (None, text, is_module) を返す。
416/// 以前は生 HTML 文字列を正規表現的にスキャンするだけで、`<script src="...">` の
417/// 外部スクリプトは本文が空のため完全に無視されていた(fetch すら行われない)。
418fn collect_scripts_from_dom(node: &crate::os_lib::dom::Node) -> alloc::vec::Vec<(Option<String>, String, bool)> {
419    let mut out = alloc::vec::Vec::new();
420    fn walk(
421        node: &crate::os_lib::dom::Node,
422        out: &mut alloc::vec::Vec<(Option<String>, String, bool)>,
423    ) {
424        if let crate::os_lib::dom::NodeType::Element {
425            tag_name,
426            attributes,
427            ..
428        } = &node.node_type
429        {
430            if tag_name == "script" {
431                // JS 以外(`application/json`・`application/ld+json`・テンプレート等)はデータ
432                // ブロックなので実行しない(HTML の「script の種類」の判定)。
433                // 【2026-10-17】従来は type を見ずに全部 JS として実行し、YouTube の JSON ブロックで
434                // 構文エラーを出していた。
435                let ty = attributes.get("type").map(|s| s.as_str());
436                if !is_js_script_type(ty) {
437                    return;
438                }
439                let is_module = ty
440                    .map(|t| t.trim().to_ascii_lowercase().split(';').next().unwrap_or("").trim() == "module")
441                    .unwrap_or(false);
442                if let Some(src) = attributes.get("src") {
443                    if !src.is_empty() {
444                        out.push((Some(src.clone()), String::new(), is_module));
445                        return;
446                    }
447                }
448                let mut text = String::new();
449                for child in &node.children {
450                    if let crate::os_lib::dom::NodeType::Text(t) = &child.node_type {
451                        text.push_str(t);
452                    }
453                }
454                out.push((None, text, is_module));
455                return;
456            }
457        }
458        for child in &node.children {
459            walk(child, out);
460        }
461    }
462    walk(node, &mut out);
463    out
464}
465
466impl super::WebEngine {
467    /// このタブだけを止める合図でレイアウトを途中でやめたときの後始末(TODO R2 (d) ①、2026-11-18)。
468    ///
469    /// 巻き戻しはしない。スタイル・箱・要素の組み立ては合図を見ると残りの子を飛ばして普通に戻るので、
470    /// 途中までの木・要素の列がそのまま残る。このタブはアプリのスレッドの次の 1 周の頭で捨てられる(`take_tab_kill`)。
471    /// 念のため(合図を見落とす隙間・捨てられなかった場合):
472    /// - 途中までの結果が入りうる使い回しの表(このタブのスタイルの表・大域の箱と要素の表)を空にする
473    ///   (合図の後は表に入れないが、合図を見る `try_lock` が外れた回だけ入りうる)。
474    /// - 捨てられずに残ったら組み直すよう、DOM の組み直しと再レイアウトの待ちを立てる。
475    fn abandon_layout_for_tab_kill(&mut self, stage: &str) {
476        // 【2026-11-18 TODO R5 (c)】ウィンドウごと止める要求で再帰を戻らせてきたのなら、ここで終わらせる
477        // (作りかけの大きな物は `kill_owned` の箱にあり、止めるときに解放される)。
478        crate::kernel::window_mgr::kill_checkpoint();
479        self.style_memo.clear();
480        crate::os_lib::layout::clear_layout_memo();
481        clear_flatten_memo();
482        self.dom_needs_rebuild = true;
483        let now = crate::kernel::timer::get_ticks();
484        self.pending_reflow_since = now.max(1);
485        self.pending_reflow_last = now;
486        self.dirty = true;
487        self.dirty_reason = "layout.rs:tab_kill_abandon";
488        crate::warn!("[WM] このタブだけ止める合図で、レイアウトを{}の途中でやめた(要素 {} 個まで)", stage, self.elements.len());
489    }
490
491    /// CSS の解析の途中でやめたときの後始末(2026-11-18、TODO R2 (b) ②)。途中までの規則が入りうる
492    /// このタブの CSS の表(外部 CSS・`<style>` の解析結果・規則の索引)を空にしてから、[`Self::abandon_layout_for_tab_kill`] を呼ぶ。
493    fn abandon_css_for_tab_kill(&mut self) {
494        self.external_css_cache = None;
495        self.external_css_counts = None;
496        self.cached_stylesheet = None;
497        self.cached_rule_index = None;
498        self.cached_css_hash = None;
499        self.inline_style_memo.clear();
500        self.abandon_layout_for_tab_kill("CSS の解析");
501    }
502
503    /// 計算量: **O(H + R×Sel + N×(C×M + K) + N×D)**
504    ///
505    /// - H: HTML バイト数(パース)
506    /// - R×Sel: CSS ルール索引の構築
507    /// - N×(C×M + K): `style_tree`(下記参照)
508    /// - N×D: `layout_tree`
509    ///
510    /// 下層の積み上げ(規約は `spec/complexity_annotation.md`):
511    /// `rule_index::active_candidates` O(1+C) → `style_tree` O(R×Sel + N×(C×M+K))
512    /// → ここ。
513    ///
514    /// 実測(sugi-lab.net: N=358, R=2403、計 607 tick ≒ 6 秒):
515    ///
516    /// | 段 | tick |
517    /// |----|------|
518    /// | CSS 取得(キャッシュ命中時) | 23 |
519    /// | `style_tree` | 291 |
520    /// | `layout_tree` | 60 |
521    ///
522    /// **`style_tree` の中ではセレクタ照合ではなくノードごとの固定コスト K
523    /// (継承マップ等の複製)が支配的**。照合は索引で全体の 2.0% まで落ちている。
524    pub fn parse_and_layout(
525        &mut self,
526        html: &str,
527        pre_parsed_dom: Option<crate::os_lib::dom::Node>,
528        top_offset: i32,
529        win_w: u32,
530        win_h: u32,
531    ) {
532        // 閉じられた/強制終了されたアプリは、組み直しを始める前に止める(TODO R2)。
533        crate::kernel::window_mgr::kill_checkpoint();
534        crate::debug!("[GPU] TRACE: parse_and_layout enter. len={}", html.len());
535        // {
536        //     let mut head = 200.min(html.len());
537        //     while head > 0 && !html.is_char_boundary(head) {
538        //         head -= 1;
539        //     }
540        //     crate::println!("[CSSDBG] recv HTML len={} head200={:?}", html.len(), html.get(..head).unwrap_or(""));
541        // }
542
543        // 上限を超える巨大ページは UTF-8 境界で安全に切り捨てる(ヒープ枯渇の予防)。
544        let html = if html.len() > MAX_HTML_BYTES {
545            let mut cut = MAX_HTML_BYTES;
546            while cut > 0 && !html.is_char_boundary(cut) {
547                cut -= 1;
548            }
549            crate::info!("[GPU] WEB_ENGINE: HTML truncated {} -> {} bytes", html.len(), cut);
550            html.get(..cut).unwrap_or(html)
551        } else {
552            html
553        };
554
555        crate::debug!("[GPU] TRACE: parse_and_layout allocating self.last_html");
556        // 新ページ読込(dom_needs_rebuild)でのみ画像キャッシュを破棄する。
557        // JS による textContent/style 変更などのインクリメンタル再レイアウトでは
558        // 画像を保持し、毎回の再フェッチ暴走(同じ src の再ダウンロード)を防ぐ。
559        let is_new_page = self.dom_needs_rebuild || self.last_html != html;
560        // 【2026-08-03】スクロール位置をリセットしてよいのは
561        // **文書そのものが変わったとき**だけ。
562        //
563        // `is_new_page` は `dom_needs_rebuild` でも真になる。しかし
564        // `dom_needs_rebuild` は `:target` の再判定やフォント到着など
565        // 「同じ文書の作り直し」でも立つ。これでスクロールを 0 に戻すと、
566        // `#id` アンカーへスクロールした直後に先頭へ引き戻されてしまう
567        // (実測: `[NAV] フラグメントへスクロール #research` は発火するのに
568        //  画面は先頭のままだった)。
569        let is_document_changed = self.last_html != html;
570        self.last_html = String::from(html);
571        // 【2026-08-05 修正】キャッシュを捨ててよいのは
572        // **文書そのものが変わったとき**だけ。
573        //
574        // `is_new_page` は `dom_needs_rebuild` でも真になるが、
575        // このフラグはフォント/画像の到着による「同じ文書の作り直し」でも立つ。
576        // それでキャッシュを消すと、届いた画像が捨てられて無限に取り直しになる
577        // (実測: 同じ画像が 2 回デコードされ、`#projects` の画像が
578        //  alt テキストのままだった)。
579        //
580        // 逆にキャッシュを守るために `dom_needs_rebuild` を立てないようにすると、
581        // DOM ブリッジが組み直されず**要素の位置が壊れる**
582        // (実測: ヒーローのグラデーションが全ページに掛かった)。
583        //
584        // 正しくは「DOM は組み直す・キャッシュは残す」。両者を分ける。
585        if is_document_changed {
586            crate::debug!("[GPU] TRACE: parse_and_layout clearing image_cache (new page)");
587            self.image_cache = alloc::collections::BTreeMap::new();
588            // 共有の置き場も一緒に捨てる(同じ画素を指しているため)。
589            super::image::clear_shared_images();
590            self.image_attempted = alloc::collections::BTreeSet::new();
591            self.scroll_regions = alloc::collections::BTreeMap::new();
592            self.dynamic_scripts.clear();
593            // 【2026-07-24発見・修正】`external_css_cache`はページ遷移開始時
594            // (`load_url`/`load_html`)に`None`へリセットされるが、実際の
595            // ページ内容が届くまでの待機中に旧ページ(プレースホルダー等)の
596            // 内容で毎フレーム`parse_and_layout`が呼ばれ続けるため、実ページの
597            // HTMLが届く前に`Some(旧ページのCSS)`で埋まってしまい、実ページの
598            // 実際の`<link>`が一度も取得されないまま丸ごとスキップされる重大な
599            // バグだった(`is_new_page`(内容変化検知)の度に確実に空へ戻す)。
600            self.external_css_cache = None;
601        }
602        // scroll_containers はページ再レイアウトのたびに再構築する。
603        self.scroll_containers = alloc::vec::Vec::new();
604        crate::debug!("[GPU] TRACE: parse_and_layout clearing elements");
605        self.elements = Vec::new();
606        self.elements_gen = self.elements_gen.wrapping_add(1);
607        self.links = Vec::new();
608        self.page_bg_color = None;
609        self.page_text_color = None;
610        self.selection_style = super::selection_style::SelectionStyle::default();
611        crate::debug!("[GPU] TRACE: parse_and_layout setting title");
612        self.title = String::from("Untitled Page");
613        self.focused_id = None;
614        self.active_text_box = None;
615        self.win_w = win_w;
616        self.win_h = win_h;
617        self.top_offset = top_offset;
618
619        crate::debug!("[GPU] TRACE: parse_and_layout start");
620        // 1. DOM パーサ。
621        // DOM ブリッジが既に構築済み(built)かつ JS 変更で dirty な場合、最終的な
622        // 描画ツリーはブリッジの to_dom_node() から作る。その場合 parse_html の結果は
623        // 破棄されるため、再パース自体を省略して確保コストを削る。
624        // ブリッジ未構築 or 新ページ(再構築要求)時のみ HTML を実際にパースする。
625        // 【2026-10-05】同じ文書の再レイアウト(フォント・CSS の到着、`:target`、サイズ変更)では
626        // **常にブリッジ(JS から見える DOM)を描画の元にする**。従来は JS が変更した直後の 1 回
627        // (`dirty`)だけブリッジを使い、それ以外は HTML から作り直していたため、JS が組み立てた
628        // 内容(sugi-lab.net/papers.htm の論文リスト)がフォント到着時の再レイアウトで消えていた。
629        // 以前はその度にスクリプトを再実行して作り直していたので表示上は辻褄が合っていた。
630        // ナビゲーション直後(`scripts_ran_for == None`)と文書が変わったときは HTML から。
631        let is_navigation = self.scripts_ran_for.is_none();
632        let bridge_is_source = {
633            let dom = self.js_runtime.dom().clone();
634            let b = dom.borrow();
635            b.built && !is_document_changed && !is_navigation
636        };
637        // 【2026-08-05 計測】再レイアウト 1 回が実測 4.6 秒かかる。
638        // `style_tree` は 24〜200 tick なので主役ではない。
639        // どの段が重いのかを段ごとに測る(推測で手を入れないため)。
640        // 目的: 再レイアウトの律速の特定。破棄条件: 特定でき次第削除。
641        let t_stage0 = crate::kernel::timer::get_ticks();
642        // 【2026-11-18 TODO R2 (c) ③】組み立て中の DOM・スタイルの木・レイアウトの木は `kill_owned` の箱に入れる。
643        // この関数の中(字幅の計測・フォントの取得)でアプリが止められると、巻き戻し無しでスレッドが終わり、
644        // 関数の中の変数は解放されない(3MB の文字の塊のページで約 140MB が残った)。箱に入れておけば、止めるときに解放される。
645        let mut root_node = crate::kernel::window_mgr::kill_owned(if bridge_is_source {
646            // ブリッジから後で差し替えるので、ここでは空ルートで十分。
647            crate::os_lib::dom::Node::empty_root()
648        } else if let Some(dom) = pre_parsed_dom {
649            dom
650        } else {
651            // 【2026-11-18 TODO R2 (b) ②】HTML の解析の途中でも止める確かめを呼ぶ(ここは錠を持っていない)。
652            crate::os_lib::dom::parse_html_app(html)
653        });
654        let _t_html_end = crate::kernel::timer::get_ticks();
655        // このタブだけ止める合図なら、途中までの木でここでやめる(DOM ブリッジに入れない)。
656        if crate::kernel::window_mgr::layout_check() {
657            self.abandon_layout_for_tab_kill("HTML の解析");
658            return;
659        }
660        crate::debug!(
661            "[GPU] TRACE: parse_html done (bridge_source={})",
662            bridge_is_source
663        );
664
665        // 相対パスの解決(実際に HTML をパースした時のみ意味がある)。
666        if !bridge_is_source {
667            let base_path = get_base_path(&self.current_path);
668            resolve_dom_paths(&mut root_node, &base_path);
669        }
670
671        // DOM ブリッジ: 新ページなら再構築。以降は **ブリッジを真実源**として描画ツリーを
672        // 生成する(textContent/style/class の変更に加え、createElement/appendChild 等の
673        // 動的ノードも反映される)。
674        {
675            // 【2026-11-18 TODO R5 (c)】`Rc` を写さずに借りる。写した `Rc` はこの関数の中の変数なので、ここで
676            // アプリが止められる(止める確かめ・確保の失敗の panic)と巻き戻し無しで残り、アプリ本体(JS の実行環境)を
677            // 解放しても DOM ブリッジ(4MB の HTML で約 170MB)が数え残りで解放されなかった。
678            let mut b = self.js_runtime.dom().borrow_mut();
679            // 【2026-07-24発見・修正】コメントは「新ページなら再構築」と書いてあった
680            // にもかかわらず、実際の条件は`is_new_page`を一切見ていなかった。
681            // このため、プレースホルダー(ロード中表示)ページで一度ブリッジが
682            // 構築された(`built=true`)後、実ページのHTMLが届いて`root_node`が
683            // 正しく最新の内容(例: 365要素)に切り替わっても、`dom_needs_rebuild`
684            // が別途明示的に立てられない限りブリッジは古いプレースホルダーの
685            // ノード(例: 33ノード)のまま据え置かれていた。結果、`document.body`/
686            // `querySelector`等JS側から見えるDOMは常に古いページの内容のままとなり、
687            // 実サイトの`js/modern-script.js`が`document.querySelector('.nav-list')`
688            // で`null`を受け取り`Cannot read properties of null (reading 'style')`
689            // で即座に停止する原因になっていた(レンダリング用ツリーは正しかった
690            // ため、この不一致は画面には出ず、JS実行時エラーとしてのみ表れていた)。
691            // `external_css_cache`(同セッションで既に発見・修正済み)と全く同じ
692            // 「プレースホルダー状態のキャッシュが実ページ到着後も無効化されない」
693            // というバグクラスの再発。
694            if !bridge_is_source && (self.dom_needs_rebuild || !b.built || is_new_page) {
695                b.build_from(&root_node); // この後 dirty=false(止める合図で途中でやめたら built=false のまま)
696                self.dom_needs_rebuild = false;
697                // 新ページ: アニメーション状態を全てリセット。
698                self.anim_engine.clear();
699                self.anim_specs.clear();
700                self.anim_prev_values.clear();
701                if b.built {
702                    // 【2026-11-18 TODO R5 (c)】解析の木を先に手放してから、ブリッジから描画用の木を作る
703                    // (以前は新しい木を作り終えるまで古い木も持っていたので、木 2 本ぶんが同時に要った)。
704                    *root_node = crate::os_lib::dom::Node::empty_root();
705                    *root_node = b.to_dom_node();
706                }
707            }
708            // JS が DOM を実際に変更した時だけブリッジから全ツリーを再構築する。
709            // 静的ページや、JS 変更の無いサイズ変更再レイアウトでは to_dom_node の
710            // ツリー全クローン(重い)を省略でき、確保回数を大幅に削減する。
711            if bridge_is_source {
712                self.dom_needs_rebuild = false;
713            }
714            if b.built && (b.dirty || bridge_is_source) {
715                *root_node = b.to_dom_node();
716                // dirty をここでクリア(遅延クリア)。relayout_if_dom_dirty が
717                // dirty を消す前に parse_and_layout へ到達できるよう、to_dom_node()
718                // 呼び出し後にクリアして無限ループを防ぐ。
719                b.clear_dirty();
720            }
721        }
722        // 【2026-11-18 TODO R2 (b) ②】DOM ブリッジの組み立て(`build_from`・`to_dom_node`)も中で止める確かめを呼ぶ。
723        // このタブだけ止める合図なら、途中までの木でここでやめる。
724        if crate::kernel::window_mgr::layout_check() {
725            self.abandon_layout_for_tab_kill("DOM ブリッジの組み立て");
726            return;
727        }
728
729        // 1.5 文書タイトル(タブ名・ウィンドウ名)。
730        // 【2026-10-04 修正】以前は上で "Untitled Page" を入れるだけで `<title>` を
731        // 読む処理が無く、どのサイトもタブ名が "Untitled Page" のままだった。
732        // ここは JS 変更後の再レイアウトでも通るので、`document.title = ...` で
733        // 書き換えた値も次の再レイアウトで反映される。
734        if let Some(t) = super::doc_title::document_title(&root_node) {
735            self.title = t;
736        }
737
738        // 2. CSS スタイリング(<style> ... </style> を抽出して適用)。
739        // root_node(ページ初回は静的パース結果、以降は DOM ブリッジ再構築後のツリー)を
740        // 直接走査して <style> の textContent を集める。生 HTML 文字列の再スキャンではなく
741        // 実際のツリーを見ることで、`document.createElement('style')` 等で動的に追加された
742        // <style> 要素のスタイルも反映される(以前は元の HTML 文字列しか見ておらず、
743        // 動的なスタイル注入が完全に無視されるバグだった)。
744        // インクリメンタル再レイアウトでキャッシュを効かせるため、抽出結果を文字列キーにする
745        // 点は従来どおり(同一なら parse_css を丸ごと省略)。
746        // 外部 <link rel=stylesheet> の CSS を初回だけ取得してキャッシュする
747        // (毎フレームの再取得を防ぐ。詳細は external_css_cache のコメント参照)。
748        let mut unpersisted_ext: Option<String> = None;
749        if self.external_css_cache.is_none() {
750            // fn dbg_count(node: &crate::os_lib::dom::Node, tag: &str) -> usize {
751            //     let mut n = 0;
752            //     if let crate::os_lib::dom::NodeType::Element { tag_name, .. } = &node.node_type {
753            //         if tag_name == tag {
754            //             n += 1;
755            //         }
756            //     }
757            //     for c in &node.children {
758            //         n += dbg_count(c, tag);
759            //     }
760            //     n
761            // }
762            // crate::println!(
763            //     "[CSSDBG] tags html={} head={} body={} link={} script={} style={}",
764            //     dbg_count(&root_node, "html"),
765            //     dbg_count(&root_node, "head"),
766            //     dbg_count(&root_node, "body"),
767            //     dbg_count(&root_node, "link"),
768            //     dbg_count(&root_node, "script"),
769            //     dbg_count(&root_node, "style"),
770            // );
771            let urls = collect_external_css_urls(&root_node);
772            // crate::println!("[CSSDBG] external <link> css found: {}", urls.len());
773            let mut ext = String::new();
774            // 【2026-08-25 バグ修正】1 本でも取れなかったら**保存しない**。
775            // 保存条件を厳しくする代わりに、呼び出し側の無条件破棄をやめる。
776            let mut all_fetched = true;
777            for url in &urls {
778                // crate::println!("[CSSDBG] fetching external css {}", url);
779                if let Some(text) = self.fetch_script_text(url) {
780                    // crate::println!("[CSSDBG] fetched {} bytes", text.len());
781                    let abs_url = self.resolve_page_url(url);
782                    let rewritten = super::url_resolve::rewrite_css_urls(&text, &abs_url);
783                    // 【2026-07-25発見・修正】TLS読み取りエラー等でCSSが波括弧の
784                    // 途中で打ち切られたまま後続CSSと連結されると、閉じられなかった
785                    // `{`のせいでパーサーが以降の本物のルールを大量に読み飛ばす
786                    // 重大バグだった(`rules.len()`が2000超のはずが122まで激減する
787                    // 事例で発見)。バランスの取れた最後のトップレベルルールまでに
788                    // 安全側で切り詰めてから連結する。
789                    let balanced = super::url_resolve::truncate_to_balanced_css(&rewritten);
790                    if balanced.len() != rewritten.len() {
791                        // 【2026-08-03 復旧】CSS を途中で切り詰めた事実は
792                        // **異常として残す**(`spec/logging_policy.md` L-1)。
793                        // 一括でログ整理したとき誤って消してしまい、
794                        // 空の if だけが残っていた。
795                        // 切り詰めが起きるとルールが丸ごと欠落し、
796                        // 「なぜかスタイルが当たらない」という形で表面化する。
797                        crate::warn!(
798                            "[CSS] 不完全な CSS を切り詰めた url={} {} -> {} バイト",
799                            url,
800                            rewritten.len(),
801                            balanced.len()
802                        );
803                    }
804                    reserve_gentle(&mut ext, balanced.len() + 1);
805                    ext.push_str(balanced);
806                    ext.push('\n');
807                } else {
808                    // crate::println!("[CSSDBG] fetch FAILED {}", url);
809                    all_fetched = false;
810                }
811            }
812            // crate::warn!("[CSSTRACE] 抽出 ext_len={}", ext.len());
813            // 【2026-08-25 バグ修正】以前はここで**無条件に**保存していた。
814            //
815            // 非同期取得では初回に間に合わない CSS があり、空や欠けた
816            // 結果がそのまま居座る。その対策として呼び出し側
817            // (`render.rs` の到着による再レイアウト)が毎回
818            // `external_css_cache = None` で捨てていたが、これは
819            // **全部取り直す**という意味になる。実際、フォントや画像が
820            // 届くたびに外部 CSS を再取得してページを組み直しており、
821            // 背景写真と本文フォントが間に合う前に描き直されていた
822            // (実測 4 回中 2 回、`total=13` に届かず `total=9` で静止)。
823            //
824            // 直し方は `cache::write_cache` と同じで、
825            // **捨てる側ではなく入れる側を守る**。
826            // 全部揃ったときだけ保存すれば、欠けたものは
827            // 次の機会に自然に取り直され、揃ったものは使い回される。
828            if all_fetched {
829                // 【2026-10-19】外部 CSS はここで 1 回だけ解析して `cached_stylesheet` の
830                // 先頭に置き、生の文字列(YouTube で 4.4MB)は手放す。従来は生の文字列を
831                // `external_css_cache` と `cached_css_key` に二重で抱えた上、JS が小さな
832                // `<style>`(1.7KB)を足すたびに 4.4MB 全体を再解析し、さらに `s.clone()` で
833                // 2.3 万ルール(約 40MB)を複製してヒープが +87MB 跳ね上がっていた。
834                let _pp = super::perf::start();
835                let mut ext_layers = alloc::vec::Vec::new();
836                // 【2026-11-18 TODO R2 (b) ②】大きい CSS(YouTube で 4.4MB)の解析の途中でも止める確かめを呼ぶ(錠を持っていない所)。
837                let ext_sheet = crate::os_lib::css::parse_css_with_layers_poll(
838                    &ext,
839                    &mut ext_layers,
840                    &mut crate::kernel::window_mgr::layout_check,
841                );
842                super::perf::add(super::perf::Slot::CssParse, _pp);
843                drop(ext);
844                // このタブだけ止める合図なら、途中までの規則を表に入れずにやめる。
845                if crate::kernel::window_mgr::layout_aborting() {
846                    self.abandon_css_for_tab_kill();
847                    return;
848                }
849                self.external_css_counts = Some((
850                    ext_sheet.rules.len(),
851                    ext_sheet.keyframes.len(),
852                    ext_sheet.counter_styles.len(),
853                    ext_sheet.font_faces.len(),
854                    ext_layers,
855                ));
856                self.cached_stylesheet = Some(alloc::rc::Rc::new(ext_sheet));
857                let page_url = alloc::format!(
858                    "{}{}{}",
859                    if self.current_is_https { "https://" } else { "http://" },
860                    self.current_host,
861                    self.current_path
862                );
863                self.external_css_parsed = urls
864                    .iter()
865                    .map(|u| {
866                        let resolved = super::url_resolve::resolve_url(&page_url, u.trim());
867                        let (_, host, path) =
868                            super::url_resolve::split_target(&resolved, page_url.starts_with("https://"), "");
869                        (host, path)
870                    })
871                    .collect();
872                self.cached_rule_index = None;
873                self.cached_css_hash = None;
874                self.external_css_cache = Some(String::new());
875            } else {
876                crate::warn!(
877                    "[CSS] 取得できない外部CSSがあるので保存しない(次回取り直す) 総数={}",
878                    urls.len()
879                );
880                self.external_css_cache = None;
881                self.external_css_counts = None;
882                unpersisted_ext = Some(ext);
883            }
884        }
885        // カスケード順は文書順(<link> は通常 <head>、<style> はその後)に合わせ、
886        // 外部 CSS を先、インライン <style> を後に連結する。
887        let collected_inline = super::inline_style_cache::collect_style_blocks(&root_node);
888        // スタイルシートが前回と同じ(キャッシュ命中)なら、規則の索引も作り直さない。
889        let mut sheet_reused = false;
890        let stylesheet: alloc::rc::Rc<crate::os_lib::css::StyleSheet> =
891            if let Some((r_len, kf_len, cs_len, ff_len, ref ext_layers)) = self.external_css_counts
892            {
893                let _pk = super::perf::start();
894                let key_hit = self.cached_stylesheet.is_some()
895                    && self.cached_css_hash == Some(collected_inline.combined_hash);
896                super::perf::add(super::perf::Slot::CssKeyCmp, _pk);
897                // crate::warn!(
898                //     "[CSSTRACE] inline_len={} blocks={} 解析キャッシュ命中={} 既存ルール数={}",
899                //     collected_inline.total_bytes,
900                //     collected_inline.blocks.len(),
901                //     key_hit,
902                //     self.cached_stylesheet.as_ref().map(|s| s.rules.len()).unwrap_or(0)
903                // );
904                if let (true, Some(cached)) = (key_hit, self.cached_stylesheet.as_ref()) {
905                    crate::debug!("[GPU] TRACE: parse_css cache hit");
906                    sheet_reused = true;
907                    cached.clone()
908                } else {
909                    let _pp = super::perf::start();
910                    let inl = self
911                        .inline_style_memo
912                        .resolve_blocks(&collected_inline.blocks, ext_layers);
913                    super::perf::add(super::perf::Slot::CssParse, _pp);
914                    let mut sheet_rc = self
915                        .cached_stylesheet
916                        .take()
917                        .unwrap_or_else(|| alloc::rc::Rc::new(crate::os_lib::css::parse_css("")));
918                    // 【2026-11-07 最適化】インライン `<style>` の生文字列が変わっても(空白・コメント・
919                    // 空の `<style>` の増減や同一内容での入れ替え)、解析後の規則列と定義が前回と
920                    // 完全一致する場合は、`cached_rule_index` と `style_memo` を破棄せず再利用する。
921                    let inline_rules_identical = sheet_rc.rules.get(r_len..) == Some(inl.rules.as_slice())
922                        && sheet_rc.keyframes.get(kf_len..) == Some(inl.keyframes.as_slice())
923                        && sheet_rc.counter_styles.get(cs_len..) == Some(inl.counter_styles.as_slice())
924                        && sheet_rc.font_faces.get(ff_len..) == Some(inl.font_faces.as_slice());
925                    if inline_rules_identical && self.cached_rule_index.is_some() {
926                        sheet_reused = true;
927                        self.cached_css_hash = Some(collected_inline.combined_hash);
928                        self.cached_stylesheet = Some(sheet_rc.clone());
929                        sheet_rc
930                    } else {
931                        let sheet = alloc::rc::Rc::make_mut(&mut sheet_rc);
932                        sheet.rules.truncate(r_len);
933                        sheet.keyframes.truncate(kf_len);
934                        sheet.counter_styles.truncate(cs_len);
935                        sheet.font_faces.truncate(ff_len);
936                        sheet.rules.extend(inl.rules);
937                        sheet.keyframes.extend(inl.keyframes);
938                        sheet.counter_styles.extend(inl.counter_styles);
939                        sheet.font_faces.extend(inl.font_faces);
940                        self.cached_css_hash = Some(collected_inline.combined_hash);
941                        self.cached_stylesheet = Some(sheet_rc.clone());
942                        sheet_rc
943                    }
944                }
945            } else {
946                let mut combined = unpersisted_ext.unwrap_or_default();
947                reserve_gentle(&mut combined, collected_inline.blocks.iter().map(|b| b.text.len() + 1).sum());
948                for blk in &collected_inline.blocks {
949                    combined.push_str(blk.text.as_ref());
950                    combined.push('\n');
951                }
952                let _pp = super::perf::start();
953                let s = alloc::rc::Rc::new(crate::os_lib::css::parse_css_with_layers_poll(
954                    &combined,
955                    &mut alloc::vec::Vec::new(),
956                    &mut crate::kernel::window_mgr::layout_check,
957                ));
958                super::perf::add(super::perf::Slot::CssParse, _pp);
959                s
960            };
961        // 【2026-11-18 TODO R2 (b) ②】CSS の解析(外部・`<style>`)の途中で、このタブだけ止める合図が来ていればここでやめる。
962        if crate::kernel::window_mgr::layout_check() {
963            self.abandon_css_for_tab_kill();
964            return;
965        }
966
967        // 【2026-08-03 発見・修正】`@font-face` の取り込みを
968        // **CSS キャッシュがミスしたときだけ**に限定していた。
969        //
970        // 「ネットワーク往復を伴うから」という理由で 2026-07-22 に入れた制限だが、
971        // その後フォント取得は非同期(`font_queue`)+キャッシュ優先になり、
972        // 前提が崩れていた。結果として:
973        //
974        // 1. 初回レイアウト: フォントは未取得なので `Pending`(登録できない)
975        // 2. 背景スレッドが取得完了してキャッシュへ保存
976        // 3. 再レイアウト: **CSS はキャッシュ命中するのでここが呼ばれない**
977        //
978        // → 取得できているのに**同一ブート内で永久に登録されない**。
979        //    実測: 8 本取得成功・`registered=` は 0 件。
980        //
981        // 毎レイアウト呼んでも安全かつ安価:
982        // - 登録済みファミリは `has_custom_font` で即スキップ
983        // - 未取得のものは `font_queue` の `seen` で重複投入されない
984        // - キャッシュ命中したものだけが実際に登録される
985        crate::debug!("[GPU] TRACE: parse_css done");
986        let t_after_css = crate::kernel::timer::get_ticks();
987
988        // `:focus-within` 判定用: 現在フォーカス中の要素自身とその祖先すべてのノード
989        // ポインタアドレスを再計算する(id ではなくノード実体の同一性で判定するため、
990        // id を持たない要素も正しく機能する)。
991        {
992            fn collect_focus_within_path(
993                node: &crate::os_lib::dom::Node,
994                focused_id: &str,
995                path: &mut alloc::vec::Vec<usize>,
996            ) -> bool {
997                path.push(node as *const _ as usize);
998                if let crate::os_lib::dom::NodeType::Element { id, .. } = &node.node_type {
999                    if id.as_deref() == Some(focused_id) {
1000                        return true;
1001                    }
1002                }
1003                for child in &node.children {
1004                    if collect_focus_within_path(child, focused_id, path) {
1005                        return true;
1006                    }
1007                }
1008                path.pop();
1009                false
1010            }
1011            let mut set = crate::os_lib::viewport::FOCUS_WITHIN_PTRS.lock();
1012            set.clear();
1013            if let Some(fid) = &self.focused_id {
1014                let mut path = alloc::vec::Vec::new();
1015                if collect_focus_within_path(&root_node, fid, &mut path) {
1016                    set.extend(path);
1017                }
1018            }
1019        }
1020
1021        // `:lang()` 判定用: <html lang="..."> の値を文書既定言語として記録する
1022        // (要素自身に lang 属性が無い場合のフォールバックとして使う)。
1023        {
1024            fn find_html_lang(node: &crate::os_lib::dom::Node) -> Option<alloc::string::String> {
1025                if let crate::os_lib::dom::NodeType::Element {
1026                    tag_name,
1027                    attributes,
1028                    ..
1029                } = &node.node_type
1030                {
1031                    if tag_name == "html" {
1032                        if let Some(l) = attributes.get("lang") {
1033                            return Some(l.to_lowercase());
1034                        }
1035                    }
1036                }
1037                for child in &node.children {
1038                    if let Some(l) = find_html_lang(child) {
1039                        return Some(l);
1040                    }
1041                }
1042                None
1043            }
1044            let mut doc_lang = crate::os_lib::viewport::DOCUMENT_LANG.lock();
1045            *doc_lang = find_html_lang(&root_node).unwrap_or_default();
1046        }
1047
1048        // 【2026-07-31計測】レイアウト 1 回が 32〜40 秒かかる原因を切り分ける。
1049        // どの段が重いのか推測で手を入れないため、段ごとの tick を測る。
1050        let _t_css_end = crate::kernel::timer::get_ticks();
1051        let _t_style_start = crate::kernel::timer::get_ticks();
1052        // 【2026-08-05】非同期版で `style_tree` が完了しない件の切り分け。
1053        // 同期版と**渡る木そのものが違う**のではないかを確かめる。
1054        // 木が壊れて(循環して)いれば走査は終わらない。
1055        // 深さは上限を設けて数える(循環していても数え終わる)。
1056        // {
1057        //     fn count(n: &crate::os_lib::dom::Node, depth: usize, limit: usize) -> (usize, usize) {
1058        //         if depth >= limit {
1059        //             return (1, depth);
1060        //         }
1061        //         let mut total = 1usize;
1062        //         let mut maxd = depth;
1063        //         for c in &n.children {
1064        //             let (t, d) = count(c, depth + 1, limit);
1065        //             total += t;
1066        //             if d > maxd {
1067        //                 maxd = d;
1068        //             }
1069        //         }
1070        //         (total, maxd)
1071        //     }
1072        //     let (nodes, depth) = count(&root_node, 0, 200);
1073        //     crate::warn!(
1074        //         "[CSSTRACE] カスケード開始 ルール数={} ノード数={} 深さ={}",
1075        //         stylesheet.rules.len(),
1076        //         nodes,
1077        //         depth
1078        //     );
1079        // }
1080        let rule_index = match (sheet_reused, self.cached_rule_index.clone()) {
1081            (true, Some(ix)) => ix,
1082            _ => {
1083                self.style_memo.clear();
1084                let ix = alloc::rc::Rc::new(crate::os_lib::css::rule_index::RuleIndex::build(&stylesheet.rules));
1085                // 外部 CSS を持つ(スタイルシートをキャッシュしている)ときだけ索引も残す。
1086                self.cached_rule_index = self.external_css_counts.is_some().then(|| ix.clone());
1087                ix
1088            }
1089        };
1090        {
1091            let mut dom = self.js_runtime.dom().borrow_mut();
1092            dom.css_referenced_attrs = Some(rule_index.referenced_attrs().clone());
1093        }
1094        // 【2026-11-04】前回の結果を使い回す(TODO A8)。確かめる版(`verify = true`: 当たっても計算し直して比べる)で
1095        // YouTube の視聴ページを 300 秒回し、約 4,900 要素・16 回の再レイアウトで食い違い 0 を確かめてから既定にした。
1096        self.style_memo.verify = false;
1097        let styled_tree = crate::kernel::window_mgr::kill_owned(crate::os_lib::css::style_tree_with_memo(
1098            &root_node,
1099            &stylesheet,
1100            &rule_index,
1101            &mut self.style_memo,
1102        ));
1103        // {
1104        //     let (hits, misses, mismatches, kept, skips, enabled) = self.style_memo.stats();
1105        //     crate::warn!(
1106        //         "[CSS][MEMO] hits={} misses={} mismatches={} kept={} enabled={} skip[off,counter,has,cand]={:?}",
1107        //         hits, misses, mismatches, kept, enabled, skips
1108        //     );
1109        // }
1110        let _t_style_end = crate::kernel::timer::get_ticks();
1111        // crate::warn!("[CSSTRACE] カスケード完了");
1112        // 【2026-11-18 TODO R2 (d) ①】このタブだけ止める合図が来ていれば、ここでレイアウトをやめる(木は途中まで)。
1113        if crate::kernel::window_mgr::layout_check() {
1114            self.abandon_layout_for_tab_kill("スタイルの計算");
1115            return;
1116        }
1117
1118        // 【2026-11-15】TODO P3: 使う `@font-face` だけを読み込む(オンデマンド化)。
1119        // `style_tree_with_memo` 直後(かつ `layout_tree` の字幅計測より前)に呼ぶことで、
1120        // 表示される要素が実際に要求している `(font-family, weight)` と文字コード(`unicode-range`)に
1121        // 合致する `@font-face` のみを取得・登録し、YouTube Sans 7 ウェイト(計 20.1MB)等の
1122        // 未使用ウェイト・未使用言語サブセットの無条件取得・展開を省く。
1123        if !stylesheet.font_faces.is_empty() {
1124            let t_ff = crate::kernel::timer::get_ticks();
1125            self.fetch_and_register_font_faces(&stylesheet.font_faces, &styled_tree);
1126            super::perf::add(super::perf::Slot::FontFace, t_ff);
1127            // let ff_ticks = crate::kernel::timer::get_ticks().wrapping_sub(t_ff);
1128            // if ff_ticks > 20 {
1129            //     crate::warn!(
1130            //         "[PERF][LAYOUT] font_face登録={}tick 件数={}",
1131            //         ff_ticks,
1132            //         stylesheet.font_faces.len()
1133            //     );
1134            // }
1135        }
1136        // 【2026-08-05】計測はしていたのに**どこにも出していなかった**ため、
1137        // 手を入れた効果を確かめられなかった(`spec/logging_policy.md` L-4)。
1138        // 目的: カスケードの高速化の効果測定。1 レイアウトに 1 回だけで毎フレームではない。
1139        // 破棄条件: style_tree が 100 tick を安定して下回ったら削除する。
1140
1141
1142        // scroll-behavior: smooth はルート要素(<html>)への指定のみ対応(簡略実装)。
1143        self.scroll_smooth = styled_tree
1144            .value("scroll-behavior")
1145            .map(|v| v.trim().eq_ignore_ascii_case("smooth"))
1146            .unwrap_or(false);
1147
1148        // W3C CSS Scrollbars Module Level 1
1149        // `scrollbar-width: auto | thin | none`
1150        let sb_width = styled_tree
1151            .value("scrollbar-width")
1152            .map(|v| ScrollbarWidth::resolve(&v))
1153            .unwrap_or(ScrollbarWidth::Auto);
1154        self.scrollbar_width = sb_width;
1155        self.scrollbar_width_none = sb_width.is_none();
1156
1157        // `scrollbar-color: auto | <thumb-color> <track-color>`
1158        self.scrollbar_color = styled_tree
1159            .value("scrollbar-color")
1160            .and_then(|v| parse_scrollbar_color(&v))
1161            .and_then(|mode| match mode {
1162                ScrollbarColorMode::Custom(c) => Some(c),
1163                ScrollbarColorMode::Auto => None,
1164            });
1165
1166        // 初期包含ブロックはビューポートそのもの(CSS 2.1 §10.1)。
1167        // 【2026-10-09】従来はルート要素に `margin:0` が無いページ(`* {margin:0}` を
1168        // 持たない素朴なページ)にだけ左右 40px・上下 20px の独自の余白を足していた
1169        // (UA スタイルが無かった 2026-06 初期の名残)。`body{margin:0}` のページまで
1170        // 全要素が (40,20) ずれ、`position:fixed;left:0` も 40px 右に出た。本文の余白は
1171        // UA スタイルの `body{margin:8px}`(css/cascade.rs)が担う。
1172        let margin_x = 0;
1173        let margin_y = 0;
1174
1175        // 3. レイアウト構築
1176        let content_w = (win_w as i32 - (margin_x * 2)).max(400);
1177        // 置換要素の width/height % 解決用ビューポートヒント
1178        // (バー類と余白を除いた実コンテンツ領域)
1179        let viewport_h_hint = (win_h as i32 - top_offset - margin_y * 2).max(100);
1180        crate::os_lib::layout::set_viewport_hint(content_w, viewport_h_hint);
1181        self.js_runtime.set_viewport_size(content_w, viewport_h_hint);
1182        let initial_containing_block = crate::os_lib::layout::Dimensions {
1183            content: crate::os_lib::layout::Rect {
1184                x: margin_x,
1185                y: margin_y,
1186                width: content_w,
1187                height: 0,
1188            },
1189            ..Default::default()
1190        };
1191        let _t_layout_start = crate::kernel::timer::get_ticks();
1192        let layout_tree =
1193            crate::kernel::window_mgr::kill_owned(crate::os_lib::layout::layout_tree(&styled_tree, initial_containing_block));
1194        let _t_layout_end = crate::kernel::timer::get_ticks();
1195        // crate::warn!("[CSSTRACE] レイアウト木完了");
1196        if crate::kernel::window_mgr::layout_check() {
1197            self.abandon_layout_for_tab_kill("箱の組み立て");
1198            return;
1199        }
1200        crate::debug!("[GPU] TRACE: layout_tree done");
1201
1202        // 4. フラットな RenderElement リストへの変換 (レガシー描画部との統合)
1203        let _t_flatten_start = crate::kernel::timer::get_ticks();
1204        let flatten_us0 = crate::kernel::timer::get_system_time_us();
1205        let memo_before = flatten_memo_stats();
1206        self.inherited_paint_z = 0;
1207        self.inherited_paint_depth = 0;
1208        self.inherited_positioned = false;
1209        self.inherited_pos_count = 0;
1210        self.abs_marks.clear();
1211        self.stack_prefix.clear();
1212        self.flatten_memo_covered = 0;
1213        self.flatten_decided.clear();
1214        self.flatten_visibility_decided.clear();
1215        let initial_text_color = self.page_text_color;
1216        self.flatten_layout(
1217            &layout_tree,
1218            "",
1219            // フォームの外の method は空(`<form>` の中でだけ設定される。ボタンの送信判定に使う)。
1220            "",
1221            "",
1222            false,
1223            false,
1224            false,
1225            false,
1226            initial_text_color,
1227            16,
1228            "",
1229            None,
1230            "",
1231            None,
1232            String::new(),
1233            1,
1234            0,
1235            false,
1236            false,
1237        );
1238        // 根の箱の要素(どの子ループにも拾われなかったもの)は最外のコンテキスト。
1239        for el in self.elements.iter_mut() {
1240            if !el.stack_decided {
1241                el.stack_path.clear();
1242                el.paint_seq = 0;
1243                el.stack_decided = true;
1244            }
1245        }
1246        if crate::kernel::window_mgr::layout_check() {
1247            self.abandon_layout_for_tab_kill("要素の組み立て");
1248            return;
1249        }
1250        let t_flatten_end = crate::kernel::timer::get_ticks();
1251        let flatten_ms = crate::kernel::timer::get_system_time_us().saturating_sub(flatten_us0) / 1000;
1252        let memo_after = flatten_memo_stats();
1253        // crate::warn!("[CSSTRACE] flatten 完了");
1254        // 【一時】ヘッダ帯の要素を列挙して、ナビ項目がどの経路で
1255        // どんな矩形になっているかを見る。特定でき次第削除する。
1256        crate::kernel::responsiveness::record_ms(
1257            crate::kernel::responsiveness::Lat::Relayout,
1258            (t_flatten_end.wrapping_sub(t_stage0) as u64).saturating_mul(10),
1259        );
1260        // crate::warn!(
1261        //     "[PERF][LAYOUT] html={} css={} style={} layout={} flatten={} 合計={}tick 要素={}",
1262        //     t_html_end.wrapping_sub(t_stage0),
1263        //     t_css_end.wrapping_sub(t_html_end),
1264        //     t_style_end.wrapping_sub(t_style_start),
1265        //     t_layout_end.wrapping_sub(t_layout_start),
1266        //     t_flatten_end.wrapping_sub(t_flatten_start),
1267        //     t_flatten_end.wrapping_sub(t_stage0),
1268        //     self.elements.len()
1269        // );
1270
1271        // 要素矩形を DOM ブリッジへ反映(getBoundingClientRect / offsetWidth 等が参照)。
1272        // element_id→node idx の解決に immutable borrow が要るので、先に収集してから書き込む。
1273        let id_rects: alloc::vec::Vec<(usize, i32, i32, i32, i32, i32, i32, i32, i32)> = {
1274            let dom = self.js_runtime.dom().borrow();
1275            // 【2026-08-05】ここは要素 1 個ごとに `get_element_by_id` を呼んでいた。
1276            //
1277            // `get_element_by_id` は**全 DOM ノードの線形走査**(しかも各ノードで
1278            // `is_attached` が親を辿る)。要素は実測 369 個、ノードも同程度あるので
1279            // O(要素 × ノード × 深さ) になっていた。
1280            // さらに id を持たない要素では毎回 `format!("_ta_{}", idx)` で
1281            // **文字列を確保**してから、まず一致しない検索を走らせていた。
1282            //
1283            // id → ノード添字の対応を**1 回だけ**作って引く。
1284            // 計算量は O(要素 × ノード) から O(要素 + ノード) へ。
1285            let mut id_map: Option<alloc::collections::BTreeMap<&str, usize>> = None;
1286            let mut seen_rect = alloc::collections::BTreeSet::new();
1287            self.elements
1288                .iter()
1289                .filter_map(|e| {
1290                    let node_idx = if let Some(i) = e.node_idx {
1291                        Some(i)
1292                    } else if !e.element_id.is_empty() {
1293                        let map = id_map.get_or_insert_with(|| dom.build_id_index());
1294                        crate::os_lib::web_apis::dom_bridge::DomBridge::resolve_element_id(map, &e.element_id)
1295                    } else {
1296                        None
1297                    };
1298                    // 1 つのノードから描画要素が複数出ることがある(箱の後に中身)。箱の矩形を残す。
1299                    node_idx.filter(|&i| seen_rect.insert(i)).map(|i| {
1300                        (
1301                            i,
1302                            e.x_offset,
1303                            e.y_offset,
1304                            e.width,
1305                            e.height,
1306                            e.border_top_width,
1307                            e.border_right_width,
1308                            e.border_bottom_width,
1309                            e.border_left_width,
1310                        )
1311                    })
1312                })
1313                .collect()
1314        };
1315        {
1316            let mut dom = self.js_runtime.dom().borrow_mut();
1317            dom.clear_rects();
1318            for (i, x, y, w, h, bt, br, bb, bl) in id_rects {
1319                dom.set_rect(i, x, y, w, h);
1320                dom.set_border_widths(i, bt, br, bb, bl);
1321            }
1322        }
1323
1324        // getComputedStyle 用に算出スタイル(全 Element ノードの specified_values)を反映。
1325        // 以前は `id` 属性を持つ要素(または transition/animation を持ち合成 id が
1326        // 登録された要素)にしか computed_styles が反映されず、`id` の無い要素の
1327        // `getComputedStyle()` は `n.style`(インライン `style=""` のみ)にしか
1328        // フォールバックできず、実際にカスケードされたスタイルシート由来の値を
1329        // 一切反映していなかった(現実の大多数のHTML要素は `id` を持たないため
1330        // 影響範囲が広い重大な既知ギャップだった)。木の走査位置を
1331        // `DomBridge::tree_order` でノードの添字へ戻して直接キーに使う(2026-07-18 発見・実装)。
1332        // 【2026-11-01】走査位置をそのまま添字に使っていたが、動的に作った要素があると
1333        // 両者は一致せず、`getComputedStyle` が別の要素の値を返していた。
1334        // 【2026-11-02 最適化】以前は全要素の全スタイルを `Vec<(String, String)>` に
1335        // 2 重にディープコピーして中間バッファ `collected` に蓄積していたため、
1336        // 再レイアウト時に 30〜40MB の確保スパイクを生みヒープ枯渇の一因となっていた(TODO A7a)。
1337        // 中間バッファを全廃し、`dom.computed_styles` へ直接 1 回だけ格納するよう最適化。
1338        {
1339            let order = self.js_runtime.dom().borrow().tree_order();
1340            let mut anim_collected: alloc::vec::Vec<(String, alloc::vec::Vec<(String, String)>)> = alloc::vec::Vec::new();
1341            let mut hidden_anim_ids: alloc::vec::Vec<String> = alloc::vec::Vec::new();
1342            let mut counter = 0usize;
1343            {
1344                let mut dom = self.js_runtime.dom().borrow_mut();
1345                dom.clear_computed();
1346
1347                fn apply_styles_direct(
1348                    node: &crate::os_lib::css::StyledNode,
1349                    dom: &mut crate::os_lib::web_apis::dom_bridge::DomBridge,
1350                    anim_out: &mut alloc::vec::Vec<(String, alloc::vec::Vec<(String, String)>)>,
1351                    hidden_anim_out: &mut alloc::vec::Vec<String>,
1352                    counter: &mut usize,
1353                    order: &[usize],
1354                    in_display_none: bool,
1355                ) {
1356                    let dom_idx = order.get(*counter).copied().unwrap_or(usize::MAX);
1357                    *counter += 1;
1358                    let mut now_display_none = in_display_none;
1359                    if let crate::os_lib::dom::NodeType::Element { id, .. } = &node.node.node_type {
1360                        if !now_display_none
1361                            && node
1362                                .specified_values
1363                                .get("display")
1364                                .is_some_and(|v| v.trim().eq_ignore_ascii_case("none"))
1365                        {
1366                            now_display_none = true;
1367                        }
1368                        let has_anim = node.specified_values.keys().any(|k| {
1369                            matches!(
1370                                k.as_str(),
1371                                "transition" | "animation" | "transition-property" | "animation-name"
1372                            )
1373                        });
1374                        if has_anim {
1375                            let use_id = if let Some(eid) = id {
1376                                eid.clone()
1377                            } else {
1378                                dom.nodes
1379                                    .get(dom_idx)
1380                                    .map(|dn| &dn.id)
1381                                    .filter(|id_str| !id_str.is_empty())
1382                                    .cloned()
1383                                    .unwrap_or_else(|| alloc::format!("_node_idx_{}", dom_idx))
1384                            };
1385                            if now_display_none {
1386                                hidden_anim_out.push(use_id);
1387                            } else {
1388                                let props: alloc::vec::Vec<(String, String)> = node
1389                                    .specified_values
1390                                    .iter()
1391                                    .map(|(k, v)| (k.clone(), v.clone()))
1392                                    .collect();
1393                                anim_out.push((use_id, props));
1394                            }
1395                        }
1396                        if dom_idx != usize::MAX {
1397                            dom.computed_styles.insert(dom_idx, node.specified_values.clone());
1398                        }
1399                    }
1400                    for c in &node.children {
1401                        apply_styles_direct(
1402                            c,
1403                            dom,
1404                            anim_out,
1405                            hidden_anim_out,
1406                            counter,
1407                            order,
1408                            now_display_none,
1409                        );
1410                    }
1411                }
1412
1413                apply_styles_direct(
1414                    &styled_tree,
1415                    &mut dom,
1416                    &mut anim_collected,
1417                    &mut hidden_anim_ids,
1418                    &mut counter,
1419                    &order,
1420                    false,
1421                );
1422            }
1423
1424            // `display: none` の部分木にある要素のアニメーションは停止・除去する(CSS Animations §4.2 / TODO P4a)。
1425            for eid in &hidden_anim_ids {
1426                self.anim_engine.cancel_for(eid);
1427            }
1428
1429            // --- CSS アニメーション/トランジションの同期 ---
1430            // anim_collected: transition/animation を持つ全要素(明示 id + 合成 id)。
1431            self.sync_animations(&anim_collected, &stylesheet);
1432        }
1433
1434        // --- サブスクロール領域の同期 ---
1435        // 1. JS が el.scrollTop / el.scrollLeft を書き込んでいれば scroll_regions へ反映する。
1436        //    (dom.scroll_tops[idx] → 要素 id → scroll_regions[id])
1437        //    (dom.scroll_lefts[idx] → 要素 id → scroll_regions_x[id])
1438        {
1439            let (js_tops, js_lefts): (alloc::vec::Vec<(String, i32)>, alloc::vec::Vec<(String, i32)>) = {
1440                let dom = self.js_runtime.dom().borrow();
1441                let tops = dom.scroll_tops
1442                    .iter()
1443                    .filter_map(|(idx, top)| {
1444                        let id = dom.nodes.get(*idx).map(|n| n.id.clone())?;
1445                        if id.is_empty() { None } else { Some((id, *top)) }
1446                    })
1447                    .collect();
1448                let lefts = dom.scroll_lefts
1449                    .iter()
1450                    .filter_map(|(idx, left)| {
1451                        let id = dom.nodes.get(*idx).map(|n| n.id.clone())?;
1452                        if id.is_empty() { None } else { Some((id, *left)) }
1453                    })
1454                    .collect();
1455                (tops, lefts)
1456            };
1457            for (id, top) in js_tops {
1458                if let Some(entry) = self.scroll_regions.get_mut(&id) {
1459                    *entry = top;
1460                }
1461            }
1462            for (id, left) in js_lefts {
1463                if let Some(entry) = self.scroll_regions_x.get_mut(&id) {
1464                    *entry = left;
1465                }
1466            }
1467        }
1468        // 2. レンダラが把握した scroll_regions / scroll_containers を dom へ反映する。
1469        //    (scroll_regions[id] → node_idx → dom.scroll_tops)
1470        //    (scroll_regions_x[id] → node_idx → dom.scroll_lefts)
1471        //    (scroll_max_y + height → dom.scroll_heights)
1472        {
1473            let sync_data: alloc::vec::Vec<(usize, i32, i32, i32)> = {
1474                let dom = self.js_runtime.dom().borrow();
1475                self.scroll_containers
1476                    .iter()
1477                    .filter_map(|(cid, max_y, _cx, _cy, _cw, ch, ..)| {
1478                        let idx = dom.get_element_by_id(cid)?;
1479                        let cur_y = self.scroll_regions.get(cid).copied().unwrap_or(0);
1480                        let cur_x = self.scroll_regions_x.get(cid).copied().unwrap_or(0);
1481                        Some((idx, cur_y, cur_x, max_y + ch))
1482                    })
1483                    .collect()
1484            };
1485            let mut dom = self.js_runtime.dom().borrow_mut();
1486            for (idx, cur_y, cur_x, sh) in sync_data {
1487                dom.scroll_tops.insert(idx, cur_y);
1488                dom.scroll_lefts.insert(idx, cur_x);
1489                dom.scroll_heights.insert(idx, sh);
1490            }
1491        }
1492
1493        // スクロール限界の設定 (ビューポートは win_h - top_offset)
1494        // 文書の高さはルートの箱に加えて、絶対配置の子孫のはみ出しも含める(CSS Overflow 3 の
1495        // scrollable overflow。固定配置とスクロール領域の中の要素は除き、切り取りがあればその下端まで)。
1496        // 【2026-10-24】YouTube の `<ytd-app>` は `position:absolute` で、文書の高さが 0 扱いになり
1497        // スクロールできず、動画の下(タイトル・説明・関連動画)が見えなかった。
1498        let flow_height = layout_tree.dimensions.margin_box().height;
1499        let overflow_bottom = self
1500            .elements
1501            .iter()
1502            .filter(|e| !e.is_fixed && e.scroll_container_id.is_empty() && e.height > 0)
1503            .map(|e| {
1504                let bottom = e.y_offset + e.height;
1505                if e.clip_y1 > e.clip_y0 {
1506                    bottom.min(e.clip_y1)
1507                } else {
1508                    bottom
1509                }
1510            })
1511            .max()
1512            .unwrap_or(0);
1513        let content_height = flow_height.max(overflow_bottom) + margin_y * 2;
1514        let viewport_height = (win_h as i32 - top_offset).max(100);
1515        self.max_scroll_y = (content_height - viewport_height).max(0);
1516
1517        // position: sticky の可動範囲下限を確定する。
1518        // スクロールコンテナに属する要素はそのコンテナの content 下端、
1519        // ページスクロールの要素はドキュメント全体の下端を上限に、height 分引いた値まで。
1520        // これ以上は「吸着解除」してその位置で止まる(親からはみ出さない)。
1521        for i in 0..self.elements.len() {
1522            if !self.elements[i].is_sticky {
1523                continue;
1524            }
1525            let cid = self.elements[i].scroll_container_id.clone();
1526            let bound_bottom = if cid.is_empty() {
1527                content_height
1528            } else if let Some((_, _, _, cy, _, ch, ..)) =
1529                self.scroll_containers.iter().find(|(id, ..)| *id == cid)
1530            {
1531                cy + *ch
1532            } else {
1533                content_height
1534            };
1535            let height = self.elements[i].height;
1536            self.elements[i].sticky_bound_max_y = (bound_bottom - height).max(0);
1537        }
1538        // scroll_y は**文書が変わったとき**のみ 0 へリセット。
1539        // 同じ文書の再レイアウト(`:target` 変化・フォント到着・JS 変更)では保持する。
1540        if is_document_changed {
1541            self.scroll_y = 0;
1542        } else {
1543            self.scroll_y = self.scroll_y.min(self.max_scroll_y);
1544        }
1545        self.dirty = true;
1546        self.dirty_reason = "layout.rs:865";
1547
1548        crate::info!(
1549            "WEB_ENGINE: Flatten layout done. generated {} elements.",
1550            self.elements.len()
1551        );
1552
1553        // 現在ページの絶対URLを JS へ反映(fetch/XHR の相対基準 + window/document.location)。
1554        // 【2026-10-29】先に `history.pushState` で変わった URL を取り込む。従来は再レイアウトのたびに
1555        // 古い URL で `location` を上書きして戻しており、アドレス欄も `location` も元の URL に戻っていた。
1556        self.sync_url_from_script();
1557        {
1558            let scheme = if self.current_is_https {
1559                "https://"
1560            } else {
1561                "http://"
1562            };
1563            let page_url = alloc::format!("{}{}{}", scheme, self.current_host, self.current_path);
1564            self.js_runtime.set_page_url(&page_url);
1565            self.js_runtime.set_referrer(&self.referrer);
1566            self.js_runtime.set_frame_depth(self.frame_depth);
1567        }
1568
1569        // <script> タグの実行は**次のフレームへ回す**(`run_pending_scripts`)。
1570        // 【2026-10-05 高速化】従来はここで外部スクリプトを同期取得・実行してから戻っていたため、
1571        // CSS を当てたレイアウトが済んでいても、スクリプト(sugi-lab.net では modern-script.js と
1572        // Cloudflare beacon)の取得・実行が終わるまで最初の画面が出なかった(約 10 秒)。
1573        // 実ブラウザもこの位置(本文末尾)のスクリプトより先に描画する。
1574        // 【2026-10-05】スクリプトは文書ごとに 1 回だけ。従来はフォント到着等の再レイアウト
1575        // (`executing_script` を立てない経路)のたびにページのスクリプトを再実行していた
1576        // (本文はキャッシュから読むので通信ログに出ず、気づけなかった)。
1577        let doc_hash = super::helpers::hash_str(html);
1578        if !self.executing_script && self.scripts_ran_for != Some(doc_hash) {
1579            self.scripts_ran_for = Some(doc_hash);
1580            self.pending_scripts = collect_scripts_from_dom(&root_node);
1581            super::fetch_limit::set_scripts_pending(!self.pending_scripts.is_empty());
1582            if !self.pending_scripts.is_empty() {
1583                // 撮影スクリプト等が「読込完了」を判断するための印(`scripts/screenshot_site.sh`)。
1584                crate::warn!("[SCRIPTS] pending n={}", self.pending_scripts.len());
1585            }
1586            crate::debug!("[GPU] TRACE: script blocks pending={}", self.pending_scripts.len());
1587        }
1588
1589        // 【2026-08-03】URL のフラグメント(`#id`)があれば、要素が出揃った
1590        // この時点でその位置までスクロールする。
1591        //
1592        // 実ブラウザの標準機能であり、このサイトのナビゲーション
1593        // (Top / Profile / Smart Home / Datamining)も `#id` リンク。
1594        // 対象 id がまだ現れていない場合は保持したままにして、
1595        // 次のレイアウト(フォント到着後の再レイアウト等)で再挑戦する。
1596        if !self.pending_fragment.is_empty() {
1597            let frag = self.pending_fragment.clone();
1598            if self.elements.iter().any(|e| e.element_id == frag) {
1599                let href = alloc::format!("#{}", frag);
1600                self.navigate_to_fragment(&href);
1601                self.pending_fragment.clear();
1602                crate::warn!("[NAV] フラグメントへスクロール #{}", frag);
1603            } else {
1604                // 見つからないこと自体は異常ではない(まだ生成されていない、
1605                // あるいは存在しない id)。ただし黙って消さない。
1606                crate::warn!(
1607                    "[NAV] フラグメントの対象がまだ見つからない #{} elements={}",
1608                    frag,
1609                    self.elements.len()
1610                );
1611            }
1612        }
1613
1614        // 【2026-08-05 計測】flatten 以降にも処理が続く。
1615        // 上の `[PERF][LAYOUT]` は flatten までしか測っておらず、
1616        // それだけでは 38〜183 tick と軽い。関数全体との差が
1617        // 「flatten より後」のコストになる。
1618        // 【2026-11-18】flatten の時間と、flatten の使い回し表(FLATTEN_MEMO)の今回の当たり・外れ・項目数・量も出す。
1619        crate::warn!(
1620            "[PERF][LAYOUT] 関数全体={}tick flatten={}ms 要素={} memo 当たり={} 外れ={} 項目={} 量={}KB",
1621            crate::kernel::timer::get_ticks().wrapping_sub(t_stage0),
1622            flatten_ms,
1623            self.elements.len(),
1624            memo_after.0.wrapping_sub(memo_before.0),
1625            memo_after.1.wrapping_sub(memo_before.1),
1626            memo_after.2,
1627            memo_after.3 >> 10
1628        );
1629    }
1630
1631    /// `<script src="...">` の外部スクリプトを取得する。`url` は resolve_dom_paths 済みのため、
1632    /// 絶対パス(同一ホスト)か `scheme://host/path` の完全URLのどちらか。
1633    /// `url`(`<link href>`等、絶対URLの場合も現在ページ相対パスの場合もある)を
1634    /// 常に絶対URL文字列へ正規化する。外部CSS自身の`url()`相対参照を、その
1635    /// CSSファイル自身の場所を基準に解決する(`rewrite_css_urls`)際の
1636    /// 基点URLとして使う。
1637    fn resolve_page_url(&self, url: &str) -> String {
1638        if url.starts_with("http://") || url.starts_with("https://") {
1639            String::from(url)
1640        } else {
1641            let scheme = if self.current_is_https { "https://" } else { "http://" };
1642            alloc::format!("{}{}{}", scheme, self.current_host, url)
1643        }
1644    }
1645
1646    /// `ensure_image_cached` と同じ規約: 現在のページが `localhost`(アプリのローカルHTML)
1647    /// なら SylFS から読み、それ以外は実際の HTTP(S) 経由でフェッチする。
1648    /// iframe の代替表示(`iframe_preview` 参照)。埋め込み先 HTML を 1 回だけ取得して OGP を読む。
1649    /// OSM 埋め込みは地図をタイルで描くので対象外。
1650    fn iframe_preview_for(&mut self, src: &str) -> Option<super::iframe_preview::Preview> {
1651        let src = src.trim();
1652        if src.is_empty()
1653            || src.starts_with("about:")
1654            || src.starts_with("data:")
1655            || src.starts_with("javascript:")
1656            || super::embed_map::parse_embed_url(src).is_some()
1657        {
1658            return None;
1659        }
1660        if let Some(p) = self.iframe_previews.get(src) {
1661            return p.clone();
1662        }
1663        let p = self
1664            .fetch_script_text(src)
1665            .and_then(|html| super::iframe_preview::parse_preview(&html));
1666        crate::debug!(
1667            "[IFRAME] preview src={} title={:?}",
1668            src,
1669            p.as_ref().map(|p| p.title.as_str())
1670        );
1671        self.iframe_previews.insert(src.into(), p.clone());
1672        p
1673    }
1674
1675    fn fetch_script_text(&self, url: &str) -> Option<String> {
1676        let _t_fs = super::perf::start();
1677        let mut r = self.fetch_script_text_inner(url);
1678        super::perf::add(super::perf::Slot::FetchScript, _t_fs);
1679        if let Some(ref mut s) = r {
1680            super::site_hooks::hooks().patch_script(url, s);
1681        }
1682        r
1683    }
1684
1685    fn fetch_script_text_inner(&self, url: &str) -> Option<String> {
1686        if self.current_host == "localhost" {
1687            // FS は複数スレッドから触られる(`kernel::fs::FS_LOCK` の説明を参照)。
1688            let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
1689            let fs = crate::kernel::fs::get_fs();
1690            return match fs.read_file_checked(url) {
1691                Ok(Some((_m, bytes))) => Some(String::from_utf8_lossy(&bytes).into_owned()),
1692                Ok(None) => None,
1693                Err(e) => {
1694                    crate::warn!("[FS] fetch_script_text_inner: failed to read '{}': {}", url, e);
1695                    None
1696                }
1697            };
1698        }
1699        // 【2026-09-05 バグ修正】ここは `https://`/`http://` 以外をすべて
1700        // 「現在のホスト上のパス」として扱っていた。そのため
1701        // プロトコル相対 URL(`//host/path`)が自ホストへ向き、
1702        // 実サイトの `//ajax.googleapis.com/.../jquery.min.js` が
1703        // 自ホストの HTML を返し、それを JS として実行して構文エラーに
1704        // なっていた(=**jQuery 本体が読み込まれていなかった**)。
1705        //
1706        // 同型の誤りは `js/builtins.rs`・`web_engine/render.rs` でも
1707        // 個別に直されており、ここが 4 例目。判定を
1708        // `url_resolve::split_target` に集約して、5 例目が生まれないようにする。
1709        let (is_https, host, path) = super::url_resolve::split_target(
1710            url,
1711            self.current_is_https,
1712            &self.current_host,
1713        );
1714        // 【2026-07-24】この自作TCPスタックは送信データの再送機構を持たず、
1715        // ネットワーク上でパケット(TLS ClientHello等)が消失すると復旧できず
1716        // 接続全体が失敗する(`tcp_send_real`自体への再送追加は既存の安定した
1717        // メインHTML取得経路に悪影響を与えたため断念済み、詳細はTODO.md参照)。
1718        // 【2026-07-25】以前はここで独自に最大3回の再試行をしていたが、
1719        // `https_get_binary`/`http_get_binary`側が接続失敗・応答打ち切りの
1720        // 両方について既に最大3回まで内部で再試行するようになったため、
1721        // ここでさらに3回重ねると最悪ケースで1リソースあたり最大9回もの
1722        // 接続試行が発生し、ロード時間を不必要に悪化させていた。二重管理を
1723        // やめ、呼び出しは1回のみとしリトライは呼び出し先に一本化する。
1724        // 【2026-07-26】外部CSS/JSもディスクキャッシュを使うようにした。
1725        // メインHTMLと画像は以前からキャッシュしていたが、この経路だけが
1726        // 毎回ネットワークへ出ていた。自作TCP/TLSスタックは実測でパケット
1727        // 消失・タイムアウトが頻発しており、一度取得できたスタイルシートを
1728        // 再取得しないだけで表示の再現性が上がる。
1729        // (SylFS に間接ブロックを追加し 1 ファイル上限を約22KB→約85KB へ
1730        //   拡大したので、49KB の `modern-style.css` も対象になる。
1731        //   現状バックエンドは RAMDisk のため効果は同一起動内に限られるが、
1732        //   ページ間の行き来では再取得を避けられる。SDカードが使えるように
1733        //   なれば起動をまたいで効く。)
1734        if let Some(cached) = super::cache::read_cache(&host, &path) {
1735            crate::debug!("[NET] fetch_script_text: cache hit host={} path={}", host, path);
1736            return Some(
1737                String::from_utf8(cached)
1738                    .unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned()),
1739            );
1740        }
1741
1742        // 【2026-08-05 試して差し戻した】ここを非同期取得にしたが**回帰した**。
1743        //
1744        // 動機は正しかった: レイアウト 1 回 92〜2176 tick のうち、
1745        // HTML 解析・CSS 解析・レイアウト木構築は合計 57〜183 tick しかなく、
1746        // **大きな値の正体はここの通信待ち**だった。
1747        // 非同期にするとレイアウトは 30〜164 tick まで落ちた。
1748        //
1749        // だが**ページが素の HTML のまま描かれた**。
1750        // CSS 自体は取得できており(`[FONT] 背景取得完了 /css/modern-style.css
1751        // bytes=49077`)、到着通知による再レイアウトも 3 回走っていたのに、
1752        // スタイルが当たらない。`external_css_cache` と `cached_stylesheet` を
1753        // 到着時に捨てるようにしても直らなかった。
1754        //
1755        // 非同期化には「初回は CSS 無しで描き、届いたら**確実に**当て直す」
1756        // 経路の作り込みが要る。キューを差し替えるだけでは足りない。
1757        // 壊れた見た目を残さないため、原因が分かるまで同期のままにする。
1758        // 設計は `spec/resource_loading.md`(R-1/R-3)にある。
1759        // 【2026-08-05 三度試して三度とも戻した】非同期取得は**まだ入れられない**。
1760        //
1761        // ## 動機(測定として正しい)
1762        //
1763        // 段ごとに測ると HTML 解析・CSS 解析・レイアウト木構築は
1764        // 合計 57〜183 tick しかないのに、`parse_and_layout` 全体は
1765        // 92〜2176 tick。**差の正体はここの同期通信待ち**。
1766        // 非同期にするとレイアウトは 35〜432 tick まで落ちる(毎回再現)。
1767        //
1768        // ## 経過
1769        //
1770        // | 回 | 結果 |
1771        // |---|---|
1772        // | 1 | 素の HTML に見えた → **撮影が早かっただけの誤判定**。計装すると `rules=2403` で正しく当たっていた |
1773        // | 2 | メイン HTML が読めない(`total=3`)→ `fetch_limit` で優先度の門を実装 |
1774        // | 3 | 門が閉じている間の投入が滞留 → `pump()` で解消。`total=12` まで回復したが**CSS が当たらない** |
1775        //
1776        // 3 回目は取得もキャッシュ破棄も動いているのにスタイルが当たらない。
1777        // 原因は未特定。**見た目が壊れたまま残さない**ため同期に戻す(R-6)。
1778        //
1779        // ## 計装を入れて分かったこと(4 回目・原因を絞り込んだ)
1780        //
1781        // `[CSSTRACE]` を常設して非同期版を走らせた結果:
1782        //
1783        // ```text
1784        // 非同期投入 host=www.sugi-lab.net path=/css/modern-style.css
1785        // 抽出 ext_len=0            ← 初回は空(想定どおり)
1786        // カスケード開始 ルール数=0
1787        // 到着による再レイアウト(CSS キャッシュ破棄)
1788        // 抽出 ext_len=124813       ← 届いた CSS を取り直せている
1789        // 解析キャッシュ命中=false
1790        // カスケード開始 ルール数=2403   ← 正しくカスケードしている
1791        // [PERF][LAYOUT] 要素=365        ← スタイル付きの要素も生成されている
1792        // ```
1793        //
1794        // **取得・キャッシュ破棄・再抽出・解析・カスケード・要素生成まで
1795        // すべて正しく動いている。** それでも画面は素の HTML のまま
1796        // (待機を 200→330 秒に延ばしても変わらないので**タイミングでもない**)。
1797        //
1798        // ## さらに絞り込んだ(5 回目・原因はほぼ確定)
1799        //
1800        // 描画側にも要素数を出し、ログの**行番号**で突き合わせた:
1801        //
1802        // ```text
1803        // 103: カスケード開始 ルール数=0
1804        // 114: [PERF][LAYOUT] ... 要素=365        ← この 365 要素は CSS 無しで作られた
1805        // 225: カスケード開始 ルール数=2403    ← この後に [PERF][LAYOUT] が無い
1806        // ```
1807        //
1808        // **スタイル付きのレイアウトは開始するが、完了行が出ない。**
1809        // つまり「描かれていない」のではなく「間に合っていない」。
1810        // 同じ実行の `[PERF][DRAW] frames=25`(通常は 100 超)も、
1811        // 実行が終盤だったことを裏づける。
1812        //
1813        // → CSS の到着が遅すぎる。フォント 8 本・画像と同じ 8 枠を
1814        //    奪い合っており、**CSS に優先権が無い**。
1815        //    `spec/resource_loading.md` の実装順序 4
1816        //    「キューを 1 本に統合し種別ごとの優先度を持たせる」が
1817        //    前提条件だと考え、優先度(CSS > フォント > 画像 > JS)を実装した。
1818        //
1819        // ## 6 回目・原因を突き止めた
1820        //
1821        // 優先度を入れても結果は同じだったので、
1822        // `style_tree` の前後・レイアウト木・flatten に印を足して測った:
1823        //
1824        // ```text
1825        // [CSSTRACE] カスケード開始 ルール数=2403
1826        // (「カスケード完了」が出ない)
1827        // ```
1828        //
1829        // **`style_tree` 自体が終わっていない。**
1830        // 同期版では同じ 2403 ルールが 118〜270 tick で完了する。
1831        // 違いは、非同期版ではカスケードが**8 本の取得ワーカーと同時に走る**こと。
1832        //
1833        // カスケードはノードごとに `BTreeMap` を作る確保の塊で、
1834        // このヒープは確保のたびに割り込みを止める spin ロックを取る
1835        // (`kernel/allocator.rs`)。取得ワーカー 8 本と競合すると
1836        // 桁違いに遅くなり、実行時間内に終わらない。
1837        //
1838        // ## 7 回目・競合説も否定された
1839        //
1840        // 「取得ワーカーと競合してカスケードが遅い」という読みで、
1841        // 再レイアウトの条件に `fetch_limit::active() == 0` を足した。
1842        // **それでもカスケードは完了しなかった。**
1843        // ヒープ競合は原因ではない。
1844        //
1845        // ## 分かっていること(ここまでの確定事項)
1846        //
1847        // - CSS の取得・キャッシュ・再抽出・解析(2403 ルール)は正しく動く
1848        // - 再レイアウトも起きる(`到着による再レイアウト` が出る)
1849        // - **`style_tree` が完了しない**(`カスケード開始` の後に完了行が無い)
1850        // - 同じ 2403 ルールでも**同期版なら 13 回すべて完了する**
1851        // - 待機を 330 秒に延ばしても変わらない(時間切れではない)
1852        // - 取得ワーカーが止まっていても変わらない(ヒープ競合ではない)
1853        //
1854        // ## 8 回目・「ハングする」という読みが**誤りだった**
1855        //
1856        // 渡る木を測ると同期版と**完全に同一**だった。
1857        //
1858        // ```text
1859        // 同期:   カスケード開始 ルール数=2403 ノード数=358 深さ=10  → 完了
1860        // 非同期: カスケード開始 ルール数=2403 ノード数=358 深さ=10  → 完了行が無い
1861        // ```
1862        //
1863        // ログの**行番号**を見ると、その「完了行が無い」開始行は
1864        // **ログの最終行**だった。つまりハングではなく、
1865        // **カスケードを始めた瞬間に実行時間が尽きただけ**。
1866        //
1867        // 6・7 回目に「`style_tree` が完了しない」「ヒープ競合だ」と
1868        // 書いたのは誤り。tail だけ見て「後続が無い=止まった」と
1869        // 決めつけていた(**ログの末尾は「止まった」の証拠にならない**)。
1870        //
1871        // ## 本当の問題: 非同期版は CSS の反映が遅すぎる
1872        //
1873        // 同じ実行の `[PERF][DRAW] frames=25`(同期版は 100 超)も、
1874        // 全体が遅いことを示している。
1875        // CSS 到着 → 再レイアウト → `@font-face` 発見 → フォント取得 →
1876        // 再レイアウト、と**直列に**進み、各段に静穏待ち(2 秒)が入る。
1877        //
1878        // ## 段ごとに測った(9 回目・数字が出た)
1879        //
1880        // ```text
1881        // [CSSTRACE] 到着 path=/css/modern-style.css 投入から=987tick   ≒ 9.9 秒
1882        // [CSSTRACE] 到着による再レイアウト 到着から=626tick            ≒ 6.3 秒
1883        // ```
1884        //
1885        // **投入から反映まで合計 16 秒**かかっている。内訳は 2 つ。
1886        //
1887        // ### (1) 取得そのものが遅い(987 tick)
1888        //
1889        // 49KB の CSS に 10 秒。実効 100KB/s なら 1 秒未満のはず。
1890        // 差はワーカーの空き待ち(フォント・画像と 8 枠を奪い合う)。
1891        // 優先度を入れたが、**既に走っているワーカーは止まらない**ので、
1892        // 重い画像が枠を握っている間は CSS が待たされる。
1893        //
1894        // ### (2) 到着してから反映までが遅い(626 tick)
1895        //
1896        // 静穏待ちは 2 秒(`QUIET`)なのに 6.3 秒かかっている。
1897        // 再レイアウトの判定は `draw()` の中でしか行われず、
1898        // その `draw()` が 200 秒で 25〜50 回しか回っていないため
1899        // (同期版は 100 回超)、判定の機会自体が少ない。
1900        //
1901        // ### 【訂正】「フォントがまだ同期だから」は**誤り**
1902        //
1903        // 一度そう結論したが、`fetch_binary_bytes` は
1904        // 2026-07-30 の時点で既に非同期化されている
1905        // (キャッシュに無ければ `enqueue_font` して即座に `None` を返す)。
1906        // コードを読まずに「同期のはずだ」と書いた。
1907        //
1908        // ### 【測定済み】`draw()` の「間」も原因ではない
1909        //
1910        // 前回の `draw()` 終了から次の開始までを測った:
1911        //
1912        // ```text
1913        // 同期:   frames=125 total=15522tick 間隔合計=746tick 間隔最大=20tick
1914        // 非同期: frames=50  total=10676tick 間隔合計=943tick 間隔最大=33tick
1915        // ```
1916        //
1917        // **間隔は両方とも極小**(全体の 5% 未満)。
1918        // GUI スレッドは `draw()` の外で止まっていない。これも外れ。
1919        //
1920        // 残るのは「1 回の `draw()` が長い」こと。
1921        // 両方とも `間隔最大` に対して `max`(1 回の最大)が
1922        // 2563〜4043 tick = 25〜40 秒あり、
1923        // **数十秒かかる `draw()` が存在する**。
1924        // 次に測るならそこ(`max` を記録した 1 回の中で何をしていたか)。
1925        //
1926        // ## ここまでで確かなこと
1927        //
1928        // - 投入から反映まで 16 秒(内訳 9.9 秒 + 6.3 秒)
1929        // - 取得の 9.9 秒は枠待ち(優先度を入れても、走行中のワーカーは止まらない)
1930        // - 反映の 6.3 秒は `draw()` の回数が少ないことに由来する
1931        // - `draw()` が減る理由は未特定(フォント同期説は誤り)
1932        //
1933        // 付随して入れた `fetch_limit`(優先度の門)と `pump()`(滞留の解消)、
1934        // 到着時の `external_css_cache` 破棄、`[CSSTRACE]` の計装は
1935        // **それぞれ独立して正しい**ので残してある。
1936        let result = if is_https {
1937            crate::kernel::tls::https_get_binary(&host, &path)
1938        } else {
1939            crate::kernel::net::http_get_binary(&host, &path)
1940        };
1941        match result {
1942            Ok(bytes) if !bytes.is_empty() => {
1943                // 空応答はキャッシュしない。一度 0 バイトを書くと
1944                // 以後は毎回キャッシュ命中して**恒久的に空が返り続ける**。
1945                super::cache::write_cache(&host, &path, &bytes);
1946                Some(
1947                    String::from_utf8(bytes)
1948                        .unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned()),
1949                )
1950            }
1951            Ok(_) => {
1952                // 取得は成功して本文が空(`Content-Length: 0`)。空の文書として返す(キャッシュはしない)。
1953                // 【2026-10-18】従来は失敗扱いで、YouTube 埋め込みの空の基本 CSS のせいで外部 CSS 全体を
1954                // 保存できず、再レイアウトのたびに 550KB の www-player.css を取り直していた。
1955                crate::debug!("[NET] fetch_script_text: 空応答 host={} path={}", host, path);
1956                Some(String::new())
1957            }
1958            Err(e) => {
1959                crate::warn!(
1960                    "[NET] fetch_script_text: 取得失敗 host={} path={} err={}",
1961                    host, path, e
1962                );
1963                None
1964            }
1965        }
1966    }
1967
1968    /// `fetch_script_text`と同じURL解決規則だが、UTF-8ロッシー変換を行わず
1969    /// バイト列のまま返す。TTF/OTF等のバイナリ形式はテキスト変換で内容が
1970    /// 破損する(不正なバイト列がU+FFFDに置換される)ため専用に必要
1971    /// (`@font-face`の実行時フォント読込用。2026-07-22新設)。
1972    fn fetch_binary_bytes(&self, url: &str) -> Option<alloc::vec::Vec<u8>> {
1973        if self.current_host == "localhost" {
1974            // 同上。フォント取得はワーカースレッドからも走る。
1975            let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
1976            let fs = crate::kernel::fs::get_fs();
1977            return match fs.read_file_checked(url) {
1978                Ok(Some((_m, bytes))) => Some(bytes),
1979                Ok(None) => None,
1980                Err(e) => {
1981                    crate::warn!("[FS] fetch_binary_bytes: failed to read '{}': {}", url, e);
1982                    None
1983                }
1984            };
1985        }
1986        fn split_host_path(rest: &str) -> (String, String) {
1987            #[allow(clippy::string_slice)]
1988            match rest.find('/') {
1989                Some(idx) => (String::from(&rest[..idx]), String::from(&rest[idx..])),
1990                None => (String::from(rest), String::from("/")),
1991            }
1992        }
1993        let (is_https, host, path) = if let Some(rest) = url.strip_prefix("https://") {
1994            let (h, p) = split_host_path(rest);
1995            (true, h, p)
1996        } else if let Some(rest) = url.strip_prefix("http://") {
1997            let (h, p) = split_host_path(rest);
1998            (false, h, p)
1999        } else {
2000            (self.current_is_https, self.current_host.clone(), String::from(url))
2001        };
2002        // 【2026-07-30】フォントもディスクキャッシュを使う。
2003        //
2004        // 実測でキャッシュ利用箇所を全列挙したところ、
2005        // CSS/JS(`fetch_script_text`)と画像(`image_loader_thread`)は
2006        // `/cache/browser/` を使っているのに、**フォント取得だけ使っていなかった**。
2007        // そのため 5.3MB の Noto Sans JP を毎回ダウンロードし直しており、
2008        // 描画が始まらない直接の要因になっていた(`spec/resource_loading.md`)。
2009        if let Some(cached) = super::cache::read_cache(&host, &path) {
2010            // crate::warn!(
2011            //     "[NET] fetch_binary_bytes: cache hit host={} path={} bytes={}",
2012            //     host,
2013            //     path,
2014            //     cached.len()
2015            // );
2016            return Some(cached);
2017        }
2018        // 【2026-07-30】キャッシュに無ければ**背景で取得を予約して即座に戻る**。
2019        //
2020        // 以前はここで同期的にダウンロードしており、5.3MB のフォントで
2021        // レンダリングが止まっていた。取得を打ち切るのはブラウザの挙動として
2022        // 誤りなので、**最後まで取得しつつ描画は待たせない**方式へ変える
2023        // (`spec/resource_loading.md` の R-1/R-2)。
2024        // 取得完了後はキャッシュに載るので、次のレイアウトで反映される(R-3)。
2025        // 【2026-08-05 正しく試して悪化・不採用】
2026        //
2027        // 「積むだけにして全部積んでから起こす」(`enqueue_kind_deferred`
2028        // + `spawn_workers`)を、今度は**実コードに当たったことを
2029        // `grep -c` で確認したうえで**測った。
2030        //
2031        // ```text
2032        // 従来:   TLS握手=2958/12  spawn=4  total=13 ok=13
2033        // 遅延版: TLS握手=3525/13  spawn=6  total=13 ok=13
2034        // ```
2035        //
2036        // **握手が 12 → 13 に増えて悪化した。**
2037        // `spawn_workers` が一度に 4 本起こすため、各ワーカーが
2038        // 1 件ずつ持って別々に接続し、**まとめ取得が成立しにくくなる**。
2039        // 「全部並べてから起こす」と「並列に起こす」は両立しない。
2040        //
2041        // 過去 2 回の同案は置換ミスで実コードに当たっておらず、
2042        // そこから導いた R-19 は取り下げ済み。これが唯一の有効な観測。
2043        super::font_queue::enqueue_font(host.clone(), path.clone(), is_https);
2044        None
2045    }
2046
2047    /// `@font-face`で参照されたフォントを実行時に取得・登録する。
2048    /// 【2026-07-24修正】以前は相対URL(`../webfonts/x.woff2`等。FontAwesome等が
2049    /// 使う)を「base URL解決未対応」として無条件でスキップしており、
2050    /// アイコンフォントが一切取得されない既知のバグだった。外部CSSの取得時点
2051    /// (`rewrite_css_urls`、CSSファイル自身の絶対URLを基準に解決)で
2052    /// 相対`url()`参照をすべて絶対URLへ書き換え済みにしたため、ここに届く
2053    /// 時点では(インラインの`<style>`ブロック由来を除き)通常すでに絶対URL
2054    /// になっている。ここでの`http(s)://`チェックは、`data:`URI等
2055    /// 非対応形式を安全に弾くガードとして残す。同名familyが既に登録済みなら
2056    /// ネットワーク往復を避けてスキップする(2026-07-22新設)。
2057    fn fetch_and_register_font_faces(
2058        &self,
2059        font_faces: &[crate::os_lib::css::FontFaceDef],
2060        styled_tree: &crate::os_lib::css::StyledNode,
2061    ) {
2062        let mut used_requests: alloc::collections::BTreeSet<(String, u16)> =
2063            alloc::collections::BTreeSet::new();
2064        let mut used_codepoints: alloc::collections::BTreeSet<u32> =
2065            alloc::collections::BTreeSet::new();
2066        collect_used_fonts_and_chars(
2067            styled_tree,
2068            "sans-serif",
2069            400,
2070            &mut used_requests,
2071            &mut used_codepoints,
2072        );
2073
2074        let mut needed_faces: alloc::collections::BTreeSet<(String, u16)> =
2075            alloc::collections::BTreeSet::new();
2076        for (fam, req_w) in &used_requests {
2077            let avail: alloc::vec::Vec<(u16, bool)> = font_faces
2078                .iter()
2079                .filter(|ff| ff.family.trim().eq_ignore_ascii_case(fam))
2080                .map(|ff| (ff.weight, true))
2081                .collect();
2082            if let Some(picked_w) = crate::kernel::font_select::pick_weight_css(*req_w, &avail) {
2083                needed_faces.insert((fam.clone(), picked_w));
2084            }
2085        }
2086
2087        for ff in font_faces {
2088            let Some(url) = &ff.src_url else { continue };
2089            if !(url.starts_with("http://") || url.starts_with("https://")) {
2090                continue;
2091            }
2092            let fam_lower = ff.family.trim().to_ascii_lowercase();
2093            // 1. この (family, weight) が表示要素から一度も要求されていなければスキップ(TODO P3)。
2094            if !needed_faces.contains(&(fam_lower, ff.weight)) {
2095                continue;
2096            }
2097            // 2. `unicode-range` があり、表示要素のテキストや `::before`/`::after` の文字と 1 文字も交差しなければスキップ。
2098            if !ff.unicode_ranges.is_empty() && !ff.matches_any_codepoint(&used_codepoints) {
2099                continue;
2100            }
2101            // 3. 同一 URL(または unicode-range 無しの同一 family|weight)が登録済みならスキップ。
2102            if crate::kernel::vector_font::is_font_url_registered(url)
2103                || (ff.unicode_ranges.is_empty()
2104                    && crate::kernel::vector_font::has_custom_font_weighted(&ff.family, ff.weight))
2105            {
2106                continue;
2107            }
2108            // let t0 = crate::kernel::timer::get_ticks();
2109            if let Some(bytes) = self.fetch_binary_bytes(url) {
2110                // let elapsed = crate::kernel::timer::get_ticks().wrapping_sub(t0);
2111                let ok = crate::kernel::vector_font::register_custom_font_weighted(
2112                    &ff.family,
2113                    ff.weight,
2114                    bytes,
2115                );
2116                if ok {
2117                    crate::kernel::vector_font::mark_font_url_registered(url);
2118                    crate::os_lib::layout::notify_custom_font_registered();
2119                }
2120                // crate::println!(
2121                //     "[CSSDBG] @font-face '{}' ({}) <- {} registered={} elapsed_ticks={}",
2122                //     ff.family, ff.weight, url, ok, elapsed
2123                // );
2124            } else {
2125                // crate::println!(
2126                //     "[CSSDBG] @font-face '{}' ({}) <- {} 非同期取得へ投入(描画は待たない)",
2127                //     ff.family, ff.weight, url
2128                // );
2129            }
2130        }
2131    }
2132
2133    /// DOM ブリッジが dirty なら、スクリプトを再実行せずに再レイアウトして反映する。
2134    /// クリックリスナや初期スクリプトによる textContent/style/class 変更を画面へ出す。
2135    /// `parse_and_layout` が保留した <script> を取得・実行し、DOM が変わっていれば再レイアウトする。
2136    /// 最初の画面を描いた後のフレームで `draw()` から呼ぶ(2026-10-05)。
2137    pub fn run_pending_scripts(&mut self, top_offset: i32, win_w: u32, win_h: u32) {
2138        if self.pending_scripts.is_empty() || self.executing_script {
2139            return;
2140        }
2141        let script_blocks = core::mem::take(&mut self.pending_scripts);
2142        let n_scripts = script_blocks.len();
2143        self.executing_script = true;
2144        // 文書の読み込み状態: 文書のスクリプトを流す間は loading、終われば interactive、
2145        // 次のフレームで complete(`ready_complete_pending`)。
2146        self.js_runtime.set_document_ready_state("loading");
2147        for (idx, (src, inline, is_module)) in script_blocks.into_iter().enumerate() {
2148            let script_owned;
2149            let script: &str = match src {
2150                Some(ref url) => {
2151                    crate::debug!("[GPU] TRACE: fetching external script idx={} src={}", idx, url);
2152                    match self.fetch_script_text(url) {
2153                        Some(text) => {
2154                            script_owned = text;
2155                            &script_owned
2156                        }
2157                        None => {
2158                            crate::debug!("[GPU] TRACE: external script fetch failed idx={}", idx);
2159                            continue;
2160                        }
2161                    }
2162                }
2163                None => inline.as_str(),
2164            };
2165            if !script.is_empty() {
2166                crate::debug!("[GPU] TRACE: executing script idx={} len={} module={}", idx, script.len(), is_module);
2167                let res = if is_module {
2168                    let spec = src.as_deref().unwrap_or("<inline-module>");
2169                    self.js_runtime.eval_module(spec, script)
2170                } else {
2171                    crate::os_lib::ecma::eval(script, &mut self.js_runtime)
2172                };
2173                if let Err(e) = res {
2174                    crate::debug!("[GPU] TRACE: JS error: {}", e);
2175                }
2176            }
2177        }
2178        self.executing_script = false;
2179        self.js_runtime.set_document_ready_state("interactive");
2180        self.ready_complete_pending = true;
2181        self.ready_interactive_at = crate::kernel::timer::get_system_time_ms();
2182        // スクリプトが DOM を変更していたら、スクリプトを再実行せずに再レイアウトする。
2183        self.relayout_if_dom_dirty(top_offset, win_w, win_h);
2184        super::fetch_limit::set_scripts_pending(false);
2185        crate::warn!("[SCRIPTS] done n={}", n_scripts);
2186        self.dirty = true;
2187        self.dirty_reason = "run_pending_scripts";
2188    }
2189
2190    /// JS が挿入した `<link rel="stylesheet">`(`dom_bridge::pending_dynamic_links`)の CSS を非同期に取得し、
2191    /// 届いたら画面へ反映して `load`、取得に失敗したら `error` を送る。何か送ったら true。
2192    ///
2193    /// 【2026-11-04】従来は外部 CSS を最初のレイアウトで 1 回だけ集めていたので、後から挿入された `<link>` の
2194    /// CSS は使われず、`load` も来なかった(YouTube のプレーヤーの CSS `player-css`)。
2195    /// 外部 CSS は一度だけ解析して元の文字列を手放す作りなので、届いたら外部 CSS のキャッシュを捨て、
2196    /// 次のレイアウトで生きている DOM の木(挿入された `<link>` も含む)から集め直す(届いた物はディスクのキャッシュにある)。
2197    fn run_dynamic_links(&mut self) -> bool {
2198        let new_links: alloc::vec::Vec<usize> =
2199            core::mem::take(&mut self.js_runtime.dom().borrow_mut().pending_dynamic_links);
2200        let scheme = if self.current_is_https { "https://" } else { "http://" };
2201        let page_url = alloc::format!("{}{}{}", scheme, self.current_host, self.current_path);
2202        for idx in new_links {
2203            let href = self.js_runtime.dom().borrow().get_attr(idx, "href").unwrap_or_default();
2204            let resolved = super::url_resolve::resolve_url(&page_url, href.trim());
2205            let (is_https, host, path) =
2206                super::url_resolve::split_target(&resolved, page_url.starts_with("https://"), "");
2207            if super::cache::read_cache(&host, &path).is_none() {
2208                super::font_queue::enqueue_kind(host.clone(), path.clone(), is_https, super::fetch_limit::Kind::Style);
2209            }
2210            self.pending_link_css.push((idx, host, path));
2211        }
2212        if self.pending_link_css.is_empty() {
2213            return false;
2214        }
2215        let mut loaded = alloc::vec::Vec::new();
2216        let mut failed = alloc::vec::Vec::new();
2217        self.pending_link_css.retain(|(idx, host, path)| {
2218            if super::cache::read_cache(host, path).is_some() {
2219                loaded.push((*idx, host.clone(), path.clone()));
2220                false
2221            } else if super::font_queue::fetch_failed(host, path) {
2222                failed.push(*idx);
2223                false
2224            } else {
2225                true
2226            }
2227        });
2228        // 【2026-11-05】届いた CSS が全部、今の外部 CSS に解析済みの物なら(YouTube は `www-player.css` を
2229        // `<link>` で入れ直す)、4MB 余りの外部 CSS の解析し直しと、スタイルの使い回しの表の破棄を省く。
2230        let all_parsed = self.external_css_counts.is_some()
2231            && loaded.iter().all(|(_, h, p)| self.external_css_parsed.iter().any(|(a, b)| a == h && b == p));
2232        if !loaded.is_empty() && !all_parsed && self.append_external_css(&loaded) {
2233            // crate::warn!("[DYNLINK] 届いた CSS だけを解析して外部 CSS の後ろに足した 件数={}", loaded.len());
2234        } else if !loaded.is_empty() && !all_parsed {
2235            self.external_css_cache = None;
2236            self.external_css_counts = None;
2237            self.cached_stylesheet = None;
2238            self.cached_rule_index = None;
2239            self.cached_css_hash = None;
2240            self.inline_style_memo.clear();
2241            self.js_runtime.dom().borrow_mut().structural_dirty = true;
2242        }
2243        // if !loaded.is_empty() && all_parsed {
2244        //     crate::warn!("[DYNLINK] 解析済みの CSS なので外部 CSS を解析し直さない 件数={}", loaded.len());
2245        // }
2246        for (idx, _, _) in &loaded {
2247            self.js_runtime.dispatch_event(*idx, "load");
2248        }
2249        for idx in &failed {
2250            crate::warn!("[DYNLINK] CSS の取得失敗 idx={}", idx);
2251            self.js_runtime.dispatch_event(*idx, "error");
2252        }
2253        !loaded.is_empty() || !failed.is_empty()
2254    }
2255
2256    /// 動的な `<link>` で届いた CSS のうち未解析の物だけを解析し、解析済みの外部 CSS の後ろ(インラインの `<style>` の前)に足す。
2257    /// 【2026-11-05】以前は届くたびに外部 CSS 全体(YouTube で約 4.4MB)を取り直して解析し直していた。外部 CSS は
2258    /// 文書の順に並べ、インラインの `<style>` をその後ろに置く作りなので、後から入った `<link>` は外部 CSS の最後に置けば同じ並びになる。
2259    /// 足せなかったら(外部 CSS を持っていない・本文が読めない)false(呼び出し側が全部取り直す)。
2260    fn append_external_css(&mut self, loaded: &[(usize, String, String)]) -> bool {
2261        let (Some((r_len, kf_len, cs_len, ff_len, layers)), Some(sheet_rc)) =
2262            (self.external_css_counts.clone(), self.cached_stylesheet.as_mut())
2263        else {
2264            return false;
2265        };
2266        let scheme = if self.current_is_https { "https://" } else { "http://" };
2267        let mut added: alloc::vec::Vec<(String, String)> = alloc::vec::Vec::new();
2268        let mut text = String::new();
2269        for (_, host, path) in loaded {
2270            if self.external_css_parsed.iter().any(|(a, b)| a == host && b == path)
2271                || added.iter().any(|(a, b)| a == host && b == path)
2272            {
2273                continue;
2274            }
2275            let url = alloc::format!("{}{}{}", scheme, host, path);
2276            let Some(body) = super::cache::read_cache(host, path).map(|bytes| String::from_utf8_lossy(&bytes).into_owned()) else {
2277                return false;
2278            };
2279            let rewritten = super::url_resolve::rewrite_css_urls(&body, &url);
2280            text.push_str(super::url_resolve::truncate_to_balanced_css(&rewritten));
2281            text.push('\n');
2282            added.push((host.clone(), path.clone()));
2283        }
2284        let mut layers = layers;
2285        let _pp = super::perf::start();
2286        let add = crate::os_lib::css::parse_css_with_layers(&text, &mut layers);
2287        super::perf::add(super::perf::Slot::CssParse, _pp);
2288        let sheet = alloc::rc::Rc::make_mut(sheet_rc);
2289        sheet.rules.truncate(r_len);
2290        sheet.keyframes.truncate(kf_len);
2291        sheet.counter_styles.truncate(cs_len);
2292        sheet.font_faces.truncate(ff_len);
2293        sheet.rules.extend(add.rules);
2294        sheet.keyframes.extend(add.keyframes);
2295        sheet.counter_styles.extend(add.counter_styles);
2296        sheet.font_faces.extend(add.font_faces);
2297        self.external_css_counts =
2298            Some((sheet.rules.len(), sheet.keyframes.len(), sheet.counter_styles.len(), sheet.font_faces.len(), layers));
2299        self.external_css_parsed.extend(added);
2300        // インラインの `<style>` を次のレイアウトで後ろへ付け直し、規則の索引も作り直す。
2301        self.cached_css_hash = None;
2302        self.cached_rule_index = None;
2303        self.js_runtime.dom().borrow_mut().structural_dirty = true;
2304        true
2305    }
2306
2307    /// JS が文書へ挿入した `<script>` を非同期取得・実行し、要素に `load`(失敗なら `error`)を発火する。
2308    /// 実行または処理したら true。
2309    pub fn run_dynamic_scripts(&mut self) -> bool {
2310        let fired_links = self.run_dynamic_links();
2311        let queued: alloc::vec::Vec<usize> = {
2312            let mut dom = self.js_runtime.dom().borrow_mut();
2313            if dom.pending_dynamic_scripts.is_empty() {
2314                alloc::vec::Vec::new()
2315            } else {
2316                let n = dom.pending_dynamic_scripts.len().min(16);
2317                dom.pending_dynamic_scripts.drain(..n).collect()
2318            }
2319        };
2320
2321        let mut actions = alloc::vec::Vec::new();
2322        let scheme = if self.current_is_https { "https://" } else { "http://" };
2323        let page_url = alloc::format!("{}{}{}", scheme, self.current_host, self.current_path);
2324
2325        // 1. キューされた新規動的スクリプトを処理(インラインまたはフェッチ要求)
2326        for idx in queued {
2327            let (src, ty, text, is_async) = {
2328                let dom = self.js_runtime.dom().borrow();
2329                let (src, ty, text) = dom.script_source(idx);
2330                let is_async = dom
2331                    .get_attr(idx, "async")
2332                    .is_some_and(|v| !v.eq_ignore_ascii_case("false"));
2333                (src, ty, text, is_async)
2334            };
2335            let (acts, fetch_req) = self.dynamic_scripts.process_script_with_async(
2336                idx,
2337                src.as_deref(),
2338                &ty,
2339                &text,
2340                &page_url,
2341                is_async,
2342                super::cache::read_cache,
2343            );
2344            actions.extend(acts);
2345            if let Some(req) = fetch_req {
2346                if self.current_host == "localhost" {
2347                    // ローカル FS は同期取得して直接実行
2348                    if let Some(code) = self.fetch_script_text(&req.url) {
2349                        super::cache::write_cache(&req.host, &req.path, code.as_bytes());
2350                        let act = if req.is_module {
2351                            super::dynamic_scripts::DynamicScriptAction::EvalModule {
2352                                idx: req.idx,
2353                                specifier: req.url,
2354                                code,
2355                            }
2356                        } else {
2357                            super::dynamic_scripts::DynamicScriptAction::EvalClassic {
2358                                idx: req.idx,
2359                                code,
2360                            }
2361                        };
2362                        actions.push(act);
2363                    } else {
2364                        actions.push(super::dynamic_scripts::DynamicScriptAction::DispatchError {
2365                            idx: req.idx,
2366                        });
2367                    }
2368                } else {
2369                    // 外部ネットワークスクリプトは完全非同期フェッチキューへ投入
2370                    super::font_queue::enqueue_kind(
2371                        req.host,
2372                        req.path,
2373                        req.is_https,
2374                        super::fetch_limit::Kind::Script,
2375                    );
2376                }
2377            }
2378        }
2379
2380        // 2. フェッチ失敗スクリプトを先に処理し、到着済みのスクリプトをポーリング(ordered の詰まり解除を含む)
2381        actions.extend(self.dynamic_scripts.take_failed(super::font_queue::fetch_failed));
2382        let arrived = self
2383            .dynamic_scripts
2384            .poll_pending(super::cache::read_cache);
2385        actions.extend(arrived);
2386
2387        if actions.is_empty() {
2388            return fired_links;
2389        }
2390
2391        // 3. アクションを順次実行
2392        for act in actions {
2393            match act {
2394                super::dynamic_scripts::DynamicScriptAction::EvalClassic { idx, code } => {
2395                    self.js_runtime.set_current_script(Some(idx));
2396                    let res = crate::os_lib::ecma::eval(&code, &mut self.js_runtime);
2397                    if let Err(e) = res {
2398                        crate::warn!(
2399                            "[DYNSCRIPT] 実行時エラー: {}",
2400                            e.chars().take(160).collect::<String>()
2401                        );
2402                    }
2403                    // crate::warn!(
2404                    //     "[DYNSCRIPT] load idx={} len={} t={}ms",
2405                    //     idx,
2406                    //     code.len(),
2407                    //     crate::kernel::timer::get_system_time_ms()
2408                    // );
2409                    self.js_runtime.dispatch_event(idx, "load");
2410                    self.js_runtime.set_current_script(None);
2411                }
2412                super::dynamic_scripts::DynamicScriptAction::EvalModule {
2413                    idx,
2414                    specifier,
2415                    code,
2416                } => {
2417                    self.js_runtime.set_current_script(None);
2418                    let res = self.js_runtime.eval_module(&specifier, &code);
2419                    if let Err(e) = res {
2420                        crate::warn!(
2421                            "[DYNSCRIPT] 実行時エラー (module): {}",
2422                            e.chars().take(160).collect::<String>()
2423                        );
2424                    }
2425                    self.js_runtime.dispatch_event(idx, "load");
2426                }
2427                super::dynamic_scripts::DynamicScriptAction::DispatchError { idx } => {
2428                    crate::warn!("[DYNSCRIPT] 取得失敗 idx={}", idx);
2429                    self.js_runtime.dispatch_event(idx, "error");
2430                }
2431            }
2432        }
2433
2434        true
2435    }
2436
2437    /// インライン `<svg>` を描画して画像キャッシュに置き、その鍵を返す(`inline_svg`)。
2438    /// 大きさが 0 か描画に失敗したら None(従来どおり何も描かない)。同じ内容・大きさは再描画しない。
2439    fn rasterize_inline_svg(&mut self, styled: &crate::os_lib::css::StyledNode, w: i32, h: i32) -> Option<String> {
2440        if w <= 0 || h <= 0 || w > 2048 || h > 2048 {
2441            return None;
2442        }
2443        // svg 自身の fill は外の祖先からの継承値として扱う(表示属性より弱い)。
2444        let root_fill = styled.value("fill");
2445        let root = inline_svg_node(styled, root_fill.as_deref())?;
2446        let color = styled.value("color").unwrap_or_else(|| String::from("#000"));
2447        let markup = super::inline_svg::serialize_svg_inheriting(&root, root_fill.as_deref(), color.trim());
2448        let key = super::inline_svg::cache_key(&markup, w, h);
2449        if !self.image_cache.contains_key(&key) {
2450            let (iw, ih, rgba) = crate::os_lib::svg::decode_svg_image(markup.as_bytes(), w as u32, h as u32)?;
2451            self.image_cache.insert(
2452                key.clone(),
2453                alloc::sync::Arc::new(super::DecodedImage { width: iw, height: ih, rgba }),
2454            );
2455        }
2456        Some(key)
2457    }
2458
2459    /// 間引きを無視して、DOM が変わっていれば今すぐ組み直す(クリックの当たり判定の前など、
2460    /// 最新の配置が要るとき。実ブラウザも当たり判定の前にレイアウトを確定させる)。
2461    pub fn relayout_now_if_dom_dirty(&mut self, top_offset: i32, win_w: u32, win_h: u32) {
2462        self.force_relayout = true;
2463        self.relayout_if_dom_dirty(top_offset, win_w, win_h);
2464        self.force_relayout = false;
2465    }
2466
2467    /// DOM の変更による組み直しの原因を、30 秒ごとに多い順で 1 行出す(TODO P4 a、2026-11-14)。
2468    /// 回数は「その原因の変更が何回あったか」で、組み直しの回数ではない(組み直し 1 回に複数の変更が入る)。
2469    fn report_dirty_causes(&mut self, now_ms: f64) {
2470        static LAST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
2471        static RELAYOUTS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2472        use core::sync::atomic::Ordering::Relaxed;
2473        RELAYOUTS.fetch_add(1, Relaxed);
2474        let now = now_ms.max(0.0) as u64;
2475        let last = LAST_MS.load(Relaxed);
2476        if last == 0 {
2477            LAST_MS.store(now.max(1), Relaxed);
2478            return;
2479        }
2480        if now.saturating_sub(last) < 30_000 {
2481            return;
2482        }
2483        LAST_MS.store(now.max(1), Relaxed);
2484        let causes = self.js_runtime.dom().borrow_mut().take_dirty_causes();
2485        let mut line = String::new();
2486        for (name, n) in causes.iter().take(32) {
2487            use core::fmt::Write;
2488            let _ = write!(line, " {}={}", name, n);
2489        }
2490        crate::warn!(
2491            "[LAYOUT][CAUSE] {}ms 組み直し={} 原因の種類={} |{}",
2492            now.saturating_sub(last),
2493            RELAYOUTS.swap(0, Relaxed),
2494            causes.len(),
2495            line
2496        );
2497    }
2498
2499    pub fn relayout_if_dom_dirty(&mut self, top_offset: i32, win_w: u32, win_h: u32) {
2500        let (dirty, scope, text_updates) = {
2501            let dom = self.js_runtime.dom().borrow();
2502            if !dom.dirty {
2503                (
2504                    false,
2505                    super::paint_update::UpdateScope::Nothing,
2506                    alloc::vec::Vec::new(),
2507                )
2508            } else if !dom.structural_dirty
2509                && dom.pending_style_updates.is_empty()
2510                && !dom.pending_text_updates.is_empty()
2511            {
2512                let tu: alloc::vec::Vec<super::paint_update::PendingTextUpdate> = dom
2513                    .pending_text_updates
2514                    .iter()
2515                    .map(|(elem_idx, text_idx, new_text)| {
2516                        super::paint_update::PendingTextUpdate {
2517                            elem_idx: *elem_idx,
2518                            text_idx: *text_idx,
2519                            new_text: new_text.clone(),
2520                        }
2521                    })
2522                    .collect();
2523                (true, super::paint_update::UpdateScope::Nothing, tu)
2524            } else {
2525                let updates: alloc::vec::Vec<super::paint_update::PendingStyleUpdate> = dom
2526                    .pending_style_updates
2527                    .iter()
2528                    .map(|(idx, prop, val)| super::paint_update::PendingStyleUpdate {
2529                        node_idx: *idx,
2530                        prop: prop.clone(),
2531                        val: val.clone(),
2532                    })
2533                    .collect();
2534                let scope = if dom.pending_text_updates.is_empty() {
2535                    super::paint_update::classify_updates(
2536                        dom.structural_dirty,
2537                        &updates,
2538                        |idx| {
2539                            dom.nodes.get(idx).map(|n| {
2540                                if !n.id.is_empty() {
2541                                    n.id.clone()
2542                                } else {
2543                                    alloc::format!("_node_idx_{}", idx)
2544                                }
2545                            })
2546                        },
2547                    )
2548                } else {
2549                    super::paint_update::UpdateScope::Relayout
2550                };
2551                (true, scope, alloc::vec::Vec::new())
2552            }
2553        };
2554        if !dirty {
2555            return;
2556        }
2557
2558        if !text_updates.is_empty() {
2559            if self.try_apply_text_updates_in_place(&text_updates) {
2560                let mut dom = self.js_runtime.dom().borrow_mut();
2561                dom.clear_dirty();
2562                self.dirty = true;
2563                self.dirty_reason = "dom-dirty text-only";
2564                return;
2565            }
2566            self.js_runtime.dom().borrow_mut().note_dirty_cause("textContent");
2567        }
2568
2569        // 【2026-10-13】スクロール連動等の style.transform / color / opacity 変更の軽量再ペイント。
2570        // 構造変更がなく、変更プロパティがすべて PaintOnly の場合、350ms かかる全再レイアウトを
2571        // スキップして RenderElement に直接値を書き込む(アニメーションと同じ経路)。
2572        if let super::paint_update::UpdateScope::PaintOnly(paint_values) = scope {
2573            if self.apply_paint_only_values(&paint_values) {
2574                let mut dom = self.js_runtime.dom().borrow_mut();
2575                dom.clear_dirty();
2576                self.dirty = true;
2577                self.dirty_reason = "dom-dirty paint-only";
2578                return;
2579            }
2580        }
2581
2582        // 【2026-10-18】再レイアウトの間引き。前回にかかった時間と同じだけ間を空ける(描画に半分以上を
2583        // 残す)。DOM は dirty のまま残し、`dirty` で再描画を続けるので、期限後の描画で反映される。
2584        // YouTube の操作部(約 1000 ノード、1 回 2 秒)は進行バーの更新のたびに組み直しが続き、
2585        // 動画を含めて画面が十数秒止まっていた。100ms 未満の軽いページは従来どおり即座に組み直す。
2586        // アニメ由来の再レイアウトとも予算を共有し、1 描画あたり 1 回までにする(同じ描画の中で
2587        // タイマー・メディアイベント・アニメの再レイアウトが続けて走り、1 描画が十数秒になっていた)。
2588        let now = self.now_ms();
2589        let last_cost = self.last_dom_layout_ms.max(self.last_anim_layout_ms);
2590        let last_end = self.last_dom_relayout_end_ms.max(self.last_anim_relayout_end_ms);
2591        if !self.force_relayout && last_cost >= 100.0 && (self.relayout_done_this_draw || now < last_end + last_cost) {
2592            self.dirty = true;
2593            self.dirty_reason = "dom-dirty deferred";
2594            return;
2595        }
2596        let html = self.last_html.clone();
2597        // executing_script を立ててスクリプト再実行を抑止(apply_overrides 経路で再描画)。
2598        let was_executing = self.executing_script;
2599        self.executing_script = true;
2600        // {
2601        //     static N: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2602        //     let n = N.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2603        //     if n < 64 {
2604        //         crate::warn!("[LAYOUT][SRC] dom-dirty relayout #{}", n + 1);
2605        //     }
2606        // }
2607        let t0 = self.now_ms();
2608        self.parse_and_layout(&html, None, top_offset, win_w, win_h);
2609        let end = self.now_ms();
2610        self.report_dirty_causes(f64::from(end));
2611        self.last_dom_layout_ms = end - t0;
2612        self.last_dom_relayout_end_ms = end;
2613        self.relayout_done_this_draw = true;
2614        self.executing_script = was_executing;
2615        // 寸法が確定したことを JS へ知らせる(ResizeObserver と、JS が読んだ寸法が古くなったときだけ
2616        // window resize)。【2026-10-24】従来は文書ごと最初の 4 回も無条件に resize を出していた。
2617        // YouTube の resize 処理は 1 回 6〜12 秒かかり、再生開始の直後に約 30 秒、画面とタイマーが
2618        // 止まって player が次の映像を取りに行けず、17 秒で再生が止まっていた。実ブラウザも
2619        // ビューポートが変わらなければ resize を出さない。
2620        self.js_runtime.notify_layout_settled();
2621        self.dirty = true;
2622        self.dirty_reason = "layout.rs:1190";
2623    }
2624
2625    /// 単一行・固定幅箱に収まるテキスト変更を描画要素へ直接反映する(TODO P4c/d)。
2626    fn try_apply_text_updates_in_place(
2627        &mut self,
2628        updates: &[super::paint_update::PendingTextUpdate],
2629    ) -> bool {
2630        let slots: alloc::vec::Vec<super::paint_update::TextElementSlot> = self
2631            .elements
2632            .iter()
2633            .enumerate()
2634            .map(|(i, el)| super::paint_update::TextElementSlot {
2635                elem_array_idx: i,
2636                node_idx: el.node_idx,
2637                is_text: !el.text.is_empty()
2638                    && !el.is_input
2639                    && !el.is_textarea
2640                    && !el.is_button,
2641                x_offset: el.x_offset,
2642                y_offset: el.y_offset,
2643                width: el.width,
2644                height: el.height,
2645            })
2646            .collect();
2647        let planned = {
2648            let elements = &self.elements;
2649            super::paint_update::plan_in_place_text_updates(
2650                false,
2651                true,
2652                updates,
2653                &slots,
2654                |elem_array_idx, new_text| {
2655                    let Some(el) = elements.get(elem_array_idx) else {
2656                        return 0;
2657                    };
2658                    let weight = el.weight();
2659                    let mut total_w = 0i32;
2660                    for c in new_text.chars() {
2661                        if c == '\n' || c == '\u{00AD}' {
2662                            continue;
2663                        }
2664                        let mut cs = String::new();
2665                        cs.push(c);
2666                        total_w += crate::kernel::vector_font::get_vector_string_width_family(
2667                            &cs,
2668                            el.font_size,
2669                            &el.font_family,
2670                            weight,
2671                            0,
2672                            0,
2673                        ) as i32
2674                            + el.letter_spacing
2675                            + if c == ' ' { el.word_spacing } else { 0 };
2676                    }
2677                    total_w
2678                },
2679            )
2680        };
2681        let Some(applied) = planned else {
2682            return false;
2683        };
2684        for (idx, new_text, new_w) in applied {
2685            if let Some(el) = self.elements.get_mut(idx) {
2686                el.text = new_text;
2687                el.width = new_w;
2688            }
2689        }
2690        self.elements_gen = self.elements_gen.wrapping_add(1);
2691        true
2692    }
2693
2694    /// アニメーションの算出値を、描画要素へ直接書き込む(軽量再ペイント経路)。
2695    ///
2696    /// 対象要素が見つからない、値を解釈できない、対応していないプロパティが
2697    /// 含まれる場合は `false` を返す。呼び出し側は従来の再レイアウト経路へ
2698    /// フォールバックすること(**部分適用のまま画面に出さない**ため、
2699    /// 1 つでも適用できなければフレーム全体をやり直す)。
2700    fn apply_paint_only_values(&mut self, computed: &[(String, String, String)]) -> bool {
2701        self.elements_gen = self.elements_gen.wrapping_add(1);
2702        for (eid, prop, val) in computed {
2703            let mut applied_any = false;
2704            let mut failed = false;
2705            for el in self.elements.iter_mut() {
2706                if el.element_id != *eid {
2707                    continue;
2708                }
2709                let ok = match super::repaint_scope::unprefixed(prop).to_ascii_lowercase().as_str() {
2710                    "color" => match crate::os_lib::css::parse_color(val) {
2711                        Some(c) => {
2712                            el.color = c;
2713                            true
2714                        }
2715                        None => false,
2716                    },
2717                    "background-color" => match crate::os_lib::css::parse_color(val) {
2718                        Some(c) => {
2719                            el.bg_color = Some(c);
2720                            true
2721                        }
2722                        None => false,
2723                    },
2724                    "opacity" => match val.trim().parse::<f32>() {
2725                        Ok(f) if f.is_finite() => {
2726                            el.opacity = (f.clamp(0.0, 1.0) * 255.0) as u8;
2727                            true
2728                        }
2729                        _ => false,
2730                    },
2731                    // 【2026-08-02 発見・修正】`transform` は書き込み先
2732                    // (`el.transform_tx/ty`・`scale`・`rotate`・`skew`)が
2733                    // **既に存在する**のに、ここで `false` を返して
2734                    // 全再レイアウト(HTML 再パース+2403 ルール再カスケード、
2735                    // 実測約 6 秒)へ落としていた。
2736                    //
2737                    // 実サイトの `fadeInUp` 系は `opacity` と `transform: translateY()`
2738                    // を組みで動かすため、**必ず**この分岐に当たっていた。
2739                    // 軽量再ペイント経路が用意されているのに一度も使われない状態。
2740                    //
2741                    // 通常のレイアウト時と同じ `parse_transform` を使うので、
2742                    // 解釈は完全に一致する。
2743                    "transform" => {
2744                        let (tx, ty, sx, sy, rot, skx, sky) =
2745                            super::helpers::parse_transform_with_size(
2746                                Some(val.as_str()),
2747                                el.width as f32,
2748                                el.height as f32,
2749                                el.font_size as f32,
2750                            );
2751                        el.transform_tx = tx - el.layout_tx;
2752                        el.transform_ty = ty - el.layout_ty;
2753                        el.transform_scale_x = sx;
2754                        el.transform_scale_y = sy;
2755                        el.transform_rotate_deg = rot;
2756                        el.transform_skew_x = skx;
2757                        el.transform_skew_y = sky;
2758                        true
2759                    }
2760                    "border-color"
2761                    | "border-top-color"
2762                    | "border-right-color"
2763                    | "border-bottom-color"
2764                    | "border-left-color"
2765                    | "outline-color" => match crate::os_lib::css::parse_color(val) {
2766                        Some(c) => {
2767                            el.border_color = Some(c);
2768                            true
2769                        }
2770                        None => false,
2771                    },
2772                    "text-decoration-color" => match crate::os_lib::css::parse_color(val) {
2773                        Some(c) => {
2774                            el.decoration_color = Some(c);
2775                            true
2776                        }
2777                        None => false,
2778                    },
2779                    "caret-color" => match crate::os_lib::css::parse_color(val) {
2780                        Some(c) => {
2781                            el.caret_color = Some(c);
2782                            true
2783                        }
2784                        None => false,
2785                    },
2786                    "accent-color" => match crate::os_lib::css::parse_color(val) {
2787                        Some(c) => {
2788                            el.accent_color = Some(c);
2789                            true
2790                        }
2791                        None => false,
2792                    },
2793                    // 再ペイント扱いだが直接書き込む先が無いプロパティ
2794                    // (box-shadow 等)は再レイアウトへ委ねる。
2795                    _ => false,
2796                };
2797                if ok {
2798                    applied_any = true;
2799                } else {
2800                    failed = true;
2801                }
2802            }
2803            if failed {
2804                return false;
2805            }
2806            if !applied_any {
2807                // 【2026-11-14】TODO P4: 描画要素が無い相手。`display: none` の部分木の中(表示されていない
2808                // スピナーなど)なら、値を書く先が無いだけで見た目は変わらないので、済んだものとして扱う。
2809                // 表示されるようになるとき(class・属性・style.display の変更)は DOM の変更として組み直しになる。
2810                // 表示されているのに描画要素が無い相手(箱を持たない入れ物など)は、従来どおり組み直す。
2811                let hidden = {
2812                    let dom = self.js_runtime.dom().borrow();
2813                    dom.get_element_by_id(eid).is_some_and(|idx| dom.is_in_display_none_subtree(idx))
2814                };
2815                if !hidden {
2816                    static N: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2817                    if N.fetch_add(1, core::sync::atomic::Ordering::Relaxed) < 12 {
2818                        let dom = self.js_runtime.dom().borrow();
2819                        let desc = dom
2820                            .get_element_by_id(eid)
2821                            .and_then(|i| dom.nodes.get(i))
2822                            .map(|n| alloc::format!("<{} class=\"{}\">", n.tag, n.classes.join(" ")))
2823                            .unwrap_or_default();
2824                        crate::warn!("[LAYOUT][PAINT-ONLY] 書く先が無い: {} {} {}={}", eid, desc, prop, val.chars().take(40).collect::<String>());
2825                    }
2826                    return false;
2827                }
2828            }
2829        }
2830        true
2831    }
2832
2833    /// 現在時刻(ms)。カーネルティック(10ms 単位)から算出。
2834    pub(crate) fn now_ms(&self) -> f32 {
2835        (crate::kernel::timer::get_ticks() as f32) * 10.0
2836    }
2837
2838    /// parse_and_layout 後に呼ばれ、各 id 付き要素の算出スタイルから
2839    /// `transition` / `animation` 指定を読み取り、アニメーションエンジンへ反映する。
2840    /// - animation: 新規 @keyframes アニメを登録(同名は重複無視)。
2841    /// - transition: 監視対象プロパティの値が前回から変化していたらトランジション開始。
2842    fn sync_animations(
2843        &mut self,
2844        collected: &[(String, alloc::vec::Vec<(String, String)>)],
2845        stylesheet: &crate::os_lib::css::StyleSheet,
2846    ) {
2847        // アニメ駆動の再レイアウト中は、補間値が computed に出てくるため
2848        // トランジション検出も prev 更新も行わない(誤発火・状態汚染の防止)。
2849        if self.in_anim_relayout {
2850            return;
2851        }
2852        let now = self.now_ms();
2853
2854        for (eid, props) in collected {
2855            // プロパティマップ化。
2856            let mut map: alloc::collections::BTreeMap<&str, &str> =
2857                alloc::collections::BTreeMap::new();
2858            for (k, v) in props {
2859                map.insert(k.as_str(), v.as_str());
2860            }
2861
2862            let animation_str = map.get("animation").map(|s| String::from(*s)).unwrap_or_default();
2863            let transition_str = map.get("transition").map(|s| String::from(*s)).unwrap_or_default();
2864
2865            // --- animation ---
2866            // `animation` ショートハンド優先、無ければ個別ロングハンドから合成解決。
2867            let anim_specs = if let Some(anim_sh) = map.get("animation") {
2868                crate::os_lib::css::parse_animations(anim_sh)
2869            } else {
2870                crate::os_lib::css::resolve_animation_specs(
2871                    map.get("animation-name").copied(),
2872                    map.get("animation-duration").copied(),
2873                    map.get("animation-timing-function").copied(),
2874                    map.get("animation-delay").copied(),
2875                    map.get("animation-iteration-count").copied(),
2876                    map.get("animation-direction").copied(),
2877                    map.get("animation-fill-mode").copied(),
2878                    map.get("animation-play-state").copied(),
2879                )
2880            };
2881            if !anim_specs.is_empty() {
2882                let current_names: alloc::vec::Vec<alloc::string::String> =
2883                    anim_specs.iter().map(|s| s.name.clone()).collect();
2884                self.anim_engine.retain_animation_names(eid, &current_names);
2885                for spec in anim_specs {
2886                    if let Some(kf) = stylesheet
2887                        .keyframes
2888                        .iter()
2889                        .find(|k| k.name == spec.name)
2890                        .cloned()
2891                    {
2892                        self.anim_engine.start_animation(eid, spec, kf, now);
2893                    }
2894                }
2895            }
2896
2897            // --- transition ---
2898            // `transition` ショートハンド優先、無ければ個別ロングハンドから合成解決。
2899            let trans_specs = if let Some(tr_sh) = map.get("transition") {
2900                crate::os_lib::css::parse_transition(tr_sh)
2901            } else {
2902                crate::os_lib::css::resolve_transition_specs(
2903                    map.get("transition-property").copied(),
2904                    map.get("transition-duration").copied(),
2905                    map.get("transition-timing-function").copied(),
2906                    map.get("transition-delay").copied(),
2907                )
2908            };
2909            if !trans_specs.is_empty() {
2910                let prev = self.anim_prev_values.get(eid).cloned().unwrap_or_default();
2911                for ts in &trans_specs {
2912                    // "all" は監視プロパティ群を限定できないので主要プロパティに展開。
2913                    let target_props: alloc::vec::Vec<String> = if ts.property == "all" {
2914                        map.keys()
2915                            .filter(|k| crate::os_lib::css::is_animatable_property(k))
2916                            .map(|k| String::from(*k))
2917                            .collect()
2918                    } else {
2919                        alloc::vec![ts.property.clone()]
2920                    };
2921                    for tp in target_props {
2922                        if let Some(new_val) = map.get(tp.as_str()) {
2923                            if let Some(old_val) = prev.get(&tp) {
2924                                if old_val != new_val {
2925                                    self.anim_engine.start_transition(
2926                                        eid,
2927                                        &tp,
2928                                        old_val,
2929                                        new_val,
2930                                        ts.clone(),
2931                                        now,
2932                                    );
2933                                }
2934                            }
2935                        }
2936                    }
2937                }
2938            }
2939
2940            // 今回の値を prev として保存(次回の変化検出用)。
2941            let mut snapshot: alloc::collections::BTreeMap<String, String> =
2942                alloc::collections::BTreeMap::new();
2943            for (k, v) in props {
2944                snapshot.insert(k.clone(), v.clone());
2945            }
2946            self.anim_prev_values.insert(eid.clone(), snapshot);
2947            self.anim_specs
2948                .insert(eid.clone(), (transition_str, animation_str));
2949        }
2950    }
2951
2952    /// レンダラが毎フレーム呼ぶ。進行中のアニメ/トランジションを現在時刻で評価し、
2953    /// 算出値を DOM ブリッジの style に焼き込んで再描画させる。
2954    /// 戻り値: アニメーションが進行中で次フレームも再描画が必要なら true。
2955    pub fn tick_animations(&mut self, top_offset: i32) -> bool {
2956        if !self.anim_engine.is_active() {
2957            return false;
2958        }
2959        let now = self.now_ms();
2960        let _active = self.anim_engine.tick(now);
2961        let mut computed = self.anim_engine.computed.clone();
2962        // 【2026-11-14】TODO P4: `display: none` の部分木の中の要素(表示されていないスピナーなど)の値は捨てる。
2963        // 見た目に出ないのに、配置に効くプロパティ(幅など)が混ざっていると、毎フレーム全体の組み直しになっていた
2964        // (YouTube の再生中: 30 秒に約 98 回・約 16 秒)。表示されるようになるとき(class・属性・style.display の変更)は
2965        // DOM の変更として組み直しになり、そのときの値から続く。
2966        if !computed.is_empty() {
2967            let dom = self.js_runtime.dom().borrow();
2968            let mut hidden_memo: alloc::collections::BTreeMap<&str, bool> = alloc::collections::BTreeMap::new();
2969            let mut keep = alloc::vec::Vec::with_capacity(computed.len());
2970            for (eid, _, _) in computed.iter() {
2971                let hidden = match hidden_memo.get(eid.as_str()) {
2972                    Some(h) => *h,
2973                    None => {
2974                        let h = dom.get_element_by_id(eid).is_some_and(|idx| dom.is_in_display_none_subtree(idx));
2975                        hidden_memo.insert(eid.as_str(), h);
2976                        h
2977                    }
2978                };
2979                keep.push(!hidden);
2980            }
2981            drop(hidden_memo);
2982            drop(dom);
2983            let mut it = keep.into_iter();
2984            computed.retain(|_| it.next().unwrap_or(true));
2985        }
2986
2987        // 【2026-07-28】軽量再ペイント経路。
2988        // このフレームで変化したのが色・不透明度など**ボックスを変えない**プロパティ
2989        // だけなら、カスケードもレイアウトもやり直さず算出値を差し替えて再描画する。
2990        // 実サイトではレイアウト 1 回が 10 秒以上かかるため、これをやらないと
2991        // 描いたフレームが画面に出る前に次のレイアウトが始まり永久に収束しない。
2992        //
2993        // なお CSS アニメーションは本来インラインスタイルを書き換えない(実ブラウザでも
2994        // `element.style` には現れない)。この経路では DOM ブリッジを一切触らないので、
2995        // ブリッジの dirty を立てずに済み、`relayout_if_dom_dirty` の連鎖も起きない。
2996        let paint_applied = if computed.is_empty() {
2997            false
2998        } else {
2999            let scope = super::repaint_scope::scope_for(computed.iter().map(|(_, p, _)| p.as_str()));
3000            scope == super::repaint_scope::RepaintScope::PaintOnly
3001                && self.apply_paint_only_values(&computed)
3002        };
3003
3004        // 算出値を DOM ブリッジへ反映(軽量経路が使えなかったときのみ)。
3005        if !computed.is_empty() && !paint_applied {
3006            let mut dom = self.js_runtime.dom().borrow_mut();
3007            for (eid, prop, val) in &computed {
3008                if let Some(idx) = dom.get_element_by_id(eid) {
3009                    dom.set_style(idx, prop, val);
3010                }
3011            }
3012            // set_style が dirty=true を立てる。その dirty を parse_and_layout 内の
3013            // to_dom_node() 呼び出しに使うため、ここでは *クリアしない*。
3014            // to_dom_node() 後に b.dirty=false されるので無限ループも起きない。
3015            // in_anim_relayout=true により sync_animations は抑止されるため
3016            // prev 値が汚染されることもない。
3017        }
3018        // `animationend`/`transitionend`/`animationstart`(CSSアニメーション/
3019        // トランジションが自動でライフサイクルイベントを発火する経路が丸ごと
3020        // 未対応だった。`AnimationEvent`/`TransitionEvent`コンストラクタ自体は
3021        // 既に実装済みで手動dispatchは可能だったが、実際の開始/完了を検知して
3022        // 自動発火する仕組みが無かった)。`AnimationEngine::tick()`が検知した
3023        // ライフサイクルイベントを、要素IDからDOMノードindexへ解決して実際に
3024        // ディスパッチする。
3025        let lifecycle_events = self.anim_engine.lifecycle_events.clone();
3026        for (eid, event_type, name) in &lifecycle_events {
3027            let idx_opt = self.js_runtime.dom().borrow().get_element_by_id(eid);
3028            if let Some(idx) = idx_opt {
3029                let key = if *event_type == "transitionend" {
3030                    "propertyName"
3031                } else {
3032                    "animationName"
3033                };
3034                self.js_runtime.dispatch_event_with(
3035                    idx,
3036                    event_type,
3037                    &[(
3038                        alloc::string::String::from(key),
3039                        crate::os_lib::ecma::value::Value::str(name.clone()),
3040                    )],
3041                );
3042            }
3043        }
3044        // 【2026-08-02 発見・修正】算出値が 1 つも無いフレームで全再レイアウトしていた。
3045        //
3046        // 実測: `animation relayout` が 5 回起きているのに、
3047        // 「軽量経路が使えなかった理由」を出す診断は **1 回も出なかった**。
3048        // つまり `computed` が空のまま下の全再レイアウト(HTML 再パース+
3049        // 2403 ルールの再カスケード、実測約 6 秒)へ落ちていた。
3050        //
3051        // 算出値が無いということは、このフレームでアニメーションが
3052        // 変える値が何も無いということ。反映すべきものが無いので
3053        // レイアウトをやり直す理由も無い。
3054        //
3055        // ライフサイクルイベント(`animationend` 等)のハンドラが DOM を
3056        // 変更した場合は、ブリッジの dirty 経由で
3057        // `relayout_if_dom_dirty` が拾うため取りこぼさない。
3058        if computed.is_empty() {
3059            return true;
3060        }
3061
3062        // 軽量経路が成立したフレームはここで完了。再描画だけ要求して戻る。
3063        if paint_applied {
3064            self.dirty = true;
3065            self.dirty_reason = "layout.rs:1518";
3066            return true;
3067        }
3068
3069        // アニメーション由来の再レイアウトは、現状 HTML 再パース + 全ルール再カスケードを
3070        // 伴うため 1 フレームあたりのコストが極めて高い。実測コストが 500ms を超える場合、
3071        // 再レイアウトが描画を占有して「描いた内容が画面に出る前に次のレイアウトが始まる」
3072        // 状態に陥る。そこで実測時間の 3 倍のクールダウンを設け、デューティを 25% に抑える。
3073        // (本来の解はアニメ値の差し替えのみで再ペイントする軽量経路。spec/TODO.md 参照)
3074        // DOM 変更由来の再レイアウトと予算を共有する(`relayout_if_dom_dirty` と同じ理由)。
3075        let last_cost = self.last_dom_layout_ms.max(self.last_anim_layout_ms);
3076        if last_cost >= 100.0 && self.relayout_done_this_draw {
3077            self.dirty = true;
3078            return true;
3079        }
3080        let since = self.now_ms() - self.last_dom_relayout_end_ms.max(self.last_anim_relayout_end_ms);
3081        match super::anim_budget::should_skip_relayout(last_cost, since) {
3082            Ok(true) => {
3083                // アニメーションは継続中。値は DOM ブリッジに反映済みなので
3084                // 次に許可された再レイアウトでまとめて反映される。
3085                return true;
3086            }
3087            Ok(false) => {}
3088            Err(_) => {
3089                // 判定不能。エラーは anim_budget 側でログ済み。
3090                // 間引かない(従来動作)方向にフォールバックし、計測値をリセットする。
3091                self.last_anim_layout_ms = 0.0;
3092                self.last_anim_relayout_end_ms = 0.0;
3093            }
3094        }
3095
3096        // 【2026-11-14】TODO P4 a: アニメ由来の組み直しを招いた値を数える(どの要素のどのプロパティか)。
3097        {
3098            let mut dom = self.js_runtime.dom().borrow_mut();
3099            for (eid, prop, _) in &computed {
3100                let why = if super::repaint_scope::is_paint_only(prop) == Ok(true) { "anim(塗り直し可)" } else { "anim" };
3101                let key = alloc::format!("{}:{}@{}", why, prop, eid.trim_start_matches("_node_idx_").chars().take(16).collect::<String>());
3102                dom.note_dirty_cause(&key);
3103            }
3104        }
3105        // 再レイアウト(アニメ値を反映)。in_anim_relayout を立てて sync_animations 抑止。
3106        let html = self.last_html.clone();
3107        let was_executing = self.executing_script;
3108        self.executing_script = true;
3109        self.in_anim_relayout = true;
3110        // 【2026-07-27診断】再レイアウトの誘発元を切り分ける。
3111        // CSS アニメーションが 1 フレームごとに全再レイアウト(2403 ルールで
3112        // 約 46 秒)を要求していると、描画が完了する前に次の再レイアウトが
3113        // 始まり、描いた内容が画面に残らない。
3114        // {
3115        //     static N: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
3116        //     let n = N.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3117        //     if n < 8 {
3118        //         crate::warn!("[LAYOUT][SRC] animation relayout #{}", n + 1);
3119        //     }
3120        // }
3121        let t0 = self.now_ms();
3122        self.parse_and_layout(&html, None, top_offset, self.win_w, self.win_h);
3123        let end = self.now_ms();
3124        self.report_dirty_causes(f64::from(end));
3125        self.last_anim_layout_ms = end - t0;
3126        self.last_anim_relayout_end_ms = end;
3127        self.relayout_done_this_draw = true;
3128        self.in_anim_relayout = false;
3129        self.executing_script = was_executing;
3130        self.dirty = true;
3131        self.dirty_reason = "layout.rs:1566";
3132        true
3133    }
3134
3135    /// 現在のページ背景色の明度から、デフォルトの (文字色, リンク色) を返す。
3136    /// 明るい背景なら濃い文字+濃い青リンク、暗い背景なら明るい文字+シアンリンク。
3137    fn default_text_colors(&self) -> (u32, u32) {
3138        let bg = self.page_bg_color.unwrap_or(0xFFFFFFFF);
3139        let r = (bg >> 16) & 0xFF;
3140        let g = (bg >> 8) & 0xFF;
3141        let b = bg & 0xFF;
3142        let luma = (299 * r + 587 * g + 114 * b) / 1000;
3143        if luma > 140 {
3144            // 明るい背景
3145            (0xFF1A1A1A, 0xFF1A5FB4)
3146        } else {
3147            // 暗い背景(Dracula 系)
3148            (0xFFF8F8F2, 0xFF8BE9FD)
3149        }
3150    }
3151
3152    fn flatten_layout(
3153        &mut self,
3154        layout: &crate::os_lib::layout::LayoutBox,
3155        current_form_action: &str,
3156        current_form_method: &str,
3157        current_href: &str,
3158        current_font_bold: bool,
3159        current_font_italic: bool,
3160        current_underline: bool,
3161        current_line_through: bool,
3162        current_color: Option<u32>,
3163        current_font_size: u32,
3164        parent_id: &str,
3165        list_state: Option<(bool, u32)>,
3166        parent_tag: &str,
3167        current_decoration_color: Option<u32>,
3168        current_decoration_style: String,
3169        current_decoration_thickness: i32,
3170        current_decoration_underline_offset: i32,
3171        current_overline: bool,
3172        current_pointer_events_none: bool,
3173    ) {
3174        // 暴走防止: 病的なページ(巨大/深い入れ子)でも RenderElement の生成数を上限で
3175        // 打ち切り、ヒープ枯渇を未然に防ぐ。上限到達後は以降の要素を無視する。
3176        if self.elements.len() >= MAX_RENDER_ELEMENTS {
3177            return;
3178        }
3179        // 【2026-11-18 TODO R5 (c)】要素は 1 個 1,800 バイトあり、倍々に伸ばすと 16,384 個から 32,768 個へ伸ばすときに
3180        // 59MB を一度に確保する(4MB の HTML のページでヒープが細切れのときに失敗し、アプリが panic していた)。
3181        // 大きくなってからは上限(と少しの余り)までしか伸ばさず、確保できなければ以降の要素を作らない。
3182        let len = self.elements.len();
3183        if len == self.elements.capacity() && len >= 4096 {
3184            let want = (len * 2).min(MAX_RENDER_ELEMENTS + 64).saturating_sub(len).max(64);
3185            if self.elements.try_reserve_exact(want).is_err() {
3186                crate::warn!("[LAYOUT] 描画する要素の配列を {} 個から伸ばせない(ヒープ不足)。以降の要素を作らない", len);
3187                return;
3188            }
3189        }
3190        // 【2026-11-18 TODO R2 (b) ②・(d) ①】箱 1 つごとに止める確かめ(錠を持っていない所。ウィンドウごと止めるならここで終わる)。
3191        // このタブだけ止める合図なら、この箱と子孫の要素を作らずに戻る(`parse_and_layout` が後でやめた印を付ける)。
3192        if crate::kernel::window_mgr::layout_poll() {
3193            return;
3194        }
3195
3196        fn extract_hover_color(styled: &crate::os_lib::css::StyledNode, key: &str) -> Option<u32> {
3197            styled
3198                .hover_values
3199                .as_ref()
3200                .and_then(|h| h.get(key).and_then(|s| crate::os_lib::css::parse_color(s)))
3201        }
3202
3203        fn extract_color(
3204            styled: &crate::os_lib::css::StyledNode,
3205            key1: &str,
3206            key2: &str,
3207        ) -> Option<u32> {
3208            let val = styled
3209                .specified_values
3210                .get(key1)
3211                .or_else(|| styled.specified_values.get(key2))?;
3212            // まずそのまま解析
3213            if let Some(c) = crate::os_lib::css::parse_color(val) {
3214                // 【2026-07-28】完全透明(アルファ 0)は「背景なし」と等価なので None を返す。
3215                // `parse_color` は不透明色に必ず 0xFF を立てるため、アルファ 0 は
3216                // `transparent` / `rgba(...,0)` を明示指定した場合だけを意味する。
3217                // これを色として返すと、描画側の「アルファ 0x00 は不透明として扱う」
3218                // 互換規則(`spec/alpha_compositing.md`)に拾われ **不透明な黒**になる。
3219                // 実際 `.nav-list` が `bg=0x00000000` で右半分を黒く塗り潰していた。
3220                if (c >> 24) & 0xFF == 0 {
3221                    return None;
3222                }
3223                return Some(c);
3224            }
3225            // `background: url(...) #color` / `background: #color url(...)` のような
3226            // ショートハンドから色トークンだけを取り出す
3227            for token in val.split_whitespace() {
3228                if token.starts_with("url(")
3229                    || token == "no-repeat"
3230                    || token == "repeat"
3231                    || token == "repeat-x"
3232                    || token == "repeat-y"
3233                    || token == "cover"
3234                    || token == "contain"
3235                    || token == "center"
3236                    || token == "top"
3237                    || token == "bottom"
3238                    || token == "left"
3239                    || token == "right"
3240                    || token.ends_with("px")
3241                    || token.ends_with('%')
3242                {
3243                    continue;
3244                }
3245                if let Some(c) = crate::os_lib::css::parse_color(token) {
3246                    return Some(c);
3247                }
3248            }
3249            None
3250        }
3251
3252        fn extract_hover_color_alt(
3253            styled: &crate::os_lib::css::StyledNode,
3254            key1: &str,
3255            key2: &str,
3256        ) -> Option<u32> {
3257            styled.hover_values.as_ref().and_then(|h| {
3258                h.get(key1)
3259                    .or_else(|| h.get(key2))
3260                    .and_then(|s| crate::os_lib::css::parse_color(s))
3261            })
3262        }
3263
3264        fn extract_focus_color(styled: &crate::os_lib::css::StyledNode, key: &str) -> Option<u32> {
3265            styled
3266                .focus_values
3267                .as_ref()
3268                .and_then(|h| h.get(key).and_then(|s| crate::os_lib::css::parse_color(s)))
3269        }
3270
3271        fn extract_focus_color_alt(
3272            styled: &crate::os_lib::css::StyledNode,
3273            key1: &str,
3274            key2: &str,
3275        ) -> Option<u32> {
3276            styled.focus_values.as_ref().and_then(|h| {
3277                h.get(key1)
3278                    .or_else(|| h.get(key2))
3279                    .and_then(|s| crate::os_lib::css::parse_color(s))
3280            })
3281        }
3282
3283        fn extract_active_color(styled: &crate::os_lib::css::StyledNode, key: &str) -> Option<u32> {
3284            styled
3285                .active_values
3286                .as_ref()
3287                .and_then(|h| h.get(key).and_then(|s| crate::os_lib::css::parse_color(s)))
3288        }
3289
3290        fn extract_active_color_alt(
3291            styled: &crate::os_lib::css::StyledNode,
3292            key1: &str,
3293            key2: &str,
3294        ) -> Option<u32> {
3295            styled.active_values.as_ref().and_then(|h| {
3296                h.get(key1)
3297                    .or_else(|| h.get(key2))
3298                    .and_then(|s| crate::os_lib::css::parse_color(s))
3299            })
3300        }
3301
3302        fn extract_marker_color(styled: &crate::os_lib::css::StyledNode) -> Option<u32> {
3303            styled
3304                .specified_values
3305                .get("x-marker-color")
3306                .and_then(|s| crate::os_lib::css::parse_color(s))
3307        }
3308
3309        fn extract_marker_font_size(styled: &crate::os_lib::css::StyledNode) -> Option<u32> {
3310            styled
3311                .specified_values
3312                .get("x-marker-font-size")
3313                .and_then(|s| parse_font_size(s))
3314        }
3315
3316        fn extract_marker_content(styled: &crate::os_lib::css::StyledNode) -> Option<String> {
3317            styled.specified_values.get("x-marker-content").cloned()
3318        }
3319
3320        fn extract_placeholder_color(styled: &crate::os_lib::css::StyledNode) -> Option<u32> {
3321            styled
3322                .specified_values
3323                .get("x-placeholder-color")
3324                .and_then(|s| crate::os_lib::css::parse_color(s))
3325        }
3326
3327        fn get_text_content(l: &crate::os_lib::layout::LayoutBox) -> String {
3328            let mut text = String::new();
3329            match &l.box_type {
3330                crate::os_lib::layout::BoxType::BlockNode(styled)
3331                | crate::os_lib::layout::BoxType::InlineNode(styled)
3332                | crate::os_lib::layout::BoxType::InlineBlockNode(styled) => {
3333                    if let crate::os_lib::dom::NodeType::Text(t) = &styled.node.node_type {
3334                        text.push_str(t);
3335                    }
3336                }
3337                _ => {}
3338            }
3339            for child in &l.children {
3340                text.push_str(&get_text_content(child));
3341            }
3342            text
3343        }
3344
3345        // <select> 配下の <option> を (value, ラベル) で収集する。
3346        // value 属性が無ければラベルテキストを value として用いる(HTML 仕様準拠)。
3347        // 戻り値: (options, selected_index)。selected 属性付き option が無ければ先頭を選択。
3348        fn collect_select_options(
3349            l: &crate::os_lib::layout::LayoutBox,
3350        ) -> (alloc::vec::Vec<(String, String)>, usize) {
3351            let mut opts: alloc::vec::Vec<(String, String)> = alloc::vec::Vec::new();
3352            let mut selected_idx = 0usize;
3353            fn walk(
3354                l: &crate::os_lib::layout::LayoutBox,
3355                opts: &mut alloc::vec::Vec<(String, String)>,
3356                selected_idx: &mut usize,
3357            ) {
3358                if let crate::os_lib::layout::BoxType::BlockNode(styled)
3359                | crate::os_lib::layout::BoxType::InlineNode(styled)
3360                | crate::os_lib::layout::BoxType::InlineBlockNode(styled) = &l.box_type
3361                {
3362                    if let crate::os_lib::dom::NodeType::Element {
3363                        tag_name,
3364                        attributes,
3365                        ..
3366                    } = &styled.node.node_type
3367                    {
3368                        if tag_name == "option" {
3369                            let label = String::from(get_text_content(l).trim());
3370                            let value = attributes
3371                                .get("value")
3372                                .cloned()
3373                                .unwrap_or_else(|| label.clone());
3374                            if attributes.contains_key("selected") {
3375                                *selected_idx = opts.len();
3376                            }
3377                            opts.push((value, label));
3378                            return; // option 配下はラベルとして消費済み
3379                        }
3380                    }
3381                }
3382                for child in &l.children {
3383                    walk(child, opts, selected_idx);
3384                }
3385            }
3386            walk(l, &mut opts, &mut selected_idx);
3387            (opts, selected_idx)
3388        }
3389
3390        // <label> 配下に内包された最初の input/select/textarea の id を返す。
3391        // <label><input id='x'> ...</label> のような暗黙的関連付け用。
3392        fn find_labelable_descendant_id(l: &crate::os_lib::layout::LayoutBox) -> Option<String> {
3393            if let crate::os_lib::layout::BoxType::BlockNode(styled)
3394            | crate::os_lib::layout::BoxType::InlineNode(styled)
3395            | crate::os_lib::layout::BoxType::InlineBlockNode(styled) = &l.box_type
3396            {
3397                if let crate::os_lib::dom::NodeType::Element {
3398                    tag_name,
3399                    attributes,
3400                    ..
3401                } = &styled.node.node_type
3402                {
3403                    if (tag_name == "input" || tag_name == "select" || tag_name == "textarea")
3404                        && attributes.contains_key("id")
3405                    {
3406                        return attributes.get("id").cloned();
3407                    }
3408                }
3409            }
3410            for child in &l.children {
3411                if let Some(id) = find_labelable_descendant_id(child) {
3412                    return Some(id);
3413                }
3414            }
3415            None
3416        }
3417
3418        match &layout.box_type {
3419            crate::os_lib::layout::BoxType::BlockNode(styled)
3420            | crate::os_lib::layout::BoxType::InlineNode(styled)
3421            | crate::os_lib::layout::BoxType::InlineBlockNode(styled)
3422            | crate::os_lib::layout::BoxType::FlexNode(styled)
3423            | crate::os_lib::layout::BoxType::TableNode(styled)
3424            | crate::os_lib::layout::BoxType::TableRowGroupNode(styled)
3425            | crate::os_lib::layout::BoxType::TableRowNode(styled)
3426            | crate::os_lib::layout::BoxType::TableCellNode(styled) => {
3427                match &styled.node.node_type {
3428                    crate::os_lib::dom::NodeType::Element {
3429                        tag_name,
3430                        attributes,
3431                        classes,
3432                        ..
3433                    } => {
3434                        // body/html 要素のページ全体背景色・文字色をキャプチャ
3435                        if tag_name == "body" || tag_name == "html" {
3436                            if self.page_bg_color.is_none() {
3437                                let bg = styled
3438                                    .specified_values
3439                                    .get("background-color")
3440                                    .or_else(|| styled.specified_values.get("background"))
3441                                    .and_then(|s| crate::os_lib::css::parse_color(s));
3442                                if bg.is_some() {
3443                                    self.page_bg_color = bg;
3444                                } else {
3445                                    let is_dark = attributes.contains_key("dark")
3446                                        || attributes.get("theme").is_some_and(|t| t == "dark")
3447                                        || classes.iter().any(|c| c.contains("dark"))
3448                                        || styled.specified_values.get("color-scheme").is_some_and(|cs| cs.contains("dark"));
3449                                    if is_dark {
3450                                        self.page_bg_color = Some(0xFF0F0F0F);
3451                                    }
3452                                }
3453                            }
3454                            if self.page_text_color.is_none() {
3455                                let tc = styled
3456                                    .specified_values
3457                                    .get("color")
3458                                    .and_then(|s| crate::os_lib::css::parse_color(s));
3459                                if tc.is_some() {
3460                                    self.page_text_color = tc;
3461                                }
3462                            }
3463                        }
3464
3465                        // ::selection 疑似要素スタイルの解決(html/body または任意要素にマッチした宣言)
3466                        if styled.specified_values.contains_key("x-selection-background-color")
3467                            || styled.specified_values.contains_key("x-selection-background")
3468                            || styled.specified_values.contains_key("x-selection-color")
3469                        {
3470                            self.selection_style = super::selection_style::resolve_selection_style(
3471                                &styled.specified_values,
3472                                crate::os_lib::css::parse_color,
3473                            );
3474                        }
3475
3476                        let mut next_form_action = String::from(current_form_action);
3477                        let mut next_form_method = String::from(current_form_method);
3478                        let mut next_href = String::from(current_href);
3479                        if tag_name == "form" {
3480                            if let Some(action) = attributes.get("action") {
3481                                next_form_action = action.clone();
3482                            }
3483                            // フォームの中では method が必ず空でない(既定 GET)。ボタンが
3484                            // フォームに属するかの判定に使う(`render.rs` の送信)。
3485                            next_form_method = attributes
3486                                .get("method")
3487                                .filter(|m| !m.trim().is_empty())
3488                                .cloned()
3489                                .unwrap_or_else(|| String::from("GET"));
3490                        }
3491                        if tag_name == "a" {
3492                            if let Some(h) = attributes.get("href") {
3493                                next_href = h.clone();
3494                            }
3495                        }
3496
3497                        // `border-radius` 系の値は、`%` 指定(例: 正円アバターの定番
3498                        // `border-radius: 50%`)を要素サイズ(`container_w`)に対する
3499                        // 割合として解決する必要があるため、要素サイズが確定する
3500                        // `container_w`/`container_h` 計算後(本関数の下方)まで
3501                        // 生の CSS 文字列のまま保持しておく(2026-07-14。以前は
3502                        // ここで即座に px 解析しており `%` は常に「暫定で 0」に
3503                        // 切り捨てられ、`border-radius: 50%` 等が静かに無効化されて
3504                        // いたバグを修正)。
3505                        let border_radius_shorthand =
3506                            styled.specified_values.get("border-radius").cloned();
3507                        let border_radius_tl =
3508                            styled.specified_values.get("border-top-left-radius").cloned();
3509                        let border_radius_tr =
3510                            styled.specified_values.get("border-top-right-radius").cloned();
3511                        let border_radius_br =
3512                            styled.specified_values.get("border-bottom-right-radius").cloned();
3513                        let border_radius_bl =
3514                            styled.specified_values.get("border-bottom-left-radius").cloned();
3515
3516                        // 継承スタイルコンテキストを計算
3517                        let mut next_font_bold = current_font_bold;
3518                        let mut next_font_italic = current_font_italic;
3519                        let mut next_underline = current_underline;
3520                        let mut next_line_through = current_line_through;
3521                        let mut next_overline = current_overline;
3522                        let mut next_color: Option<u32> = current_color;
3523                        let mut next_font_size: u32 = current_font_size;
3524                        let mut next_decoration_color = current_decoration_color;
3525                        let mut next_decoration_style = current_decoration_style.clone();
3526                        let mut next_decoration_thickness = current_decoration_thickness;
3527                        let mut next_decoration_underline_offset = current_decoration_underline_offset;
3528                        // pointer-events: none は継承する(inherited)。子孫で明示的に auto に
3529                        // 戻すケース(`pointer-events:auto` による部分的な復元)は非対応の簡略実装。
3530                        let mut next_pointer_events_none = current_pointer_events_none;
3531                        if let Some(pe) = styled.value("pointer-events") {
3532                            let pe_l = pe.trim().to_lowercase();
3533                            if pe_l == "none" {
3534                                next_pointer_events_none = true;
3535                            } else if pe_l == "auto" {
3536                                next_pointer_events_none = false;
3537                            }
3538                        }
3539                        if let Some(dc) = styled.value("text-decoration-color") {
3540                            if let Some(c) = crate::os_lib::css::parse_color(dc.trim()) {
3541                                next_decoration_color = Some(c);
3542                            }
3543                        }
3544                        if let Some(ds) = styled.value("text-decoration-style") {
3545                            let ds_l = ds.trim().to_lowercase();
3546                            if matches!(ds_l.as_str(), "solid" | "dotted" | "dashed" | "wavy" | "double") {
3547                                next_decoration_style = ds_l;
3548                            }
3549                        }
3550                        if let Some(dt) = styled.value("text-decoration-thickness") {
3551                            let dt_t = dt.trim();
3552                            if !dt_t.eq_ignore_ascii_case("auto") && !dt_t.eq_ignore_ascii_case("from-font") {
3553                                next_decoration_thickness = parse_px_val(dt_t).max(1);
3554                            }
3555                        }
3556                        if let Some(uo) = styled.value("text-underline-offset") {
3557                            let uo_t = uo.trim();
3558                            if !uo_t.eq_ignore_ascii_case("auto") {
3559                                next_decoration_underline_offset = parse_px_val(uo_t);
3560                            }
3561                        }
3562                        // `text-decoration-line`(CSS Text Decoration Module Level 3の
3563                        // ロングハンド。`-color`/`-style`/`-thickness` は既に対応済みだったが
3564                        // 肝心の `-line` 単体指定だけが完全に無視され、`text-decoration`
3565                        // ショートハンド経由でしか下線等を付けられなかった)。
3566                        if let Some(tdl) = styled.value("text-decoration-line") {
3567                            let (u, lt, ov, is_none, _, _) = parse_text_decoration_shorthand(&tdl);
3568                            if is_none {
3569                                next_underline = false;
3570                                next_line_through = false;
3571                                next_overline = false;
3572                            } else {
3573                                if u {
3574                                    next_underline = true;
3575                                }
3576                                if lt {
3577                                    next_line_through = true;
3578                                }
3579                                if ov {
3580                                    next_overline = true;
3581                                }
3582                            }
3583                        }
3584                        if let Some(fw) = styled.value("font-weight") {
3585                            let fw_l = fw.trim().to_lowercase();
3586                            if fw_l == "bold"
3587                                || fw_l == "bolder"
3588                                || fw_l.parse::<u32>().unwrap_or(400) >= 700
3589                            {
3590                                next_font_bold = true;
3591                            } else if fw_l == "normal" || fw_l.parse::<u32>().unwrap_or(400) < 700 {
3592                                next_font_bold = false;
3593                            }
3594                        }
3595                        if let Some(fs) = styled.value("font-style") {
3596                            let fs_l = fs.trim().to_lowercase();
3597                            if fs_l == "italic" || fs_l == "oblique" {
3598                                next_font_italic = true;
3599                            } else if fs_l == "normal" {
3600                                next_font_italic = false;
3601                            }
3602                        }
3603                        if let Some(td) = styled.value("text-decoration") {
3604                            let (u, lt, ov, is_none, style, color) =
3605                                parse_text_decoration_shorthand(&td);
3606                            if is_none {
3607                                next_underline = false;
3608                                next_line_through = false;
3609                                next_overline = false;
3610                            } else {
3611                                if u {
3612                                    next_underline = true;
3613                                }
3614                                if lt {
3615                                    next_line_through = true;
3616                                }
3617                                if ov {
3618                                    next_overline = true;
3619                                }
3620                                if let Some(s) = style {
3621                                    next_decoration_style = s;
3622                                }
3623                                if let Some(c) = color {
3624                                    next_decoration_color = Some(c);
3625                                }
3626                            }
3627                        }
3628                        if tag_name == "b" || tag_name == "strong" {
3629                            next_font_bold = true;
3630                        }
3631                        if tag_name == "i" || tag_name == "em" {
3632                            next_font_italic = true;
3633                        }
3634                        if tag_name == "u" {
3635                            next_underline = true;
3636                        }
3637                        if tag_name == "s" || tag_name == "del" || tag_name == "strike" {
3638                            next_line_through = true;
3639                        }
3640                        let effective_color_str = styled
3641                            .value("-webkit-text-fill-color")
3642                            .or_else(|| styled.value("color"));
3643                        if let Some(c_str) = effective_color_str {
3644                            if let Some(c_val) = parse_color(&c_str) {
3645                                let is_bg_clip_text = styled.value("background-clip").as_deref().map(str::trim) == Some("text")
3646                                    || styled.value("-webkit-background-clip").as_deref().map(str::trim) == Some("text");
3647                                if (c_val >> 24) == 0 && is_bg_clip_text {
3648                                    if next_color.is_none() {
3649                                        next_color = Some(0xFF000000);
3650                                    }
3651                                } else {
3652                                    next_color = Some(c_val);
3653                                }
3654                            }
3655                        }
3656                        if let Some(sz_str) = styled.value("font-size") {
3657                            if let Some(sz_val) = parse_font_size(&sz_str) {
3658                                next_font_size = sz_val;
3659                            }
3660                        }
3661                        let aspect_ratio_val = styled
3662                            .value("aspect-ratio")
3663                            .and_then(|v| parse_aspect_ratio(&v));
3664
3665                        let is_hr = tag_name == "hr";
3666                        // 【2026-10-24】インライン `<svg>` は描画した画素を画像キャッシュに置き、`<img>` と
3667                        // 同じ経路で描く(`inline_svg`)。鍵が src の代わりになる。
3668                        let inline_svg_src: Option<String> = if tag_name == "svg" {
3669                            self.rasterize_inline_svg(
3670                                styled,
3671                                layout.dimensions.content.width,
3672                                layout.dimensions.content.height,
3673                            )
3674                        } else {
3675                            None
3676                        };
3677                        let is_img = tag_name == "img" || inline_svg_src.is_some();
3678                        // 【2026-09-03】`<canvas>` の 2D コンテキスト id。
3679                        //
3680                        // `getContext("2d")` が呼ばれると JS 側が
3681                        // `_c2d_id` 属性へ registry の id を書く。ここで拾って
3682                        // `RenderElement` へ載せ、描画時に `Surface` の内容を
3683                        // 要素の矩形へ転送する。
3684                        //
3685                        // DOM 属性を経由するのは、レイアウトが `StyledNode`
3686                        // しか見ないため。JS のオブジェクトを直接引くと
3687                        // 層をまたぐ依存になる。
3688                        let canvas_ctx_id: Option<u32> = if tag_name == "canvas" {
3689                            attributes
3690                                .get("_c2d_id")
3691                                .and_then(|s| s.trim().parse::<u32>().ok())
3692                        } else {
3693                            None
3694                        };
3695                        let is_video = tag_name == "video";
3696                        // <progress>/<meter>(HTML5 ネイティブ進捗/計量バー)。`<img>`/`<video>` と
3697                        // 同じ「置換要素」として扱い、専用の RenderElement を構築する。
3698                        // <meter> の low/high/optimum による色分けは非対応(常に同じ色で描画)。
3699                        let is_progress = tag_name == "progress" || tag_name == "meter";
3700                        let progress_ratio: f32 = if is_progress {
3701                            let parse_f32 = |k: &str, default: f32| -> f32 {
3702                                attributes
3703                                    .get(k)
3704                                    .and_then(|v| v.trim().parse::<f32>().ok())
3705                                    .unwrap_or(default)
3706                            };
3707                            let min = if tag_name == "meter" { parse_f32("min", 0.0) } else { 0.0 };
3708                            let max = parse_f32("max", 1.0);
3709                            let value = parse_f32("value", min);
3710                            let range = (max - min).max(0.0001);
3711                            ((value - min) / range).clamp(0.0, 1.0)
3712                        } else {
3713                            0.0
3714                        };
3715                        let mut is_input = tag_name == "input";
3716                        let is_textarea = tag_name == "textarea";
3717                        let mut is_button = tag_name == "button";
3718                        let is_select = tag_name == "select";
3719                        let mut is_reset_btn = false;
3720
3721                        // input 種別判定: checkbox/radio はトグル要素、submit/button/reset はボタン。
3722                        let mut input_kind: u8 = 0;
3723                        if is_input {
3724                            if let Some(t) = attributes.get("type") {
3725                                let tl = t.trim().to_lowercase();
3726                                if tl == "submit" || tl == "button" || tl == "reset" {
3727                                    is_input = false;
3728                                    is_button = true;
3729                                    if tl == "reset" {
3730                                        is_reset_btn = true;
3731                                    }
3732                                } else if tl == "checkbox" {
3733                                    input_kind = 1;
3734                                } else if tl == "radio" {
3735                                    input_kind = 2;
3736                                } else if tl == "range" {
3737                                    input_kind = 5;
3738                                }
3739                            }
3740                        }
3741                        if is_select {
3742                            input_kind = 3;
3743                        }
3744                        // <button type="reset"> も reset ボタンとして扱う。
3745                        // `type="button"`(<button>・<input>)は送信しない(`no_submit`)。
3746                        let mut no_submit = false;
3747                        if tag_name == "button" || tag_name == "input" {
3748                            if let Some(t) = attributes.get("type") {
3749                                if t.trim().eq_ignore_ascii_case("reset") && tag_name == "button" {
3750                                    is_reset_btn = true;
3751                                }
3752                                if t.trim().eq_ignore_ascii_case("button") {
3753                                    no_submit = true;
3754                                }
3755                            }
3756                        }
3757
3758                        let mut el_id = String::new();
3759                        if let Some(id_val) = attributes.get("id") {
3760                            el_id = id_val.clone();
3761                        } else if let Some(name_val) = attributes.get("name") {
3762                            el_id = name_val.clone();
3763                        }
3764                        // フォーム送信のパラメータ名は `name` 属性を用いる(element_id とは別物)。
3765                        // id を持つ入力でも name で送信されるよう element_id → name を記録する。
3766                        if (is_input || is_textarea) && !el_id.is_empty() {
3767                            if let Some(name_val) = attributes.get("name") {
3768                                self.field_names.insert(el_id.clone(), name_val.clone());
3769                            }
3770                        }
3771
3772                        let mut onclick = String::new();
3773                        if let Some(oc) = attributes.get("onclick") {
3774                            onclick = oc.clone();
3775                        }
3776
3777                        let mut next_parent_id = String::from(parent_id);
3778                        if !el_id.is_empty() {
3779                            next_parent_id = el_id.clone();
3780                        }
3781
3782                        // --- New CSS features: position, opacity, box-shadow, white-space, text-overflow, linear-gradient ---
3783                        let position_val = styled
3784                            .value("position")
3785                            .unwrap_or_else(|| String::from("static"));
3786                        // `inset` ショートハンド(top/right/bottom/left の一括指定。CSS Box
3787                        // Alignment/Positioning。margin と同じ1〜4値の展開規則)。個別の
3788                        // longhand(top/left/right/bottom)が明示されていればそちらを優先する。
3789                        let inset_val = styled.value("inset");
3790                        fn inset_component(shorthand: &str, side: usize) -> Option<&str> {
3791                            // side: 0=top, 1=right, 2=bottom, 3=left
3792                            let toks: alloc::vec::Vec<&str> = shorthand.split_whitespace().collect();
3793                            match toks.len() {
3794                                1 => toks.first().copied(),
3795                                2 => match side {
3796                                    0 | 2 => toks.first().copied(),
3797                                    _ => toks.get(1).copied(),
3798                                },
3799                                3 => match side {
3800                                    0 => toks.first().copied(),
3801                                    2 => toks.get(2).copied(),
3802                                    _ => toks.get(1).copied(),
3803                                },
3804                                4 => toks.get(side).copied(),
3805                                _ => None,
3806                            }
3807                        }
3808                        let parse_pos = |v: &str| parse_pos_len(v, next_font_size as f32);
3809                        let pos_top = styled.value("top").and_then(|v| parse_pos(&v)).or_else(
3810                            || inset_val.as_deref().and_then(|s| inset_component(s, 0)).and_then(parse_pos),
3811                        );
3812                        let pos_left = styled.value("left").and_then(|v| parse_pos(&v)).or_else(
3813                            || inset_val.as_deref().and_then(|s| inset_component(s, 3)).and_then(parse_pos),
3814                        );
3815                        let pos_right = styled.value("right").and_then(|v| parse_pos(&v)).or_else(
3816                            || inset_val.as_deref().and_then(|s| inset_component(s, 1)).and_then(parse_pos),
3817                        );
3818                        let pos_bottom = styled.value("bottom").and_then(|v| parse_pos(&v)).or_else(
3819                            || inset_val.as_deref().and_then(|s| inset_component(s, 2)).and_then(parse_pos),
3820                        );
3821                        // `z-index` は position が static(既定値)以外のときにのみ効果を持つ
3822                        // 仕様(CSS2.1/CSS3)。以前は position を一切見ておらず、static な
3823                        // 要素にも `z-index` がそのまま適用されてしまい、意図しない重なり順に
3824                        // なるバグがあった。
3825                        let own_z = if position_val == "static" {
3826                            0
3827                        } else {
3828                            styled
3829                                .value("z-index")
3830                                .and_then(|v| v.trim().parse::<i32>().ok())
3831                                .unwrap_or(0)
3832                        };
3833                        // 【2026-07-28】祖先の実効 z まで引き上げる。
3834                        // これをやらないと `section{position:relative;z-index:5}` の
3835                        // static な子孫(z=0)が section より前に描かれ、直後に
3836                        // section の背景で丸ごと塗り潰される(実際に踏んだ回帰)。
3837                        // 仕様と不変条件は `spec/paint_order.md` を参照。
3838                        let z_index_val = super::paint_order::effective_z(
3839                            own_z,
3840                            Some(self.inherited_paint_z),
3841                        );
3842                        let opacity_val: u8 = styled
3843                            .value("opacity")
3844                            .and_then(|v| {
3845                                v.trim()
3846                                    .parse::<f32>()
3847                                    .ok()
3848                                    .map(|f| (f.clamp(0.0, 1.0) * 255.0) as u8)
3849                            })
3850                            .unwrap_or(255);
3851
3852                        let is_fixed_pos = position_val == "fixed";
3853                        let is_sticky_pos = position_val == "sticky";
3854                        let is_positioned_self = position_val != "static";
3855
3856                        // スタッキングコンテキストの生成判定(CSS 2.1 Appendix E, CSS Color 3, CSS Transforms 1, Filter Effects 1)
3857                        let has_transform = styled.value("transform").is_some_and(|v| {
3858                            let t = v.trim();
3859                            !t.is_empty() && t != "none"
3860                        });
3861                        let has_filter = styled.value("filter").is_some_and(|v| {
3862                            let t = v.trim();
3863                            !t.is_empty() && t != "none"
3864                        });
3865                        let has_backdrop_filter = styled.value("backdrop-filter").is_some_and(|v| {
3866                            let t = v.trim();
3867                            !t.is_empty() && t != "none"
3868                        });
3869                        let has_opacity = opacity_val < 255;
3870                        let has_isolation = styled.value("isolation").is_some_and(|v| v.trim() == "isolate");
3871                        let has_contain = styled.value("contain").is_some_and(|v| {
3872                            let t = v.trim();
3873                            t.contains("paint") || t.contains("layout") || t.contains("strict") || t.contains("content")
3874                        });
3875
3876                        // この箱の文書順と、スタッキングコンテキストを作るか
3877                        let my_seq = self.elements.len() as u32;
3878                        let creates_stacking_ctx = is_fixed_pos
3879                            || is_sticky_pos
3880                            || (is_positioned_self
3881                                && styled.value("z-index").is_some_and(|v| v.trim().parse::<i32>().is_ok()))
3882                            || has_opacity
3883                            || has_transform
3884                            || has_filter
3885                            || has_backdrop_filter
3886                            || has_isolation
3887                            || has_contain;
3888                        let is_positioned_effective = is_positioned_self || self.inherited_positioned;
3889                        let establishes_fixed_cb = crate::os_lib::layout::styled_establishes_fixed_cb(styled);
3890                        let establishes_abs_cb = is_positioned_self || establishes_fixed_cb;
3891
3892                        // overflow: hidden/scroll/auto/clip は子孫をこの要素の content box でクリップする。
3893                        // scroll/auto のときはさらにサブスクロールコンテナとして扱う。
3894                        // `overflow` ショートハンドは `<overflow-x>`(1値なら両軸に適用)または
3895                        // `<overflow-x> <overflow-y>`(2値)を受け付ける。
3896                        let (overflow_x_val, overflow_y_val) = match styled.value("overflow") {
3897                            Some(v) => {
3898                                let toks: alloc::vec::Vec<&str> = v.split_whitespace().collect();
3899                                match toks.as_slice() {
3900                                    [x, y] => (String::from(*x), String::from(*y)),
3901                                    [xy] => (String::from(*xy), String::from(*xy)),
3902                                    _ => (String::new(), String::new()),
3903                                }
3904                            }
3905                            None => (
3906                                styled.value("overflow-x").unwrap_or_default(),
3907                                styled.value("overflow-y").unwrap_or_default(),
3908                            ),
3909                        };
3910                        // `html`・`body` の overflow はビューポート(ページのスクロール)へ伝わる
3911                        // (CSS Overflow 3 §3.3)。それ自体は切り取りもスクロール領域も作らない。
3912                        // 【2026-10-24】YouTube の `body` の overflow を高さ 0 のスクロール領域として扱い、
3913                        // 全要素がその中に入ってページがスクロールできず、動画の下が見えなかった。
3914                        let propagates_to_viewport = matches!(tag_name.as_str(), "html" | "body");
3915                        let axis_clips = |v: &str| {
3916                            !propagates_to_viewport && matches!(v.trim(), "hidden" | "scroll" | "auto" | "clip")
3917                        };
3918                        let axis_scrolls = |v: &str| !propagates_to_viewport && matches!(v.trim(), "scroll" | "auto");
3919                        // 軸ごとに独立してクリップするか判定する。以前は x/y いずれかが該当すれば
3920                        // 矩形1つ丸ごとをクリップに使っていたため、`overflow-x:hidden;
3921                        // overflow-y:visible`(またはその逆)のような軸ごとに異なる指定で、
3922                        // 本来クリップされないはずの軸まで誤ってクリップされてしまうバグがあった。
3923                        let x_clips = axis_clips(&overflow_x_val);
3924                        let y_clips = axis_clips(&overflow_y_val);
3925                        let overflow_clips = x_clips || y_clips;
3926                        // scroll/auto: 独立スクロール領域を作る(element_id が必要)。
3927                        let is_scroll_container =
3928                            axis_scrolls(&overflow_x_val) || axis_scrolls(&overflow_y_val);
3929
3930                        let _white_space_nowrap = styled
3931                            .value("white-space")
3932                            .map(|v| v.trim() == "nowrap")
3933                            .unwrap_or(false);
3934                        let _text_overflow_ellipsis = styled
3935                            .value("text-overflow")
3936                            .map(|v| v.trim() == "ellipsis")
3937                            .unwrap_or(false);
3938
3939                        // Parse box-shadow: `<Xpx> <Ypx> [<Blur>px] [<color>] [inset]` を
3940                        // 最上位カンマで区切った複数シャドウに対応(box-shadow の値自体に
3941                        // 括弧を含む余地は無いため、単純な `,` 分割で安全に複数シャドウを
3942                        // 分離できる)。各セグメントを独立してトークン解析する。
3943                        // オフセット/ぼかしの長さトークン解決は`parse_shadow_len_tok`
3944                        // (モジュールトップレベル。丸ごと未対応だった`rem`単位を
3945                        // 2026-07-17に追加。詳細は同関数のdocコメント参照)を使う。
3946                        // 【2026-09-26】解析は純粋モジュール `box_shadow`(試験あり)へ。
3947                        // 従来は空白で単純に分割して `rgba(0, 0, 0, 0.1)` を壊し、既定の
3948                        // 50% の黒で塗っていた(カードの影が濃い灰色の塊になっていた)。
3949                        let mut box_shadow: alloc::vec::Vec<(i32, i32, i32, u32, bool)> = styled
3950                            .value("box-shadow")
3951                            .map(|v| super::box_shadow::parse_list_with_font(&v.to_lowercase(), next_font_size as f32))
3952                            .unwrap_or_default();
3953
3954                        // `filter: drop-shadow()` は描いた内容の形に付く影。形を持たない描画なので、
3955                        // 背景のある箱に限って矩形の影で近似する。背景の無い要素(文字やアイコンだけ)に
3956                        // 付けると、中身の形ではなく要素の矩形が丸ごと塗られてしまう
3957                        // (YouTube のロゴの位置に四角が出ていた、2026-11-01)。
3958                        if box_shadow.is_empty() {
3959                            let has_bg = extract_color(styled, "background-color", "background")
3960                                .is_some_and(|c| c >> 24 != 0)
3961                                || styled.value("background-image").is_some_and(|v| v.contains('('));
3962                            if has_bg {
3963                                if let Some(ds) = styled
3964                                    .value("filter")
3965                                    .and_then(|f| super::box_shadow::drop_shadow_from_filter(&f))
3966                                {
3967                                    box_shadow.push(ds);
3968                                }
3969                            }
3970                        }
3971
3972                        // Parse linear-gradient from background or background-image
3973                        let linear_gradient = {
3974                            let bg_val = styled
3975                                .value("background")
3976                                .or_else(|| styled.value("background-image"));
3977                            bg_val.and_then(|v| {
3978                                let v_lower = v.to_lowercase();
3979                                if !v_lower.contains("linear-gradient")
3980                                    || v_lower.contains("repeating-linear-gradient")
3981                                {
3982                                    return None;
3983                                }
3984                                // `rgba(...)` が引数に入るため、単純な find(')') では
3985                                // rgba の閉じ括弧を拾って定義が壊れる(実際に踏んだ回帰)。
3986                                // 入れ子対応の対応括弧探索を使う。
3987                                let open_paren = v_lower.find("linear-gradient(")? + 15;
3988                                let inner_start = open_paren + 1;
3989                                let inner_end =
3990                                    super::css_units::find_balanced_close(&v, open_paren)?;
3991                                let inner = v.get(inner_start..inner_end)?;
3992                                let mut parts = super::css_units::split_top_level_commas(inner).into_iter();
3993                                let first = parts.next()?.trim();
3994                                
3995                                let mut angle_deg = 180.0; // default to bottom
3996                                let mut is_first_color = true;
3997                                
3998                                // 角度や方向の判定
3999                                let first_lower = first.to_lowercase();
4000                                if first_lower.starts_with("to ") {
4001                                    if first_lower == "to top" { angle_deg = 0.0; }
4002                                    else if first_lower == "to right" { angle_deg = 90.0; }
4003                                    else if first_lower == "to bottom" { angle_deg = 180.0; }
4004                                    else if first_lower == "to left" { angle_deg = 270.0; }
4005                                    else if first_lower == "to top right" || first_lower == "to right top" { angle_deg = 45.0; }
4006                                    else if first_lower == "to bottom right" || first_lower == "to right bottom" { angle_deg = 135.0; }
4007                                    else if first_lower == "to bottom left" || first_lower == "to left bottom" { angle_deg = 225.0; }
4008                                    else if first_lower == "to top left" || first_lower == "to left top" { angle_deg = 315.0; }
4009                                    is_first_color = false;
4010                                } else if let Some(deg) = super::css_units::parse_angle_to_deg(&first_lower) {
4011                                    angle_deg = deg;
4012                                    is_first_color = false;
4013                                }
4014                                
4015                                let mut raw_stops = alloc::vec::Vec::new();
4016                                if is_first_color {
4017                                    raw_stops.push(first);
4018                                }
4019                                for p in parts {
4020                                    raw_stops.push(p.trim());
4021                                }
4022                                
4023                                let mut stops = alloc::vec::Vec::new();
4024                                for (i, s) in raw_stops.iter().enumerate() {
4025                                    let mut tokens = s.split_whitespace();
4026                                    if let Some(c_str) = tokens.next() {
4027                                        if let Some(c) = parse_color(c_str) {
4028                                            let mut pos = None;
4029                                            if let Some(p_str) = tokens.next() {
4030                                                if p_str.ends_with('%') {
4031                                                    if let Ok(v) = p_str.trim_end_matches('%').parse::<f32>() {
4032                                                        pos = Some(v / 100.0);
4033                                                    }
4034                                                }
4035                                            }
4036                                            stops.push((c, pos));
4037                                        }
4038                                    }
4039                                }
4040                                
4041                                if stops.len() < 2 {
4042                                    return None;
4043                                }
4044                                
4045                                // 位置の自動計算 (省略されている場合)
4046                                let n = stops.len();
4047                                if stops[0].1.is_none() { stops[0].1 = Some(0.0); }
4048                                if stops[n-1].1.is_none() { stops[n-1].1 = Some(1.0); }
4049                                
4050                                let mut final_stops = alloc::vec::Vec::new();
4051                                let mut last_pos = 0.0;
4052                                for i in 0..n {
4053                                    if let Some(p) = stops[i].1 {
4054                                        last_pos = p;
4055                                    } else {
4056                                        // Find next specified position
4057                                        let mut next_pos = 1.0;
4058                                        let mut next_idx = n - 1;
4059                                        for j in i+1..n {
4060                                            if let Some(p) = stops[j].1 {
4061                                                next_pos = p;
4062                                                next_idx = j;
4063                                                break;
4064                                            }
4065                                        }
4066                                        let step = (next_pos - last_pos) / ((next_idx - i + 1) as f32);
4067                                        last_pos += step;
4068                                    }
4069                                    final_stops.push(super::GradientStop {
4070                                        color: stops[i].0,
4071                                        position: last_pos,
4072                                    });
4073                                }
4074
4075                                Some(super::LinearGradient {
4076                                    angle_deg,
4077                                    stops: final_stops,
4078                                })
4079                            })
4080                        };
4081
4082                        // Parse radial-gradient(circle, c1, c2) from background/background-image.
4083                        // 楕円形状・位置指定は非対応で、常に矩形の中心を起点とする簡略実装。
4084                        let radial_gradient = {
4085                            let bg_val = styled
4086                                .value("background")
4087                                .or_else(|| styled.value("background-image"));
4088                            bg_val.and_then(|v| {
4089                                let v_lower = v.to_lowercase();
4090                                if !v_lower.contains("radial-gradient")
4091                                    || v_lower.contains("repeating-radial-gradient")
4092                                {
4093                                    return None;
4094                                }
4095                                let inner_start = v_lower.find("radial-gradient(")? + 17;
4096                                let inner_end =
4097                                    v_lower.get(inner_start..)?.find(')')? + inner_start;
4098                                let inner = v.get(inner_start..inner_end)?;
4099                                let mut parts = inner.split(',');
4100                                let first = parts.next()?.trim();
4101                                
4102                                let mut shape = super::RadialShape::Ellipse;
4103                                let mut pos_x = 0.5;
4104                                let mut pos_y = 0.5;
4105                                let mut is_first_color = true;
4106                                
4107                                let first_lower = first.to_lowercase();
4108                                if first_lower.contains("circle") || first_lower.contains("ellipse") || first_lower.contains("at ") {
4109                                    is_first_color = false;
4110                                    if first_lower.contains("circle") {
4111                                        shape = super::RadialShape::Circle;
4112                                    }
4113                                    if let Some(at_idx) = first_lower.find("at ") {
4114                                        let pos_str = first_lower.get(at_idx + 3..)?;
4115                                        let mut pos_tokens = pos_str.split_whitespace();
4116                                        if let Some(x_str) = pos_tokens.next() {
4117                                            if x_str == "left" { pos_x = 0.0; }
4118                                            else if x_str == "right" { pos_x = 1.0; }
4119                                            else if x_str == "center" { pos_x = 0.5; }
4120                                            else if x_str.ends_with('%') {
4121                                                if let Ok(v) = x_str.trim_end_matches('%').parse::<f32>() {
4122                                                    pos_x = v / 100.0;
4123                                                }
4124                                            }
4125                                        }
4126                                        if let Some(y_str) = pos_tokens.next() {
4127                                            if y_str == "top" { pos_y = 0.0; }
4128                                            else if y_str == "bottom" { pos_y = 1.0; }
4129                                            else if y_str == "center" { pos_y = 0.5; }
4130                                            else if y_str.ends_with('%') {
4131                                                if let Ok(v) = y_str.trim_end_matches('%').parse::<f32>() {
4132                                                    pos_y = v / 100.0;
4133                                                }
4134                                            }
4135                                        } else {
4136                                            pos_y = pos_x; // 1つだけ指定された場合の中央寄せなど (厳密な仕様ではないが簡略)
4137                                        }
4138                                    }
4139                                }
4140                                
4141                                let mut raw_stops = alloc::vec::Vec::new();
4142                                if is_first_color {
4143                                    raw_stops.push(first);
4144                                }
4145                                for p in parts {
4146                                    raw_stops.push(p.trim());
4147                                }
4148                                
4149                                let mut stops = alloc::vec::Vec::new();
4150                                for (i, s) in raw_stops.iter().enumerate() {
4151                                    let mut tokens = s.split_whitespace();
4152                                    if let Some(c_str) = tokens.next() {
4153                                        if let Some(c) = parse_color(c_str) {
4154                                            let mut pos = None;
4155                                            if let Some(p_str) = tokens.next() {
4156                                                if p_str.ends_with('%') {
4157                                                    if let Ok(v) = p_str.trim_end_matches('%').parse::<f32>() {
4158                                                        pos = Some(v / 100.0);
4159                                                    }
4160                                                }
4161                                            }
4162                                            stops.push((c, pos));
4163                                        }
4164                                    }
4165                                }
4166                                
4167                                if stops.len() < 2 {
4168                                    return None;
4169                                }
4170                                
4171                                let n = stops.len();
4172                                if stops[0].1.is_none() { stops[0].1 = Some(0.0); }
4173                                if stops[n-1].1.is_none() { stops[n-1].1 = Some(1.0); }
4174                                
4175                                let mut final_stops = alloc::vec::Vec::new();
4176                                let mut last_pos = 0.0;
4177                                for i in 0..n {
4178                                    if let Some(p) = stops[i].1 {
4179                                        last_pos = p;
4180                                    } else {
4181                                        let mut next_pos = 1.0;
4182                                        let mut next_idx = n - 1;
4183                                        for j in i+1..n {
4184                                            if let Some(p) = stops[j].1 {
4185                                                next_pos = p;
4186                                                next_idx = j;
4187                                                break;
4188                                            }
4189                                        }
4190                                        let step = (next_pos - last_pos) / ((next_idx - i + 1) as f32);
4191                                        last_pos += step;
4192                                    }
4193                                    final_stops.push(super::GradientStop {
4194                                        color: stops[i].0,
4195                                        position: last_pos,
4196                                    });
4197                                }
4198
4199                                Some(super::RadialGradient {
4200                                    shape,
4201                                    pos_x,
4202                                    pos_y,
4203                                    stops: final_stops,
4204                                })
4205                            })
4206                        };
4207
4208                        // Parse conic-gradient(c1, c2, ...) from background/background-image.
4209                        // 全カラーストップを角度方向へ等間隔配置する(`from`/位置指定は非対応の
4210                        // 簡略実装、radial-gradient と同じ方針)。以前は先頭2色しか保持できない
4211                        // `(u32,u32)` だったため3色目以降が丸ごと失われるバグがあった。
4212                        let conic_gradient = {
4213                            let bg_val = styled
4214                                .value("background")
4215                                .or_else(|| styled.value("background-image"));
4216                            bg_val.and_then(|v| {
4217                                let v_lower = v.to_lowercase();
4218                                if !v_lower.contains("conic-gradient") {
4219                                    return None;
4220                                }
4221                                let inner_start = v_lower.find("conic-gradient(")? + 15;
4222                                let inner_end =
4223                                    v_lower.get(inner_start..)?.find(')')? + inner_start;
4224                                let inner = v.get(inner_start..inner_end)?;
4225                                let parts: Vec<&str> = inner.split(',').collect();
4226                                let colors: Vec<u32> = parts
4227                                    .iter()
4228                                    .filter_map(|p| parse_color(p.trim()))
4229                                    .collect();
4230                                if colors.len() < 2 {
4231                                    return None;
4232                                }
4233                                let n = colors.len();
4234                                let stops: alloc::vec::Vec<super::GradientStop> = colors
4235                                    .into_iter()
4236                                    .enumerate()
4237                                    .map(|(i, color)| super::GradientStop {
4238                                        color,
4239                                        position: i as f32 / (n - 1) as f32,
4240                                    })
4241                                    .collect();
4242                                Some(stops)
4243                            })
4244                        };
4245
4246                        // repeating-linear-gradient(c1 [len], c2 len, ...) / repeating-radial-gradient(...):
4247                        // 色トークンの中から末尾の px 長さトークンを周期(cycle_px)として使う簡略実装
4248                        // (角度/形状/位置指定は非対応、px 以外の単位も非対応)。全カラーストップを
4249                        // 収集し周期内で均等割り補間する(以前は先頭2色のみで3色目以降が失われていた)。
4250                        fn extract_px_cycle(parts: &[&str]) -> Option<i32> {
4251                            parts
4252                                .iter()
4253                                .rev()
4254                                .find_map(|p| {
4255                                    p.trim()
4256                                        .rsplit(' ')
4257                                        .next()
4258                                        .and_then(|tok| tok.strip_suffix("px"))
4259                                        .and_then(|n| n.parse::<i32>().ok())
4260                                })
4261                                .filter(|n| *n > 0)
4262                        }
4263                        let repeating_linear_gradient = {
4264                            let bg_val = styled
4265                                .value("background")
4266                                .or_else(|| styled.value("background-image"));
4267                            bg_val.and_then(|v| {
4268                                let v_lower = v.to_lowercase();
4269                                if !v_lower.contains("repeating-linear-gradient") {
4270                                    return None;
4271                                }
4272                                let inner_start = v_lower.find("repeating-linear-gradient(")? + 26;
4273                                let inner_end =
4274                                    v_lower.get(inner_start..)?.find(')')? + inner_start;
4275                                let inner = v.get(inner_start..inner_end)?;
4276                                let parts: Vec<&str> = inner.split(',').collect();
4277                                let colors: Vec<u32> = parts
4278                                    .iter()
4279                                    .filter_map(|p| parse_color(p.trim().split(' ').next().unwrap_or("")))
4280                                    .collect();
4281                                if colors.len() < 2 {
4282                                    return None;
4283                                }
4284                                let cycle = extract_px_cycle(&parts).unwrap_or(20);
4285                                let dir = parts[0].trim().to_lowercase();
4286                                let is_vertical =
4287                                    dir.contains("bottom") || dir == "180deg" || dir == "to bottom";
4288                                Some((colors, cycle, is_vertical))
4289                            })
4290                        };
4291                        let repeating_radial_gradient = {
4292                            let bg_val = styled
4293                                .value("background")
4294                                .or_else(|| styled.value("background-image"));
4295                            bg_val.and_then(|v| {
4296                                let v_lower = v.to_lowercase();
4297                                if !v_lower.contains("repeating-radial-gradient") {
4298                                    return None;
4299                                }
4300                                let inner_start = v_lower.find("repeating-radial-gradient(")? + 26;
4301                                let inner_end =
4302                                    v_lower.get(inner_start..)?.find(')')? + inner_start;
4303                                let inner = v.get(inner_start..inner_end)?;
4304                                let parts: Vec<&str> = inner.split(',').collect();
4305                                let colors: Vec<u32> = parts
4306                                    .iter()
4307                                    .filter_map(|p| parse_color(p.trim().split(' ').next().unwrap_or("")))
4308                                    .collect();
4309                                if colors.len() < 2 {
4310                                    return None;
4311                                }
4312                                let cycle = extract_px_cycle(&parts).unwrap_or(20);
4313                                Some((colors, cycle))
4314                            })
4315                        };
4316
4317                        // `visibility: collapse` は本来テーブル行/列専用の特殊な折りたたみ
4318                        // レイアウト(行/列自体の高さ/幅を無くす)を持つが、この処理系はその
4319                        // 専用レイアウトを実装していない。以前は `collapse` が文字列として
4320                        // `"hidden"` と一致しないため何の効果も持たず(可視のまま描画される)、
4321                        // 完全に無視されていた。テーブル行/列以外の要素では仕様上も
4322                        // `collapse` は `hidden` と同じ扱いでよいとされているため、
4323                        // 専用レイアウト非対応を許容しつつ `hidden` と同一視する簡略実装とする
4324                        // (何もしないよりは大幅に改善、他の多くの簡略実装と同じ妥協水準)。
4325                        let visibility_hidden = styled
4326                            .value("visibility")
4327                            .map(|v| matches!(v.trim(), "hidden" | "collapse"))
4328                            .unwrap_or(false);
4329
4330                        // コンテナ背景・ボーダー要素の追加
4331                        let container_x = layout.dimensions.content.x
4332                            - layout.dimensions.padding.left
4333                            - layout.dimensions.border.left;
4334                        let container_y = layout.dimensions.content.y
4335                            - layout.dimensions.padding.top
4336                            - layout.dimensions.border.top;
4337                        let container_w = layout.dimensions.content.width
4338                            + layout.dimensions.padding.left
4339                            + layout.dimensions.padding.right
4340                            + layout.dimensions.border.left
4341                            + layout.dimensions.border.right;
4342                        let container_h = layout.dimensions.content.height
4343                            + layout.dimensions.padding.top
4344                            + layout.dimensions.padding.bottom
4345                            + layout.dimensions.border.top
4346                            + layout.dimensions.border.bottom;
4347
4348                        // `border-radius` の `%` 値を要素サイズに対する割合として
4349                        // 解決する(`border-radius: <h-radii> / <v-radii>` の楕円角
4350                        // 構文は非対応のため水平半径のみを円弧として使う従来どおりの
4351                        // 簡略実装。`%` は仕様上コーナーごとに対応する軸(水平半径は
4352                        // 幅、垂直半径は高さ)に対する割合だが、この実装は水平半径
4353                        // しか保持しないため常に `container_w` を基準にする)。
4354                        // `rem`対応は`resolve_border_radius`(モジュールトップレベル。
4355                        // 丸ごと未対応だった。2026-07-17)参照。
4356                        let parse_radius = |s: &str| -> i32 { resolve_border_radius_with_font(s, container_w, next_font_size as f32) };
4357                        let mut border_radius = (0, 0, 0, 0);
4358                        if let Some(s) = &border_radius_shorthand {
4359                            let h_part = s.split('/').next().unwrap_or(s);
4360                            let parts: alloc::vec::Vec<&str> = h_part.split_whitespace().collect();
4361                            if parts.len() == 1 {
4362                                let v = parse_radius(parts[0]);
4363                                border_radius = (v, v, v, v);
4364                            } else if parts.len() == 2 {
4365                                let v1 = parse_radius(parts[0]);
4366                                let v2 = parse_radius(parts[1]);
4367                                border_radius = (v1, v2, v1, v2);
4368                            } else if parts.len() == 3 {
4369                                let v1 = parse_radius(parts[0]);
4370                                let v2 = parse_radius(parts[1]);
4371                                let v3 = parse_radius(parts[2]);
4372                                border_radius = (v1, v2, v3, v2);
4373                            } else if parts.len() >= 4 {
4374                                border_radius = (
4375                                    parse_radius(parts[0]),
4376                                    parse_radius(parts[1]),
4377                                    parse_radius(parts[2]),
4378                                    parse_radius(parts[3]),
4379                                );
4380                            }
4381                        }
4382                        if let Some(s) = &border_radius_tl { border_radius.0 = parse_radius(s); }
4383                        if let Some(s) = &border_radius_tr { border_radius.1 = parse_radius(s); }
4384                        if let Some(s) = &border_radius_br { border_radius.2 = parse_radius(s); }
4385                        if let Some(s) = &border_radius_bl { border_radius.3 = parse_radius(s); }
4386
4387                        let bg_color = extract_color(styled, "background-color", "background");
4388                        // 【2026-08-03診断】研究セクションの背景確認(デバッグ用)。
4389                        // if bg_color.is_none() && layout.dimensions.content.height > 800 {
4390                        //     static ONCE: core::sync::atomic::AtomicU32 =
4391                        //         core::sync::atomic::AtomicU32::new(0);
4392                        //     if ONCE.fetch_add(1, core::sync::atomic::Ordering::Relaxed) < 4 {
4393                        //         crate::debug!(
4394                        //             "[BGDIAG] tag={} h={} background-color={:?} background={:?} class={:?}",
4395                        //             tag_name,
4396                        //             layout.dimensions.content.height,
4397                        //             styled.value("background-color"),
4398                        //             styled.value("background"),
4399                        //             styled.value("x-class-debug")
4400                        //         );
4401                        //     }
4402                        // }
4403                        let border_style = extract_border_style(styled);
4404                        let border_color = if !border_style.is_none() {
4405                            extract_border_color(styled, 0)
4406                        } else {
4407                            None
4408                        };
4409
4410                        let border_top_style = styled
4411                            .value("border-top-style")
4412                            .or_else(|| styled.value("border-style"))
4413                            .map(|s| super::BorderStyle::parse(&s))
4414                            .unwrap_or_default();
4415                        let border_right_style = styled
4416                            .value("border-right-style")
4417                            .or_else(|| styled.value("border-style"))
4418                            .map(|s| super::BorderStyle::parse(&s))
4419                            .unwrap_or_default();
4420                        let border_bottom_style = styled
4421                            .value("border-bottom-style")
4422                            .or_else(|| styled.value("border-style"))
4423                            .map(|s| super::BorderStyle::parse(&s))
4424                            .unwrap_or_default();
4425                        let border_left_style = styled
4426                            .value("border-left-style")
4427                            .or_else(|| styled.value("border-style"))
4428                            .map(|s| super::BorderStyle::parse(&s))
4429                            .unwrap_or_default();
4430
4431                        let border_top_color = styled
4432                            .value("border-top-color")
4433                            .or_else(|| styled.value("border-color"))
4434                            .and_then(|v| parse_color(&v));
4435                        let border_right_color = styled
4436                            .value("border-right-color")
4437                            .or_else(|| styled.value("border-color"))
4438                            .and_then(|v| parse_color(&v));
4439                        let border_bottom_color = styled
4440                            .value("border-bottom-color")
4441                            .or_else(|| styled.value("border-color"))
4442                            .and_then(|v| parse_color(&v));
4443                        let border_left_color = styled
4444                            .value("border-left-color")
4445                            .or_else(|| styled.value("border-color"))
4446                            .and_then(|v| parse_color(&v));
4447
4448                        let bg_image = styled
4449                            .value("background-image")
4450                            .or_else(|| styled.value("background"))
4451                            .and_then(|v| extract_url_path(&v));
4452                        let bg_images = styled
4453                            .value("background-image")
4454                            .or_else(|| styled.value("background"))
4455                            .map(|v| extract_all_url_paths(&v))
4456                            .unwrap_or_default();
4457                        // `background`ショートハンドの`<position>/<size>`分解は
4458                        // カスケード時点(`css::expand_background_shorthand`)で完了済みの
4459                        // ため、ここでは`background-position`/`-size`/`-repeat`の
4460                        // longhandをそのまま読むだけでよい。
4461                        let bg_size_raw = styled.value("background-size");
4462                        let bg_size = parse_bg_size(bg_size_raw.as_deref());
4463                        let bg_repeat_raw = styled.value("background-repeat");
4464                        let (bg_repeat_x, bg_repeat_y) = parse_bg_repeat(bg_repeat_raw.as_deref());
4465                        let bg_position_raw = styled.value("background-position");
4466                        let (bg_pos_x, bg_pos_y) = parse_bg_position(bg_position_raw.as_deref());
4467                        // 複数レイヤー(`background-image: url(a), url(b)`)向けの、レイヤーごとの
4468                        // size/repeat/position。以前は全レイヤーが `bg_size`/`bg_repeat_*`/
4469                        // `bg_pos_*`(先頭値のみ)を共有しており、`background-position: left top,
4470                        // right bottom` のようなレイヤーごとの指定が無視されるバグがあった。
4471                        // CSS仕様どおり、値の個数がレイヤー数より少なければ先頭から繰り返す。
4472                        let bg_layers: alloc::vec::Vec<(
4473                            super::BgSizeMode,
4474                            super::BgRepeatMode,
4475                            super::BgRepeatMode,
4476                            f32,
4477                            f32,
4478                        )> = if bg_images.len() > 1 {
4479                            let sizes: alloc::vec::Vec<&str> = bg_size_raw
4480                                .as_deref()
4481                                .map(|v| v.split(',').collect())
4482                                .unwrap_or_default();
4483                            let repeats: alloc::vec::Vec<&str> = bg_repeat_raw
4484                                .as_deref()
4485                                .map(|v| v.split(',').collect())
4486                                .unwrap_or_default();
4487                            let positions: alloc::vec::Vec<&str> = bg_position_raw
4488                                .as_deref()
4489                                .map(|v| v.split(',').collect())
4490                                .unwrap_or_default();
4491                            (0..bg_images.len())
4492                                .map(|i| {
4493                                    let size = if sizes.is_empty() {
4494                                        bg_size
4495                                    } else {
4496                                        parse_bg_size(Some(sizes[i % sizes.len()].trim()))
4497                                    };
4498                                    let (rx, ry) = if repeats.is_empty() {
4499                                        (bg_repeat_x, bg_repeat_y)
4500                                    } else {
4501                                        parse_bg_repeat(Some(repeats[i % repeats.len()].trim()))
4502                                    };
4503                                    let (px, py) = if positions.is_empty() {
4504                                        (bg_pos_x, bg_pos_y)
4505                                    } else {
4506                                        parse_bg_position(Some(positions[i % positions.len()].trim()))
4507                                    };
4508                                    (size, rx, ry, px, py)
4509                                })
4510                                .collect()
4511                        } else {
4512                            alloc::vec::Vec::new()
4513                        };
4514                        let background_blend_mode = styled
4515                            .value("background-blend-mode")
4516                            .unwrap_or_default();
4517                        // `background-clip`/`background-origin`: border-box/padding-box/content-box。
4518                        // `background-clip: text` は文字マスク合成が必要で非対応のため border-box にフォールバック。
4519                        fn normalize_bg_box(v: Option<alloc::string::String>) -> alloc::string::String {
4520                            match v.as_deref().map(str::trim) {
4521                                Some("padding-box") => alloc::string::String::from("padding-box"),
4522                                Some("content-box") => alloc::string::String::from("content-box"),
4523                                _ => alloc::string::String::from("border-box"),
4524                            }
4525                        }
4526                        let bg_clip = normalize_bg_box(
4527                            styled.value("background-clip")
4528                                .or_else(|| styled.value("-webkit-background-clip")),
4529                        );
4530                        // `background-origin` の既定値は border-box ではなく padding-box(CSS 仕様)。
4531                        let bg_origin = match styled.value("background-origin").as_deref().map(str::trim)
4532                        {
4533                            Some("border-box") => alloc::string::String::from("border-box"),
4534                            Some("content-box") => alloc::string::String::from("content-box"),
4535                            _ => alloc::string::String::from("padding-box"),
4536                        };
4537                        // `background-attachment: fixed` はスクロールしてもパターンが
4538                        // ビューポートに固定されて見える効果。`local` はネストしたスクロール
4539                        // コンテナ内での挙動差異があるが、この処理系では `scroll` と同一視する。
4540                        let bg_attachment = match styled.value("background-attachment").as_deref().map(str::trim)
4541                        {
4542                            Some("fixed") => alloc::string::String::from("fixed"),
4543                            _ => alloc::string::String::from("scroll"),
4544                        };
4545                        // CSS `cursor`: `text` のみ実際のカーソル形状へ反映する(他は非対応で
4546                        // 既定の矢印にフォールバックするが、値自体は保持する)。
4547                        let cursor_style = styled
4548                            .value("cursor")
4549                            .map(|v| String::from(v.trim()))
4550                            .unwrap_or_default();
4551                        let (outline_color, outline_width, outline_style) =
4552                            match parse_outline(styled) {
4553                                Some((c, w, s)) => (Some(c), w, s),
4554                                None => (None, 0, String::from("solid")),
4555                            };
4556                        let outline_offset = styled
4557                            .value("outline-offset")
4558                            .map(|v| parse_px_val(v.trim()))
4559                            .unwrap_or(0);
4560
4561                        // Parse text-shadow: `<Xpx> <Ypx> [<Blur>px] [<color>]` のカンマ区切り
4562                        // 複数シャドウに対応(box-shadow と同じ理由・同じ方式で最上位カンマ分割)。
4563                        // `rem`が丸ごと未対応だった同型のバグ(box-shadowと同じ理由。
4564                        // 詳細は`parse_shadow_len_tok`のdocコメント参照)。同関数を再利用。
4565                        fn parse_one_text_shadow(seg: &str, font_px: f32) -> Option<(i32, i32, i32, u32)> {
4566                            let seg = seg.trim();
4567                            if seg.is_empty() {
4568                                return None;
4569                            }
4570                            let mut ox = 0i32;
4571                            let mut oy = 0i32;
4572                            let mut blur = 0i32;
4573                            let mut sh_color = 0x80808080u32;
4574                            let mut px_count = 0;
4575                            for token in seg.split_whitespace() {
4576                                if let Some(n) = parse_shadow_len_tok_with_font(token, font_px) {
4577                                    match px_count {
4578                                        0 => ox = n,
4579                                        1 => oy = n,
4580                                        2 => blur = n,
4581                                        _ => {}
4582                                    }
4583                                    px_count += 1;
4584                                    continue;
4585                                }
4586                                if let Some(c) = parse_color(token) {
4587                                    sh_color = c;
4588                                }
4589                            }
4590                            if px_count == 0 {
4591                                None
4592                            } else {
4593                                Some((ox, oy, blur, sh_color))
4594                            }
4595                        }
4596                        let text_shadow: alloc::vec::Vec<(i32, i32, i32, u32)> = styled
4597                            .value("text-shadow")
4598                            .map_or_else(alloc::vec::Vec::new, |v| {
4599                                let v = v.trim().to_lowercase();
4600                                if v == "none" {
4601                                    alloc::vec::Vec::new()
4602                                } else {
4603                                    v.split(',')
4604                                        .filter_map(|s| parse_one_text_shadow(s, next_font_size as f32))
4605                                        .collect()
4606                                }
4607                            });
4608
4609                        // ::before / ::after content。`display:none` が指定されていれば
4610                        // 仕様通りボックス自体を生成しない(`content:none` と同じ扱い)。
4611                        let before_content = if styled.value("x-before-display").as_deref() == Some("none") {
4612                            String::new()
4613                        } else {
4614                            styled.value("x-before-content").unwrap_or_default()
4615                        };
4616                        let after_content = if styled.value("x-after-display").as_deref() == Some("none") {
4617                            String::new()
4618                        } else {
4619                            styled.value("x-after-content").unwrap_or_default()
4620                        };
4621                        // FontAwesome等のアイコンフォントは、アイコン専用クラス(`.fas`/`.far`/
4622                        // `.fab`等)で要素自身に`font-family`を指定し、実際のグリフは同じ要素の
4623                        // `::before{content:"\fXXX"}`から出す、という実装が一般的(`::before`は
4624                        // 既定で親要素からfont-familyを継承するため、要素自身の指定で足りる)。
4625                        // `x-before-font-family`(`::before`セレクタへの直接指定、稀)があれば
4626                        // それを優先し、無ければ要素自身の`font-family`にフォールバックする。
4627                        // 要素自身の font-family。カンマ区切りのまま渡し、
4628                        // 描画側が先頭から順に登録済みフォントを探す。
4629                        let font_family = styled
4630                            .value("font-family")
4631                            .map(|v| String::from(v.trim()))
4632                            .unwrap_or_default();
4633                        let before_font_family = styled
4634                            .value("x-before-font-family")
4635                            .or_else(|| styled.value("font-family"))
4636                            .and_then(|v| v.split(',').next().map(|s| String::from(s.trim().trim_matches('"').trim_matches('\''))))
4637                            .unwrap_or_default();
4638
4639                        // empty-cells: hide — 空セル(子孫がテキストのみ、かつ空白のみ)の
4640                        // 背景/境界線を非表示にする。`border-collapse:collapse` では常に
4641                        // 境界線が表示される仕様だが、この簡略実装ではその区別は行わない
4642                        // (collapse 時の empty-cells 適用除外は非対応、実用上の影響は軽微)。
4643                        let is_empty_cell_hidden = (tag_name == "td" || tag_name == "th")
4644                            && styled
4645                                .value("empty-cells")
4646                                .map(|v| v.trim().eq_ignore_ascii_case("hide"))
4647                                .unwrap_or(false)
4648                            && styled.node.children.iter().all(|c| match &c.node_type {
4649                                crate::os_lib::dom::NodeType::Text(t) => t.trim().is_empty(),
4650                                _ => false,
4651                            });
4652
4653                        // CSS transform: translate / scale(X/Y) / rotate / skew パース(要素サイズ・em・角度単位対応)
4654                        let (
4655                            transform_tx,
4656                            transform_ty,
4657                            transform_scale_x,
4658                            transform_scale_y,
4659                            transform_rotate_deg,
4660                            transform_skew_x,
4661                            transform_skew_y,
4662                        ) = parse_transform_with_size(
4663                            styled.value("transform").as_deref(),
4664                            layout.dimensions.content.width as f32,
4665                            layout.dimensions.content.height as f32,
4666                            next_font_size as f32,
4667                        );
4668                        let (transform_origin_x, transform_origin_y) =
4669                            parse_transform_origin(styled.value("transform-origin").as_deref());
4670                        // レイアウトが既に箱をずらした分は描画で足さない(二重適用の防止)。
4671                        let (layout_tx, layout_ty) = crate::os_lib::layout::box_translate(layout);
4672                        let transform_tx = transform_tx - layout_tx;
4673                        let transform_ty = transform_ty - layout_ty;
4674
4675                        let is_modal_dialog = matches!(&styled.node.node_type, crate::os_lib::dom::NodeType::Element { tag_name, attributes, .. }
4676                            if (tag_name == "dialog" && attributes.contains_key("_modal")) || attributes.contains_key("_popover_open"));
4677                        let backdrop_color = if is_modal_dialog {
4678                            extract_color(styled, "x-backdrop-background", "x-backdrop-background-color")
4679                                .or(Some(0x52000000))
4680                        } else {
4681                            None
4682                        };
4683
4684                        if (bg_color.is_some()
4685                            || is_modal_dialog
4686                            || (border_color.is_some() && !border_style.is_none())
4687                            || tag_name == "blockquote"
4688                            || bg_image.is_some()
4689                            || linear_gradient.is_some()
4690                            || radial_gradient.is_some()
4691                            || conic_gradient.is_some()
4692                            || repeating_linear_gradient.is_some()
4693                            || repeating_radial_gradient.is_some()
4694                            || !box_shadow.is_empty()
4695                            // 【2026-09-26 バグ修正】`::before`/`::after` の内容を持つ要素も
4696                            // 描画要素にする。従来は背景・枠線が無いと箱を作らず、内容ごと
4697                            // 捨てていた。Font Awesome の `<i class="fas fa-...">` は背景を
4698                            // 持たないので、www.sugi-lab.net のアイコンが全部消えていた。
4699                            // 本文の文字を持つ要素は対象外(疑似要素の幅がレイアウトに
4700                            // 入っていないので、本文と重なって描かれるため)。
4701                            || ((!before_content.is_empty() || !after_content.is_empty())
4702                                && styled.node.children.iter().all(|c| match &c.node_type {
4703                                    crate::os_lib::dom::NodeType::Text(t) => t.trim().is_empty(),
4704                                    _ => true,
4705                                })))
4706                            && container_w > 0
4707                            && container_h > 0
4708                            && tag_name != "head"
4709                            && tag_name != "title"
4710                            && tag_name != "meta"
4711                            && tag_name != "link"
4712                            && tag_name != "style"
4713                            && tag_name != "script"
4714                            && !is_empty_cell_hidden
4715                        {
4716                            // 疑似要素の内容を描くときは要素の文字サイズ・色が要る
4717                            // (無ければ従来どおり 0 = 文字は描かない箱)。
4718                            let has_pseudo = !before_content.is_empty() || !after_content.is_empty();
4719                            let pseudo_color = if has_pseudo {
4720                                let (default_text_color, default_link_color) = self.default_text_colors();
4721                                if current_href.is_empty() {
4722                                    next_color.unwrap_or(default_text_color)
4723                                } else {
4724                                    next_color.unwrap_or(default_link_color)
4725                                }
4726                            } else {
4727                                0
4728                            };
4729                            self.elements.push(RenderElement {
4730                                text: String::new(),
4731                                font_size: if has_pseudo { next_font_size } else { 0 },
4732                                color: pseudo_color,
4733                                bg_color,
4734                                hover_bg_color: extract_hover_color_alt(
4735                                    styled,
4736                                    "background-color",
4737                                    "background",
4738                                ),
4739                                hover_color: None,
4740                                hover_border_color: extract_hover_color(styled, "border-color"),
4741                                filter: styled.value("filter").unwrap_or_default(),
4742                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
4743                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
4744                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
4745                                text_stroke_width: extract_text_stroke(styled).0,
4746                                text_stroke_color: extract_text_stroke(styled).1,
4747                                marker_color: extract_marker_color(styled),
4748                                marker_font_size: extract_marker_font_size(styled),
4749                                marker_content: extract_marker_content(styled),
4750                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
4751                                focus_color: None,
4752                                focus_border_color: extract_focus_color(styled, "border-color"),
4753                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
4754                                active_color: None,
4755                                active_border_color: extract_active_color(styled, "border-color"),
4756                                border_color,
4757                                border_style,
4758                                // 【2026-08-05 発見・修正】`false` の決め打ちだった。
4759                                //
4760                                // この要素の `::before` / `::after` の内容は
4761                                // **この要素自身**の書体で描かれる。にもかかわらず
4762                                // 太字・斜体を常に無効にしていたため、
4763                                // `.fas { font-weight: 900 }` のアイコンが
4764                                // regular(400) の書体で引かれ、字形が無くて
4765                                // 箱(☐)になっていた。
4766                                //
4767                                // 実測: `[FONTPICK] font awesome 7 free|bold=false|
4768                                // hit=Some("font awesome 7 free|400")`
4769                                font_bold: styled
4770                                    .value("font-weight")
4771                                    .map(|v| {
4772                                        let t = v.trim().to_lowercase();
4773                                        t == "bold"
4774                                            || t == "bolder"
4775                                            || t.parse::<u32>().unwrap_or(400) >= 700
4776                                    })
4777                                    .unwrap_or(false),
4778                                font_italic: styled
4779                                    .value("font-style")
4780                                    .map(|v| {
4781                                        let t = v.trim().to_lowercase();
4782                                        t == "italic" || t == "oblique"
4783                                    })
4784                                    .unwrap_or(false),
4785                                underline: false,
4786                                line_through: false,
4787                                is_video: false,
4788                                video_src: String::new(),
4789                                is_link: false,
4790                                href: String::new(),
4791                                is_hr: false,
4792                                is_img: false,
4793                                canvas_ctx_id,
4794                                img_alt: String::new(),
4795                                is_input: false,
4796                                is_textarea: false,
4797                                is_button: false,
4798                                button_icon: 0,
4799                                element_id: el_id.clone(),
4800                                node_idx: styled.node.node_idx,
4801                                scroll_margin_top: styled.value("scroll-margin-top").map(|v| parse_px_val(&v)).unwrap_or(0),
4802                                onclick: onclick.clone(),
4803                                form_action: String::new(),
4804                                form_method: String::new(),
4805                                width: container_w,
4806                                x_offset: container_x,
4807                                y_offset: container_y,
4808                                height: container_h,
4809                                border_radius,
4810                                is_li: tag_name == "li",
4811                                li_num: None,
4812                                is_blockquote: tag_name == "blockquote",
4813                                border_top_width: layout.dimensions.border.top,
4814                                border_right_width: layout.dimensions.border.right,
4815                                border_bottom_width: layout.dimensions.border.bottom,
4816                                border_left_width: layout.dimensions.border.left,
4817                                padding_top: layout.dimensions.padding.top,
4818                                padding_right: layout.dimensions.padding.right,
4819                                padding_bottom: layout.dimensions.padding.bottom,
4820                                padding_left: layout.dimensions.padding.left,
4821                                bg_clip,
4822                                bg_origin,
4823                                bg_attachment,
4824                                cursor_style,
4825                                border_top_color,
4826                                border_right_color,
4827                                border_bottom_color,
4828                                border_left_color,
4829                                border_top_style,
4830                                border_right_style,
4831                                border_bottom_style,
4832                                border_left_style,
4833                                bg_image,
4834                                bg_images,
4835                                bg_size,
4836                                bg_repeat_x,
4837                                bg_repeat_y,
4838                                bg_pos_x,
4839                                bg_pos_y,
4840                                background_blend_mode,
4841                                bg_layers,
4842                                outline_color,
4843                                outline_width,
4844                                outline_offset,
4845                                outline_style,
4846                                pos_top,
4847                                pos_left,
4848                                pos_right,
4849                                pos_bottom,
4850                                z_index: z_index_val,
4851                                paint_depth: self.inherited_paint_depth,
4852                                is_fixed: is_fixed_pos,
4853                                is_sticky: is_sticky_pos,
4854                                is_positioned: is_positioned_effective,
4855                                sticky_top: if is_sticky_pos { pos_top } else { None },
4856                                sticky_bottom: if is_sticky_pos { pos_bottom } else { None },
4857                                box_shadow,
4858                                linear_gradient,
4859                                radial_gradient,
4860                                conic_gradient,
4861                                repeating_linear_gradient,
4862                                repeating_radial_gradient,
4863                                opacity: opacity_val,
4864                                visibility_hidden,
4865                                text_shadow,
4866                                before_content,
4867                                after_content,
4868                                font_family,
4869                                before_font_family,
4870                                transform_tx,
4871                                transform_ty,
4872                                layout_tx,
4873                                layout_ty,
4874                                transform_scale_x,
4875                                transform_scale_y,
4876                                transform_rotate_deg,
4877                                transform_skew_x,
4878                                transform_skew_y,
4879                                transform_origin_x,
4880                                transform_origin_y,
4881                                // `mask-image` はフルサポート(url()による画像マスク等)は非対応だが、
4882                                // `circle()`/`ellipse()`/`polygon()` 等の図形関数構文は `clip-path` と
4883                                // 全く同じ `parse_clip_shape` を再利用してマスキングできる。`clip-path`
4884                                // が無指定のときのみ `mask-image` にフォールバックする(`clip-path` が
4885                                // 優先、両方指定されるケースは稀なため簡略化)。`mask-image:url(...)`
4886                                // のような非対応構文は `parse_clip_shape` がどのプレフィックスにも
4887                                // 一致せず `None` を返すため、単に無視されるだけで安全。
4888                                clip_path: styled
4889                                    .value("clip-path")
4890                                    .or_else(|| styled.value("mask-image"))
4891                                    .unwrap_or_default(),
4892                                is_modal: is_modal_dialog,
4893                                backdrop_color,
4894                                ..Default::default()
4895                            });
4896                        }
4897
4898                        // CSS Multi-column: 段罫線(column-rule)の生成
4899                        // column-count または columns/column-width が指定されている多段組コンテナで、
4900                        // 2 列以上生成され column-rule が指定されている場合、各列間に境界線を描画。
4901                        {
4902                            let cc = styled.value("column-count");
4903                            let cw = styled.value("column-width");
4904                            let shorthand = styled.value("columns");
4905                            let (sh_w, sh_c) = shorthand
4906                                .as_deref()
4907                                .map(crate::os_lib::layout::multicol::parse_columns_shorthand)
4908                                .unwrap_or((None, None));
4909                            let parse_px = |v: &Option<String>| -> Option<i32> {
4910                                v.as_deref()
4911                                    .and_then(|s| s.trim().strip_suffix("px"))
4912                                    .and_then(|n| n.trim().parse::<f32>().ok())
4913                                    .filter(|f| f.is_finite() && *f > 0.0)
4914                                    .map(|f| f as i32)
4915                            };
4916                            let count = cc
4917                                .as_deref()
4918                                .and_then(|s| s.trim().parse::<i32>().ok())
4919                                .filter(|v| *v > 0)
4920                                .or(sh_c);
4921                            let width = parse_px(&cw).or(sh_w);
4922                            if count.is_some() || width.is_some() {
4923                                let content_w = layout.dimensions.content.width.max(0);
4924                                let content_h = layout.dimensions.content.height.max(0);
4925                                if content_w > 0 && content_h > 0 {
4926                                    let gap_str = styled.value("column-gap").or_else(|| styled.value("gap"));
4927                                    let gap = crate::os_lib::layout::multicol::resolve_column_gap(
4928                                        gap_str.as_deref(),
4929                                        content_w,
4930                                        next_font_size as f32,
4931                                    );
4932                                    let spec = crate::os_lib::layout::multicol::MultiColSpec { count, width, gap };
4933                                    let cols = crate::os_lib::layout::multicol::layout_columns(&spec, content_w);
4934                                    if cols.len() > 1 {
4935                                        let rule_sh = styled.value("column-rule");
4936                                        let rule_w = styled.value("column-rule-width");
4937                                        let rule_s = styled.value("column-rule-style");
4938                                        let rule_c = styled.value("column-rule-color");
4939                                        if let Some(rule) = crate::os_lib::layout::multicol::parse_column_rule(
4940                                            rule_sh.as_deref(),
4941                                            rule_w.as_deref(),
4942                                            rule_s.as_deref(),
4943                                            rule_c.as_deref(),
4944                                            next_font_size as f32,
4945                                        ) {
4946                                            let rules = crate::os_lib::layout::multicol::compute_column_rules(
4947                                                &cols,
4948                                                gap,
4949                                                layout.dimensions.content.y,
4950                                                content_h,
4951                                                &rule,
4952                                            );
4953                                            let base_x = layout.dimensions.content.x;
4954                                            let border_style = match rule.style {
4955                                                crate::os_lib::layout::multicol::RuleStyle::Dashed => super::BorderStyle::Dashed,
4956                                                crate::os_lib::layout::multicol::RuleStyle::Dotted => super::BorderStyle::Dotted,
4957                                                crate::os_lib::layout::multicol::RuleStyle::Double => super::BorderStyle::Double,
4958                                                _ => super::BorderStyle::Solid,
4959                                            };
4960                                            for r in rules {
4961                                                self.elements.push(RenderElement {
4962                                                    x_offset: base_x + r.x,
4963                                                    y_offset: r.y,
4964                                                    width: r.width,
4965                                                    height: r.height,
4966                                                    border_left_width: r.width,
4967                                                    border_left_style: border_style,
4968                                                    border_left_color: Some(r.color),
4969                                                    bg_color: if border_style == super::BorderStyle::Solid {
4970                                                        Some(r.color)
4971                                                    } else {
4972                                                        None
4973                                                    },
4974                                                    opacity: opacity_val,
4975                                                    z_index: z_index_val,
4976                                                    is_positioned: is_positioned_effective,
4977                                                    ..Default::default()
4978                                                });
4979                                            }
4980                                        }
4981                                    }
4982                                }
4983                            }
4984                        }
4985
4986                        // 子要素をフラット化
4987                        // select は option 子要素を独自に収集済みなので通常フラット化をスキップ。
4988                        // button は子要素に要素ノード(<i> や <span> 等)を含む場合はアイコンや装飾を描画するため走査する。
4989                        let has_child_elements = styled
4990                            .node
4991                            .children
4992                            .iter()
4993                            .any(|c| matches!(&c.node_type, crate::os_lib::dom::NodeType::Element { .. }));
4994                        let skip_children = (is_button && !has_child_elements)
4995                            || is_input
4996                            || is_textarea
4997                            || is_select
4998                            || inline_svg_src.is_some();
4999                        if !skip_children {
5000                            let is_ul = tag_name == "ul";
5001                            let is_ol = tag_name == "ol";
5002                            let mut child_list_state = if is_ul {
5003                                Some((false, 0))
5004                            } else if is_ol {
5005                                Some((true, 0))
5006                            } else {
5007                                list_state
5008                            };
5009
5010                            // overflow クリップ: 子孫の生成インデックス範囲に、この要素の
5011                            // パディングボックスを clip 矩形として後付けする(入れ子は交差)。
5012                            // 【2026-10-03】従来は content box で切っており、縦横比の手法
5013                            // (`padding-bottom:56.25%; height:0; overflow:hidden`)の箱で中身
5014                            // (sugi-lab.net/smarthome.htm の埋め込み iframe)がすべて消えていた。
5015                            // 仕様(CSS Overflow 3)ではクリップの縁はパディングの縁。
5016                            let clip_rect_for_children: Option<(i32, i32, i32, i32)> =
5017                                if overflow_clips {
5018                                    let c = layout.dimensions.padding_box();
5019                                    Some((c.x, c.y, c.x + c.width, c.y + c.height))
5020                                } else {
5021                                    None
5022                                };
5023                            let clip_start_idx = self.elements.len();
5024
5025                            // <label> の関連付け先 id を算出(for 属性優先、無ければ内包 input)。
5026                            // この label のサブツリーで生成された要素に後付けし、テキストクリックで
5027                            // 該当 input をトグル/フォーカスできるようにする。
5028                            let label_target: Option<String> = if tag_name == "label" {
5029                                attributes
5030                                    .get("for")
5031                                    .cloned()
5032                                    .filter(|s| !s.is_empty())
5033                                    .or_else(|| find_labelable_descendant_id(layout))
5034                            } else {
5035                                None
5036                            };
5037
5038                            // 【2026-10-03】位置指定(absolute)された ::before/::after を、背景・枠線・
5039                            // 不透明度を持つ箱として子の先頭・末尾に加える(`layout::pseudo_box`)。
5040                            // 包含ブロックは要素自身(位置指定されているときだけ扱う)のパディングボックス。
5041                            // 置換要素・フォーム部品の疑似要素は描かない(Chrome も生成しない)。
5042                            let pseudo_parent_ok = !matches!(
5043                                tag_name.as_str(),
5044                                "img" | "iframe" | "input" | "textarea" | "select" | "video" | "canvas"
5045                                    | "progress" | "meter" | "svg"
5046                            ) && establishes_abs_cb;
5047                            let make_pseudo = |which: &str| -> Option<crate::os_lib::css::StyledNode> {
5048                                if !pseudo_parent_ok {
5049                                    return None;
5050                                }
5051                                let vals = crate::os_lib::layout::pseudo_box::pseudo_values(
5052                                    &styled.specified_values,
5053                                    which,
5054                                )?;
5055                                if vals.get("position").map(|p| p.trim()) != Some("absolute") {
5056                                    return None;
5057                                }
5058                                Some(crate::os_lib::css::StyledNode {
5059                                    node: styled.node,
5060                                    specified_values: alloc::rc::Rc::new(vals),
5061                                    hover_values: None,
5062                                    focus_values: None,
5063                                    active_values: None,
5064                                    css_vars: styled.css_vars.clone(),
5065                                    children: alloc::vec::Vec::new(),
5066                                    edges_cache: Default::default(),
5067                                    intrinsic_size_cache: Default::default(),
5068                                    block_intrinsic_cache: Default::default(),
5069                                    layout_subtree_cache: Default::default(),
5070                                })
5071                            };
5072                            let before_styled = make_pseudo("before");
5073                            let after_styled = make_pseudo("after");
5074                            let pseudo_cb = layout.dimensions.padding_box();
5075                            let before_box = before_styled.as_ref().map(|ps| make_pseudo_box(ps, &pseudo_cb));
5076                            let after_box = after_styled.as_ref().map(|ps| make_pseudo_box(ps, &pseudo_cb));
5077
5078                            // 子孫はこの要素のスタッキングコンテキストの中(段の列に自分の段を足す)。
5079                            if creates_stacking_ctx {
5080                                self.stack_prefix.push(super::paint_order::stack_step(
5081                                    z_index_val,
5082                                    is_positioned_effective,
5083                                    self.inherited_paint_depth,
5084                                    my_seq,
5085                                ));
5086                            }
5087                            for child in before_box.iter().chain(layout.children.iter()).chain(after_box.iter()) {
5088                                // 疑似要素の箱(要素自身の DOM ノードを指す)はリスト番号を進めない。
5089                                let is_pseudo_box = matches!(
5090                                    &child.box_type,
5091                                    crate::os_lib::layout::BoxType::BlockNode(s) if core::ptr::eq(s.node, styled.node)
5092                                );
5093                                let is_child_li = !is_pseudo_box && match &child.box_type {
5094                                    crate::os_lib::layout::BoxType::BlockNode(styled_child)
5095                                    | crate::os_lib::layout::BoxType::InlineNode(styled_child)
5096                                    | crate::os_lib::layout::BoxType::InlineBlockNode(
5097                                        styled_child,
5098                                    ) => match &styled_child.node.node_type {
5099                                        crate::os_lib::dom::NodeType::Element {
5100                                            tag_name: child_tag,
5101                                            ..
5102                                        } => child_tag == "li",
5103                                        _ => false,
5104                                    },
5105                                    _ => false,
5106                                };
5107
5108                                if is_child_li {
5109                                    if let Some((is_ol, count)) = child_list_state {
5110                                        child_list_state = Some((is_ol, count + 1));
5111                                    }
5112                                }
5113
5114                                // 子孫は自分の実効 z を祖先値として引き継ぐ。
5115                                let saved_paint_z = self.inherited_paint_z;
5116                                let saved_paint_depth = self.inherited_paint_depth;
5117                                let saved_positioned = self.inherited_positioned;
5118                                self.inherited_paint_z = z_index_val;
5119                                self.inherited_paint_depth =
5120                                    self.inherited_paint_depth.saturating_add(1);
5121                                self.inherited_positioned = is_positioned_effective;
5122                                let saved_pos_count = self.inherited_pos_count;
5123                                self.inherited_pos_count = saved_pos_count + establishes_abs_cb as u32;
5124                                let child_start_idx = self.elements.len();
5125                                let abs_marks_start = self.abs_marks.len();
5126                                // FLATTEN_MEMO: 不変部分木の RenderElement 再利用(TODO P5c)
5127                                let flatten_key = flatten_subtree_info(child).and_then(|(h0, h1, can_memo)| {
5128                                    if can_memo {
5129                                        let ih = hash_flatten_inherited(
5130                                            &next_form_action, &next_form_method, &next_href,
5131                                            next_font_bold, next_font_italic, next_underline, next_line_through,
5132                                            next_color, next_font_size, &next_parent_id,
5133                                            child_list_state, tag_name,
5134                                            next_decoration_color, &next_decoration_style,
5135                                            next_decoration_thickness, next_decoration_underline_offset,
5136                                            next_overline, next_pointer_events_none,
5137                                            z_index_val, self.inherited_paint_depth,
5138                                            is_positioned_effective, self.inherited_pos_count,
5139                                            &self.stack_prefix,
5140                                        );
5141                                        Some(FlattenMemoKey {
5142                                            subtree_hash: (h0, h1),
5143                                            inherited_hash: ih,
5144                                            x: child.dimensions.content.x,
5145                                            y: child.dimensions.content.y,
5146                                            env_hash: flatten_env_hash(),
5147                                        })
5148                                    } else {
5149                                        None
5150                                    }
5151                                });
5152                                // 【2026-11-18】この部分木より前に、子孫の項目(当たり・登録)から来た要素の数。
5153                                // 部分木を表に入れるかを決めるのに使う(祖先ごとに同じ要素の写しを持たない)。
5154                                let covered_start = self.flatten_memo_covered;
5155                                let flatten_hit = if let Some(ref key) = flatten_key {
5156                                    let mut g = GLOBAL_FLATTEN_MEMO.lock();
5157                                    purge_closed_groups(&mut g);
5158                                    let g = &mut *g;
5159                                    if let Some(entry) = g.map.get(key) {
5160                                        self.elements.extend_from_slice(&entry.elements);
5161                                        for &(s, e, k) in &entry.abs_marks {
5162                                            self.abs_marks.push((s + child_start_idx, e + child_start_idx, k));
5163                                        }
5164                                        self.flatten_memo_covered = covered_start + entry.elements.len();
5165                                        g.hits += 1;
5166                                        true
5167                                    } else {
5168                                        g.misses += 1;
5169                                        false
5170                                    }
5171                                } else {
5172                                    false
5173                                };
5174                                if !flatten_hit {
5175                                    self.flatten_layout(
5176                                        child,
5177                                        &next_form_action,
5178                                        &next_form_method,
5179                                        &next_href,
5180                                        next_font_bold,
5181                                        next_font_italic,
5182                                        next_underline,
5183                                        next_line_through,
5184                                        next_color,
5185                                        next_font_size,
5186                                        &next_parent_id,
5187                                        child_list_state,
5188                                        tag_name,
5189                                        next_decoration_color,
5190                                        next_decoration_style.clone(),
5191                                        next_decoration_thickness,
5192                                        next_decoration_underline_offset,
5193                                        next_overline,
5194                                        next_pointer_events_none,
5195                                    );
5196                                    if let Some(key) = flatten_key {
5197                                        let end_idx = self.elements.len();
5198                                        let count = end_idx.saturating_sub(child_start_idx);
5199                                        // 【2026-11-18】入れるのは、要素の半分以上が子孫の項目に無い部分木か、小さな(1MB 以下)部分木だけ
5200                                        // (大きな祖先ごとに同じ要素の写しを持たない)。量(見積もり)が 1 項目の上限を超える部分木も入れない。
5201                                        // 表全体の量は上限まで、古い順に捨てる(`flatten_memo_budget.rs`)。
5202                                        let covered = self.flatten_memo_covered.saturating_sub(covered_start);
5203                                        let limits = super::flatten_memo_budget::Limits::FLATTEN_MEMO;
5204                                        // 【2026-11-18 TODO R5 (e) ④】要素の数だけで 1 項目の上限を超える部分木は、量を数えずに外す
5205                                        // (量の見積もりは要素を全部読むので、入らない大きな部分木の祖先ごとに数えると深さ × 要素の数になった)。
5206                                        let fits = count.saturating_mul(core::mem::size_of::<RenderElement>()) <= limits.max_entry_bytes;
5207                                        if count > 0 && count <= FlattenMemo::MAX_ELEMENTS && fits {
5208                                            let abs_marks: Vec<(usize, usize, u32)> = self.abs_marks[abs_marks_start..]
5209                                                .iter()
5210                                                .filter(|&&(s, _, _)| s >= child_start_idx && s < end_idx)
5211                                                .map(|&(s, e, k)| (s - child_start_idx, e - child_start_idx, k))
5212                                                .collect();
5213                                            let bytes = core::mem::size_of::<FlattenMemoEntry>()
5214                                                + abs_marks.len() * core::mem::size_of::<(usize, usize, u32)>()
5215                                                + self.elements[child_start_idx..end_idx].iter().map(render_element_bytes).sum::<usize>();
5216                                            // 止める合図の後の部分木は途中までなので、表(ほかのタブも引く)に入れない(2026-11-18)。
5217                                            if limits.admits(bytes)
5218                                                && super::flatten_memo_budget::worth_storing(count, covered, bytes)
5219                                                && !crate::kernel::window_mgr::layout_aborting()
5220                                            {
5221                                                let elements = self.elements[child_start_idx..end_idx].to_vec();
5222                                                let mut g = GLOBAL_FLATTEN_MEMO.lock();
5223                                                purge_closed_groups(&mut g);
5224                                                let outcome = g.map.insert(
5225                                                    key,
5226                                                    FlattenMemoEntry { elements, abs_marks },
5227                                                    bytes,
5228                                                    crate::kernel::window_mgr::current_group(),
5229                                                );
5230                                                if matches!(outcome, super::flatten_memo_budget::InsertOutcome::Stored { .. }) {
5231                                                    // 祖先から見ると、この部分木の要素は全部この項目にある。
5232                                                    self.flatten_memo_covered = covered_start + count;
5233                                                }
5234                                            }
5235                                        }
5236                                    }
5237                                }
5238                                self.inherited_paint_z = saved_paint_z;
5239                                self.inherited_paint_depth = saved_paint_depth;
5240                                self.inherited_positioned = saved_positioned;
5241                                // `visibility` は継承するので、子の部分木で生まれた要素のうち未決定のもの
5242                                // (文字・画像・ボタン等。背景の箱以外は従来 visible 固定だった)は子の値。
5243                                // 【2026-10-18】YouTube の隠れた再生ボタン(`visibility:hidden` の祖先)が
5244                                // 動画のクリックを奪っていた。
5245                                // `pointer-events` も継承する。子の箱自身の要素(背景の箱・ボタン等)は従来
5246                                // 既定の false のままで、`pointer-events:none` の祖先の中のボタンがクリックを
5247                                // 奪っていた(YouTube の `.intercept-element-clicks .player-controls-middle`)。
5248                                if let Some(hidden) = box_visibility_hidden(child) {
5249                                    // 【2026-11-18 TODO R5 (e) ④】下と同じく、子孫の段で決まった区間は飛ばす(要素の箱ではいつも Some)。
5250                                    let end_idx = self.elements.len();
5251                                    let mut gaps = core::mem::take(&mut self.flatten_gaps);
5252                                    self.flatten_visibility_decided.take_gaps(child_start_idx, end_idx, &mut gaps);
5253                                    for &(gs, ge) in gaps.iter() {
5254                                        for el in self.elements.get_mut(gs..ge).into_iter().flatten() {
5255                                            if !el.visibility_decided {
5256                                                el.visibility_hidden = hidden;
5257                                                el.visibility_decided = true;
5258                                            }
5259                                        }
5260                                    }
5261                                    self.flatten_gaps = gaps;
5262                                }
5263                                // `pointer-events` と、子の箱自身の要素(子孫は内側のループで決定済み)に今の段の列と文書順。
5264                                // 【2026-11-18 TODO R5 (e) ④】子孫の段で決まった要素の区間(`flatten_decided`)は飛ばし、
5265                                // すき間だけを見る(以前は祖先ごとに子孫の要素を全部見直し、512 段の入れ子では深さ × 要素の数になった)。
5266                                {
5267                                    let pe = box_pointer_events_none(child).unwrap_or(next_pointer_events_none);
5268                                    let end_idx = self.elements.len();
5269                                    let mut gaps = core::mem::take(&mut self.flatten_gaps);
5270                                    self.flatten_decided.take_gaps(child_start_idx, end_idx, &mut gaps);
5271                                    for &(gs, ge) in gaps.iter() {
5272                                        for el in self.elements.get_mut(gs..ge).into_iter().flatten() {
5273                                            if !el.pointer_events_decided {
5274                                                el.pointer_events_none = pe;
5275                                                el.pointer_events_decided = true;
5276                                            }
5277                                            if !el.stack_decided {
5278                                                el.stack_path = self.stack_prefix.clone();
5279                                                el.paint_seq = child_start_idx as u32;
5280                                                el.stack_decided = true;
5281                                            }
5282                                        }
5283                                    }
5284                                    self.flatten_gaps = gaps;
5285                                }
5286                                if box_is_absolute(child) {
5287                                    self.abs_marks.push((child_start_idx, self.elements.len(), self.inherited_pos_count));
5288                                }
5289                                self.inherited_pos_count = saved_pos_count;
5290                            }
5291                            if creates_stacking_ctx {
5292                                self.stack_prefix.pop();
5293                            }
5294
5295                            // 【2026-09-26 バグ修正】`position:fixed` の子孫も画面に固定する。
5296                            // 従来は固定要素自身にしか `is_fixed` を立てず、子孫(文字・画像)は
5297                            // ページと一緒にスクロールしていた。www.sugi-lab.net の固定ヘッダで、
5298                            // スクロールすると背景だけ残りロゴとナビの文字が消えていた
5299                            // (QEMU の実画面撮影で発見)。
5300                            if is_fixed_pos {
5301                                for el in &mut self.elements[clip_start_idx..] {
5302                                    el.is_fixed = true;
5303                                }
5304                            } else if establishes_fixed_cb {
5305                                // `transform` 等の包含ブロックの中にある `position:fixed` はビューポート固定ではなく
5306                                // この要素に追従する(スクロールおよび overflow 切り取りの対象になる)。
5307                                for el in &mut self.elements[clip_start_idx..] {
5308                                    el.is_fixed = false;
5309                                }
5310                            }
5311                            if is_positioned_effective || establishes_fixed_cb {
5312                                for el in &mut self.elements[clip_start_idx..] {
5313                                    el.is_positioned = true;
5314                                }
5315                            }
5316
5317                            // 生成された子孫要素にクリップ矩形を適用(既存 clip と交差)。
5318                            // 軸ごとに独立して適用する: `overflow-x`/`overflow-y` の一方だけが
5319                            // clip 対象の場合、クリップされない軸の境界は据え置く(両軸まとめて
5320                            // 適用すると、クリップ不要な軸まで誤ってクリップされてしまうため)。
5321                            if let Some((cx0, cy0, cx1, cy1)) = clip_rect_for_children {
5322                                // 【2026-10-03】角丸の箱は中身も角丸に切る(両軸を切るときだけ。
5323                                // 内側の箱が既に角丸で切っていればそちらを残す)。
5324                                let clip_r = if x_clips && y_clips {
5325                                    border_radius.0.max(border_radius.1).max(border_radius.2).max(border_radius.3)
5326                                } else {
5327                                    0
5328                                };
5329                                // 包含ブロックを作らない箱(static かつ transform 等なし)は、包含ブロックが
5330                                // この箱より外にある absolute の子孫を切らない(CSS 2.1 §11.1.1)。【2026-10-18】
5331                                // YouTube の `.html5-video-container`(高さ 0・overflow:hidden)が中の
5332                                // `<video>`(absolute、包含ブロックは外側の player)を全部切っていた。
5333                                let escaped: Vec<(usize, usize)> = if establishes_abs_cb {
5334                                    Vec::new()
5335                                } else {
5336                                    let own_count = self.inherited_pos_count;
5337                                    self.abs_marks
5338                                        .iter()
5339                                        .filter(|&&(s, _, k)| s >= clip_start_idx && k <= own_count)
5340                                        .map(|&(s, e, _)| (s, e))
5341                                        .collect()
5342                                };
5343                                for i in clip_start_idx..self.elements.len() {
5344                                    if escaped.iter().any(|&(s, e)| i >= s && i < e) {
5345                                        continue;
5346                                    }
5347                                    let el = &mut self.elements[i];
5348                                    // `position:fixed` の子孫は(この箱自身が fixed でなければ)祖先の
5349                                    // overflow で切らない(包含ブロックはビューポート)。【2026-10-17】
5350                                    // YouTube 埋め込みの操作部(fixed)が高さ 0 の祖先で全部切られていた。
5351                                    if el.is_fixed && !is_fixed_pos {
5352                                        continue;
5353                                    }
5354                                    if clip_r > 0 && el.clip_radius == 0 {
5355                                        el.clip_radius = clip_r;
5356                                    }
5357                                    el.overflow_hidden = true;
5358                                    if x_clips {
5359                                        el.clip_x0 = el.clip_x0.max(cx0);
5360                                        el.clip_x1 = el.clip_x1.min(cx1);
5361                                    }
5362                                    if y_clips {
5363                                        el.clip_y0 = el.clip_y0.max(cy0);
5364                                        el.clip_y1 = el.clip_y1.min(cy1);
5365                                    }
5366                                }
5367                            }
5368
5369                            // overflow:scroll/auto → サブスクロールコンテナとして子孫に ID を付与。
5370                            // 内側に入れ子のスクロールコンテナが存在する子孫は上書きしない
5371                            // (既に内側コンテナの ID が設定済みのため)。
5372                            if is_scroll_container {
5373                                // element_id が空の場合は自動生成(位置ベースの仮 ID)。
5374                                let cid = if el_id.is_empty() {
5375                                    let c = &layout.dimensions.content;
5376                                    alloc::format!("_sc_{}_{}", c.x, c.y)
5377                                } else {
5378                                    el_id.clone()
5379                                };
5380                                // コンテナ高さを超えるコンテンツ量を scroll_max_y として算出。
5381                                let c = &layout.dimensions.content;
5382                                let container_bottom = c.y + c.height;
5383                                let content_bottom = self.elements[clip_start_idx..]
5384                                    .iter()
5385                                    .map(|e| e.y_offset + e.height)
5386                                    .max()
5387                                    .unwrap_or(container_bottom);
5388                                let scroll_max = (content_bottom - container_bottom).max(0);
5389                                // コンテナ幅を超えるコンテンツ量を scroll_max_x として算出。
5390                                let container_right = c.x + c.width;
5391                                let content_right = self.elements[clip_start_idx..]
5392                                    .iter()
5393                                    .map(|e| e.x_offset + e.width)
5394                                    .max()
5395                                    .unwrap_or(container_right);
5396                                let scroll_max_x = (content_right - container_right).max(0);
5397                                // scroll_regions に初期エントリを作る(存在しなければ 0)。
5398                                self.scroll_regions.entry(cid.clone()).or_insert(0);
5399                                self.scroll_regions_x.entry(cid.clone()).or_insert(0);
5400                                // DOM 側の scroll_widths / scroll_heights に即座に反映。
5401                                // 条件式の borrow() を本体まで持ち越すと borrow_mut() と衝突して panic する
5402                                // (【2026-10-17】YouTube の埋め込みの操作部で発生)。先に取り出す。
5403                                let found = self.js_runtime.dom().borrow().get_element_by_id(&cid);
5404                                if let Some(idx) = found {
5405                                    let mut dom = self.js_runtime.dom().borrow_mut();
5406                                    dom.scroll_widths.insert(idx, c.width + scroll_max_x);
5407                                    dom.scroll_heights.insert(idx, c.height + scroll_max);
5408                                }
5409                                // スクロールバースタイル(W3C CSS Scrollbars Module Level 1)
5410                                let sc_sb_width = styled
5411                                    .value("scrollbar-width")
5412                                    .map(|v| ScrollbarWidth::resolve(&v))
5413                                    .unwrap_or(ScrollbarWidth::Auto);
5414                                let sc_sb_color = styled
5415                                    .value("scrollbar-color")
5416                                    .and_then(|v| parse_scrollbar_color(&v))
5417                                    .and_then(|mode| match mode {
5418                                        ScrollbarColorMode::Custom(c) => Some(c),
5419                                        ScrollbarColorMode::Auto => None,
5420                                    });
5421                                // スクロールバー描画・ホバー判定用のメタ情報を登録。
5422                                self.scroll_containers.push((
5423                                    cid.clone(),
5424                                    scroll_max,
5425                                    c.x,
5426                                    c.y,
5427                                    c.width,
5428                                    c.height,
5429                                    sc_sb_width,
5430                                    sc_sb_color,
5431                                ));
5432                                // 子孫に scroll_container_id を付与(内側コンテナ済みは除く)。
5433                                for i in clip_start_idx..self.elements.len() {
5434                                    let el = &mut self.elements[i];
5435                                    if el.scroll_container_id.is_empty() {
5436                                        el.scroll_container_id = cid.clone();
5437                                    }
5438                                }
5439                            }
5440
5441                            // <label> サブツリーで生成された要素に関連付け先を付与
5442                            // (内包 input 自体は除外: 自前のトグル動作を持つため)。
5443                            if let Some(target) = label_target {
5444                                for i in clip_start_idx..self.elements.len() {
5445                                    let el = &mut self.elements[i];
5446                                    if el.label_for.is_empty()
5447                                        && el.input_kind == 0
5448                                        && !el.is_input
5449                                        && !el.is_textarea
5450                                    {
5451                                        el.label_for = target.clone();
5452                                    }
5453                                }
5454                            }
5455                        }
5456
5457                        if is_hr {
5458                            self.elements.push(RenderElement {
5459                                text: String::new(),
5460                                font_size: 16,
5461                                color: 0xFF44475A,
5462                                bg_color: None,
5463                                hover_bg_color: extract_hover_color_alt(
5464                                    styled,
5465                                    "background-color",
5466                                    "background",
5467                                ),
5468                                hover_color: extract_hover_color(styled, "color"),
5469                                hover_border_color: extract_hover_color(styled, "border-color"),
5470                                filter: styled.value("filter").unwrap_or_default(),
5471                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5472                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5473                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5474                                text_stroke_width: extract_text_stroke(styled).0,
5475                                text_stroke_color: extract_text_stroke(styled).1,
5476                                marker_color: extract_marker_color(styled),
5477                                marker_font_size: extract_marker_font_size(styled),
5478                                marker_content: extract_marker_content(styled),
5479                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
5480                                focus_color: extract_focus_color(styled, "color"),
5481                                focus_border_color: extract_focus_color(styled, "border-color"),
5482                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
5483                                active_color: extract_active_color(styled, "color"),
5484                                active_border_color: extract_active_color(styled, "border-color"),
5485                                border_color: None,
5486                                border_style: super::BorderStyle::Solid,
5487                                font_bold: false,
5488                                underline: false,
5489                                is_video: false,
5490                                video_src: String::new(),
5491                                is_link: false,
5492                                href: String::new(),
5493                                is_hr: true,
5494                                is_img: false,
5495                                canvas_ctx_id,
5496                                img_alt: String::new(),
5497                                is_input: false,
5498                                is_textarea: false,
5499                                is_button: false,
5500                                button_icon: 0,
5501                                element_id: String::new(),
5502                                node_idx: styled.node.node_idx,
5503                                onclick: String::new(),
5504                                form_action: String::new(),
5505                                form_method: String::new(),
5506                                width: layout.dimensions.content.width,
5507                                x_offset: layout.dimensions.content.x,
5508                                y_offset: layout.dimensions.content.y,
5509                                height: match aspect_ratio_val {
5510                                    Some(ratio) if layout.dimensions.content.height <= 0 => {
5511                                        (layout.dimensions.content.width as f32 / ratio) as i32
5512                                    }
5513                                    _ => layout.dimensions.content.height,
5514                                },
5515                                aspect_ratio: aspect_ratio_val,
5516                                border_radius: (0, 0, 0, 0),
5517                                is_li: false,
5518                                li_num: None,
5519                                is_blockquote: false,
5520                                z_index: self.inherited_paint_z,
5521                                paint_depth: self.inherited_paint_depth,
5522                                is_positioned: is_positioned_effective,
5523                                ..Default::default()
5524                            });
5525                        } else if is_img {
5526                            let alt = if inline_svg_src.is_some() {
5527                                String::new()
5528                            } else {
5529                                attributes.get("alt").cloned().unwrap_or_default()
5530                            };
5531                            let src = inline_svg_src
5532                                .clone()
5533                                .or_else(|| attributes.get("src").cloned())
5534                                .unwrap_or_default();
5535
5536                            self.elements.push(RenderElement {
5537                                text: String::new(),
5538                                font_size: 16,
5539                                color: next_color.unwrap_or(0xFFF8F8F2),
5540                                bg_color,
5541                                hover_bg_color: extract_hover_color_alt(
5542                                    styled,
5543                                    "background-color",
5544                                    "background",
5545                                ),
5546                                hover_color: extract_hover_color(styled, "color"),
5547                                hover_border_color: extract_hover_color(styled, "border-color"),
5548                                filter: styled.value("filter").unwrap_or_default(),
5549                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5550                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5551                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5552                                text_stroke_width: extract_text_stroke(styled).0,
5553                                text_stroke_color: extract_text_stroke(styled).1,
5554                                marker_color: extract_marker_color(styled),
5555                                marker_font_size: extract_marker_font_size(styled),
5556                                marker_content: extract_marker_content(styled),
5557                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
5558                                focus_color: extract_focus_color(styled, "color"),
5559                                focus_border_color: extract_focus_color(styled, "border-color"),
5560                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
5561                                active_color: extract_active_color(styled, "color"),
5562                                active_border_color: extract_active_color(styled, "border-color"),
5563                                border_color: extract_border_color(styled, 0xFF44475A),
5564                                border_style: extract_border_style(styled),
5565                                font_bold: false,
5566                                underline: false,
5567                                is_video: false,
5568                                video_src: src,
5569                                is_link: false,
5570                                href: String::new(),
5571                                is_hr: false,
5572                                is_img: true,
5573                                img_lazy: attributes
5574                                    .get("loading")
5575                                    .is_some_and(|v| v.trim().eq_ignore_ascii_case("lazy")),
5576                                canvas_ctx_id,
5577                                img_alt: alt,
5578                                is_input: false,
5579                                is_textarea: false,
5580                                is_button: false,
5581                                button_icon: 0,
5582                                element_id: el_id,
5583                                node_idx: styled.node.node_idx,
5584                                scroll_margin_top: styled.value("scroll-margin-top").map(|v| parse_px_val(&v)).unwrap_or(0),
5585                                onclick,
5586                                form_action: String::new(),
5587                                form_method: String::new(),
5588                                width: layout.dimensions.content.width,
5589                                x_offset: layout.dimensions.content.x,
5590                                y_offset: layout.dimensions.content.y,
5591                                height: layout.dimensions.content.height,
5592                                border_radius,
5593                                is_li: false,
5594                                li_num: None,
5595                                is_blockquote: false,
5596                                // `mask-image` はフルサポート(url()による画像マスク等)は非対応だが、
5597                                // `circle()`/`ellipse()`/`polygon()` 等の図形関数構文は `clip-path` と
5598                                // 全く同じ `parse_clip_shape` を再利用してマスキングできる。`clip-path`
5599                                // が無指定のときのみ `mask-image` にフォールバックする(`clip-path` が
5600                                // 優先、両方指定されるケースは稀なため簡略化)。`mask-image:url(...)`
5601                                // のような非対応構文は `parse_clip_shape` がどのプレフィックスにも
5602                                // 一致せず `None` を返すため、単に無視されるだけで安全。
5603                                clip_path: styled
5604                                    .value("clip-path")
5605                                    .or_else(|| styled.value("mask-image"))
5606                                    .unwrap_or_default(),
5607                                object_fit: parse_object_fit(styled.value("object-fit").as_deref()),
5608                                object_pos_x: parse_object_position(
5609                                    styled.value("object-position").as_deref(),
5610                                )
5611                                .0,
5612                                object_pos_y: parse_object_position(
5613                                    styled.value("object-position").as_deref(),
5614                                )
5615                                .1,
5616                                z_index: self.inherited_paint_z,
5617                                paint_depth: self.inherited_paint_depth,
5618                                is_positioned: is_positioned_effective,
5619                                ..Default::default()
5620                            });
5621                        } else if is_video {
5622                            let src = attributes.get("src").cloned().unwrap_or(String::new());
5623                            self.elements.push(RenderElement {
5624                                text: String::new(),
5625                                font_size: 16,
5626                                color: next_color.unwrap_or(0xFFF8F8F2),
5627                                bg_color,
5628                                hover_bg_color: extract_hover_color_alt(
5629                                    styled,
5630                                    "background-color",
5631                                    "background",
5632                                ),
5633                                hover_color: extract_hover_color(styled, "color"),
5634                                hover_border_color: extract_hover_color(styled, "border-color"),
5635                                filter: styled.value("filter").unwrap_or_default(),
5636                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5637                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5638                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5639                                text_stroke_width: extract_text_stroke(styled).0,
5640                                text_stroke_color: extract_text_stroke(styled).1,
5641                                marker_color: extract_marker_color(styled),
5642                                marker_font_size: extract_marker_font_size(styled),
5643                                marker_content: extract_marker_content(styled),
5644                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
5645                                focus_color: extract_focus_color(styled, "color"),
5646                                focus_border_color: extract_focus_color(styled, "border-color"),
5647                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
5648                                active_color: extract_active_color(styled, "color"),
5649                                active_border_color: extract_active_color(styled, "border-color"),
5650                                border_color: extract_border_color(styled, 0xFF6272A4),
5651                                border_style: extract_border_style(styled),
5652                                font_bold: false,
5653                                underline: false,
5654                                is_video: true,
5655                                video_src: src,
5656                                video_has_controls: attributes.contains_key("controls"),
5657                                video_autoplay: attributes.contains_key("autoplay"),
5658                                video_poster: attributes.get("poster").cloned().unwrap_or_default(),
5659                                video_loop: attributes.contains_key("loop"),
5660                                is_link: false,
5661                                href: String::new(),
5662                                is_hr: false,
5663                                is_img: false,
5664                                canvas_ctx_id,
5665                                img_alt: String::new(),
5666                                is_input: false,
5667                                is_textarea: false,
5668                                is_button: false,
5669                                button_icon: 0,
5670                                element_id: el_id,
5671                                node_idx: styled.node.node_idx,
5672                                scroll_margin_top: styled.value("scroll-margin-top").map(|v| parse_px_val(&v)).unwrap_or(0),
5673                                onclick,
5674                                form_action: String::new(),
5675                                form_method: String::new(),
5676                                width: layout.dimensions.content.width,
5677                                x_offset: layout.dimensions.content.x,
5678                                y_offset: layout.dimensions.content.y,
5679                                height: layout.dimensions.content.height,
5680                                border_radius,
5681                                is_li: false,
5682                                li_num: None,
5683                                is_blockquote: false,
5684                                z_index: self.inherited_paint_z,
5685                                paint_depth: self.inherited_paint_depth,
5686                                is_positioned: is_positioned_effective,
5687                                ..Default::default()
5688                            });
5689                        } else if is_progress {
5690                            // input_kind=4 として checkbox/radio/select と同じ仕組みに便乗し、
5691                            // 比率(0.0..1.0)の文字列表現を input_value に格納する
5692                            // (RenderElement に新規フィールドを増やさない簡略実装)。
5693                            self.elements.push(RenderElement {
5694                                text: String::new(),
5695                                font_size: 16,
5696                                color: next_color.unwrap_or(0xFFF8F8F2),
5697                                bg_color,
5698                                hover_bg_color: extract_hover_color_alt(
5699                                    styled,
5700                                    "background-color",
5701                                    "background",
5702                                ),
5703                                hover_color: extract_hover_color(styled, "color"),
5704                                hover_border_color: extract_hover_color(styled, "border-color"),
5705                                filter: styled.value("filter").unwrap_or_default(),
5706                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5707                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5708                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5709                                text_stroke_width: extract_text_stroke(styled).0,
5710                                text_stroke_color: extract_text_stroke(styled).1,
5711                                border_color: extract_border_color(styled, 0xFF6272A4),
5712                                border_style: extract_border_style(styled),
5713                                is_video: false,
5714                                video_src: String::new(),
5715                                is_link: false,
5716                                href: String::new(),
5717                                is_hr: false,
5718                                is_img: false,
5719                                canvas_ctx_id,
5720                                img_alt: String::new(),
5721                                is_input: false,
5722                                is_textarea: false,
5723                                is_button: false,
5724                                input_kind: 4,
5725                                input_value: alloc::format!("{}", progress_ratio),
5726                                element_id: el_id,
5727                                node_idx: styled.node.node_idx,
5728                                onclick,
5729                                width: layout.dimensions.content.width,
5730                                x_offset: layout.dimensions.content.x,
5731                                y_offset: layout.dimensions.content.y,
5732                                height: layout.dimensions.content.height,
5733                                border_radius,
5734                                z_index: self.inherited_paint_z,
5735                                paint_depth: self.inherited_paint_depth,
5736                                is_positioned: is_positioned_effective,
5737                                ..Default::default()
5738                            });
5739                        } else if tag_name == "iframe" {
5740                            let src = attributes.get("src").cloned().unwrap_or(String::new());
5741                            let width = layout.dimensions.content.width;
5742                            let height = layout.dimensions.content.height;
5743                            let iframe_preview = self.iframe_preview_for(&src);
5744                            self.elements.push(RenderElement {
5745                                is_iframe: true,
5746                                iframe_src: src,
5747                                iframe_preview,
5748                                width,
5749                                height,
5750                                x_offset: layout.dimensions.content.x,
5751                                y_offset: layout.dimensions.content.y,
5752                                border_color: if attributes.get("frameborder").map(|v| v.trim()) == Some("0") {
5753                                    None
5754                                } else {
5755                                    extract_border_color(styled, 0xFF6272A4)
5756                                },
5757                                border_style: extract_border_style(styled),
5758                                border_radius,
5759                                element_id: el_id,
5760                                node_idx: styled.node.node_idx,
5761                                z_index: self.inherited_paint_z,
5762                                paint_depth: self.inherited_paint_depth,
5763                                is_positioned: is_positioned_effective,
5764                                ..Default::default()
5765                            });
5766                        } else if is_input || is_textarea || is_select {
5767                            // --- checkbox / radio / select の状態を form_values に初期化 ---
5768                            let mut radio_group = String::new();
5769                            let mut input_value = String::new();
5770                            let mut select_options: alloc::vec::Vec<(String, String)> =
5771                                alloc::vec::Vec::new();
5772
5773                            if input_kind == 1 || input_kind == 2 {
5774                                // checkbox / radio: value 属性(既定 "on")と checked 初期状態。
5775                                input_value = attributes
5776                                    .get("value")
5777                                    .cloned()
5778                                    .unwrap_or_else(|| String::from("on"));
5779                                if input_kind == 2 {
5780                                    radio_group =
5781                                        attributes.get("name").cloned().unwrap_or_default();
5782                                }
5783                                let checked = attributes.contains_key("checked");
5784                                let init_v = if checked {
5785                                    input_value.clone()
5786                                } else {
5787                                    String::new()
5788                                };
5789                                if !el_id.is_empty() {
5790                                    self.initial_form_values
5791                                        .insert(el_id.clone(), init_v.clone());
5792                                    if !self.form_values.contains_key(&el_id) {
5793                                        // checked のときのみ value を、未チェックは空文字を格納。
5794                                        self.form_values.insert(el_id.clone(), init_v);
5795                                    }
5796                                }
5797                            } else if input_kind == 3 {
5798                                // select: option 一覧を収集し、選択中の value を form_values に格納。
5799                                let (opts, sel_idx) = collect_select_options(layout);
5800                                select_options = opts;
5801                                let init_v = select_options
5802                                    .get(sel_idx)
5803                                    .map(|(val, _)| val.clone())
5804                                    .unwrap_or_default();
5805                                if !el_id.is_empty() {
5806                                    self.initial_form_values
5807                                        .insert(el_id.clone(), init_v.clone());
5808                                    if !self.form_values.contains_key(&el_id) {
5809                                        self.form_values.insert(el_id.clone(), init_v);
5810                                    }
5811                                }
5812                            } else if input_kind == 5 {
5813                                // <input type="range">: min/max/step を select_options に
5814                                // (name, value) ペアとして格納する(RenderElement に新規
5815                                // フィールドを増やさず、select 用の Vec<(String,String)> を
5816                                // 流用する簡略実装。クリックで値を設定するのみでドラッグは非対応)。
5817                                let min_s =
5818                                    attributes.get("min").cloned().unwrap_or_else(|| String::from("0"));
5819                                let max_s = attributes
5820                                    .get("max")
5821                                    .cloned()
5822                                    .unwrap_or_else(|| String::from("100"));
5823                                let step_s = attributes
5824                                    .get("step")
5825                                    .cloned()
5826                                    .unwrap_or_else(|| String::from("1"));
5827                                let min_f: f32 = min_s.parse().unwrap_or(0.0);
5828                                let max_f: f32 = max_s.parse().unwrap_or(100.0);
5829                                select_options = alloc::vec![
5830                                    (String::from("min"), min_s),
5831                                    (String::from("max"), max_s),
5832                                    (String::from("step"), step_s),
5833                                ];
5834                                let default_v = alloc::format!("{}", (min_f + max_f) / 2.0);
5835                                let init_v = attributes.get("value").cloned().unwrap_or(default_v);
5836                                if !el_id.is_empty() {
5837                                    self.initial_form_values
5838                                        .insert(el_id.clone(), init_v.clone());
5839                                    if !self.form_values.contains_key(&el_id) {
5840                                        self.form_values.insert(el_id.clone(), init_v);
5841                                    }
5842                                }
5843                            } else {
5844                                // text / textarea: value 属性(textarea は子テキスト)を初期値に。
5845                                let mut val =
5846                                    attributes.get("value").cloned().unwrap_or(String::new());
5847                                if val.is_empty() && is_textarea {
5848                                    val = get_text_content(layout);
5849                                }
5850                                if !el_id.is_empty() {
5851                                    self.initial_form_values.insert(el_id.clone(), val.clone());
5852                                    if !self.form_values.contains_key(&el_id) {
5853                                        self.form_values.insert(el_id.clone(), val);
5854                                    }
5855                                }
5856                                // autofocus 属性: ページロード時点でこの入力欄へフォーカス。
5857                                // (まだどこにもフォーカスが無い場合のみ。DDG 検索ボックス等で有効)
5858                                if !el_id.is_empty()
5859                                    && self.focused_id.is_none()
5860                                    && attributes.contains_key("autofocus")
5861                                {
5862                                    self.focused_id = Some(el_id.clone());
5863                                    // `document.activeElement`(HTML5。丸ごと未対応
5864                                    // だった)が実際のフォーカス状態を反映できるよう、
5865                                    // JS 側の `DomBridge::focused_idx` にも同期する。
5866                                    let didx = self.js_runtime.dom().borrow().get_element_by_id(&el_id);
5867                                    self.js_runtime.dom().borrow_mut().focused_idx = didx;
5868                                }
5869                            }
5870
5871                            self.elements.push(RenderElement {
5872                                text: String::new(),
5873                                font_size: 16,
5874                                color: next_color.unwrap_or(0xFFF8F8F2),
5875                                bg_color,
5876                                hover_bg_color: extract_hover_color_alt(
5877                                    styled,
5878                                    "background-color",
5879                                    "background",
5880                                ),
5881                                hover_color: extract_hover_color(styled, "color"),
5882                                hover_border_color: extract_hover_color(styled, "border-color"),
5883                                filter: styled.value("filter").unwrap_or_default(),
5884                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5885                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5886                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5887                                text_stroke_width: extract_text_stroke(styled).0,
5888                                text_stroke_color: extract_text_stroke(styled).1,
5889                                marker_color: extract_marker_color(styled),
5890                                marker_font_size: extract_marker_font_size(styled),
5891                                marker_content: extract_marker_content(styled),
5892                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
5893                                focus_color: extract_focus_color(styled, "color"),
5894                                focus_border_color: extract_focus_color(styled, "border-color"),
5895                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
5896                                active_color: extract_active_color(styled, "color"),
5897                                active_border_color: extract_active_color(styled, "border-color"),
5898                                border_color: extract_border_color(styled, 0xFF6272A4),
5899                                border_style: extract_border_style(styled),
5900                                font_bold: false,
5901                                underline: false,
5902                                is_video: false,
5903                                video_src: String::new(),
5904                                is_link: false,
5905                                href: String::new(),
5906                                is_hr: false,
5907                                is_img: false,
5908                                canvas_ctx_id,
5909                                img_alt: String::new(),
5910                                // checkbox/radio/select はテキスト編集対象外なので is_input=false。
5911                                is_input: is_input && input_kind == 0,
5912                                is_textarea,
5913                                caret_color: styled.value("caret-color").and_then(|v| parse_color(&v)),
5914                                accent_color: styled.value("accent-color").and_then(|v| parse_color(&v)),
5915                                placeholder_color: extract_placeholder_color(styled),
5916                                placeholder: attributes.get("placeholder").cloned().unwrap_or_default(),
5917                                is_button: false,
5918                                input_kind,
5919                                radio_group,
5920                                input_value,
5921                                select_options,
5922                                button_icon: 0,
5923                                element_id: el_id,
5924                                node_idx: styled.node.node_idx,
5925                                scroll_margin_top: styled.value("scroll-margin-top").map(|v| parse_px_val(&v)).unwrap_or(0),
5926                                onclick,
5927                                form_action: String::new(),
5928                                form_method: String::new(),
5929                                width: layout.dimensions.content.width,
5930                                x_offset: layout.dimensions.content.x,
5931                                y_offset: layout.dimensions.content.y,
5932                                height: layout.dimensions.content.height,
5933                                border_radius,
5934                                is_li: false,
5935                                li_num: None,
5936                                is_blockquote: false,
5937                                z_index: self.inherited_paint_z,
5938                                paint_depth: self.inherited_paint_depth,
5939                                is_positioned: is_positioned_effective,
5940                                ..Default::default()
5941                            });
5942                        } else if is_button {
5943                            // 子要素を持つボタンは中身を普通に描く(`skip_children`)。自身のラベルにも
5944                            // 描くと文字が二重になる(YouTube の「チャンネル登録」、2026-11-01)。
5945                            let mut text = if has_child_elements {
5946                                String::new()
5947                            } else {
5948                                get_text_content(layout)
5949                            };
5950                            let class_val =
5951                                attributes.get("class").cloned().unwrap_or(String::new());
5952                            let mut icon_id = 0;
5953                            if class_val == "save_btn" {
5954                                icon_id = 1;
5955                            } else if class_val == "load_btn" {
5956                                icon_id = 2;
5957                            } else if class_val == "wrap_btn" {
5958                                icon_id = 3;
5959                            }
5960
5961                            if el_id == "wrap_status" {
5962                                text = if self.editor_wrap {
5963                                    String::from("Wrap: ON")
5964                                } else {
5965                                    String::from("Wrap: OFF")
5966                                };
5967                            } else if text.is_empty() && !has_child_elements {
5968                                text = attributes
5969                                    .get("value")
5970                                    .cloned()
5971                                    .unwrap_or(String::from("Button"));
5972                            }
5973                            self.elements.push(RenderElement {
5974                                text,
5975                                font_size: 16,
5976                                color: 0xFFF8F8F2,
5977                                bg_color,
5978                                hover_bg_color: extract_hover_color_alt(
5979                                    styled,
5980                                    "background-color",
5981                                    "background",
5982                                ),
5983                                hover_color: extract_hover_color(styled, "color"),
5984                                hover_border_color: extract_hover_color(styled, "border-color"),
5985                                filter: styled.value("filter").unwrap_or_default(),
5986                                mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
5987                                backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
5988                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
5989                                text_stroke_width: extract_text_stroke(styled).0,
5990                                text_stroke_color: extract_text_stroke(styled).1,
5991                                marker_color: extract_marker_color(styled),
5992                                marker_font_size: extract_marker_font_size(styled),
5993                                marker_content: extract_marker_content(styled),
5994                                focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
5995                                focus_color: extract_focus_color(styled, "color"),
5996                                focus_border_color: extract_focus_color(styled, "border-color"),
5997                                active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
5998                                active_color: extract_active_color(styled, "color"),
5999                                active_border_color: extract_active_color(styled, "border-color"),
6000                                border_color: extract_border_color(styled, 0xFF6272A4),
6001                                border_style: extract_border_style(styled),
6002                                font_bold: false,
6003                                underline: false,
6004                                is_video: false,
6005                                video_src: String::new(),
6006                                is_link: false,
6007                                href: String::new(),
6008                                is_hr: false,
6009                                is_img: false,
6010                                canvas_ctx_id,
6011                                img_alt: String::new(),
6012                                is_input: false,
6013                                is_textarea: false,
6014                                is_button: true,
6015                                is_reset: is_reset_btn,
6016                                btn_author_bg: super::button_paint::author_set_background(
6017                                    styled.value("background-color").as_deref(),
6018                                    styled.value("background").as_deref(),
6019                                ),
6020                                button_icon: icon_id,
6021                                element_id: el_id,
6022                                node_idx: styled.node.node_idx,
6023                                scroll_margin_top: styled.value("scroll-margin-top").map(|v| parse_px_val(&v)).unwrap_or(0),
6024                                onclick,
6025                                form_action: if no_submit { String::new() } else { current_form_action.into() },
6026                                form_method: if no_submit { String::new() } else { current_form_method.into() },
6027                                width: layout.dimensions.content.width,
6028                                x_offset: layout.dimensions.content.x,
6029                                y_offset: layout.dimensions.content.y,
6030                                height: layout.dimensions.content.height,
6031                                border_radius,
6032                                is_li: false,
6033                                li_num: None,
6034                                is_blockquote: false,
6035                                is_fixed: is_fixed_pos,
6036                                is_positioned: is_positioned_effective,
6037                                z_index: self.inherited_paint_z,
6038                                paint_depth: self.inherited_paint_depth,
6039                                ..Default::default()
6040                            });
6041                        }
6042                    }
6043                    crate::os_lib::dom::NodeType::Text(text) => {
6044                        let mut display_text = text.clone();
6045                        if !parent_id.is_empty() {
6046                            if let Some(updated_text) = self.dom_contents.get(parent_id) {
6047                                display_text = updated_text.clone();
6048                            }
6049                        }
6050                        // text-transform(uppercase / lowercase / capitalize)。
6051                        if let Some(tt) = styled.specified_values.get("text-transform") {
6052                            display_text =
6053                                crate::os_lib::css::apply_text_transform(&display_text, tt);
6054                        }
6055                        // hyphens: ソフトハイフン(U+00AD, `&shy;`)は、実際に行分割される箇所でだけ
6056                        // "-" として見せるのが仕様(既定値 manual)だが、この処理系は
6057                        // 折り返し位置を決めるアルゴリズムにハイフン挿入判定を組み込んでいないため、
6058                        // 常に非表示にする簡略実装(`hyphens:none` と同じ扱い)。誤った箇所に
6059                        // ハイフンが出てしまうより、常に非表示の方が実害が小さいとの判断。
6060                        if display_text.contains('\u{00AD}') {
6061                            display_text = display_text.replace('\u{00AD}', "");
6062                        }
6063                        // 【2026-09-26】white-space に従って空白を畳む(normal/nowrap では
6064                        // 改行・タブを含む連続を空白 1 つに)。従来は畳まずにタブ展開までしており、
6065                        // HTML の字下げが行頭の大きな空白になって文を押し出していた。
6066                        // タブ展開(下)は pre 系で残ったタブにだけ効く。
6067                        {
6068                            let ws_mode = styled.value("white-space").unwrap_or_default();
6069                            display_text = crate::os_lib::layout::line_break::collapse_white_space(
6070                                &display_text,
6071                                &ws_mode,
6072                            );
6073                        }
6074                        // 行頭・匿名アイテム先頭の空白はレイアウトが幅から外した(`trim_leading_space`)。
6075                        // 描画でも落とさないと箱の左端から空白ぶん右へずれる(2026-10-14)。
6076                        if layout.trim_leading_space {
6077                            if let Some(rest) = display_text.strip_prefix(' ') {
6078                                display_text = String::from(rest);
6079                            }
6080                        }
6081                        // tab-size: タブ文字(U+0009)を N 個の半角スペースへ展開する
6082                        // (実ブラウザのようなタブ位置ストップ計算はせず、単純な固定幅展開)。
6083                        if display_text.contains('\t') {
6084                            let tab_size = styled
6085                                .value("tab-size")
6086                                .and_then(|v| v.trim().parse::<usize>().ok())
6087                                .filter(|n| *n > 0)
6088                                .unwrap_or(8)
6089                                .min(64);
6090                            display_text = display_text.replace('\t', &" ".repeat(tab_size));
6091                        }
6092                        let is_link = !current_href.is_empty();
6093                        let (default_text_color, default_link_color) = self.default_text_colors();
6094                        let default_color = if is_link {
6095                            default_link_color
6096                        } else {
6097                            default_text_color
6098                        };
6099                        let mut final_color = current_color.unwrap_or(default_color);
6100                        if is_link {
6101                            final_color = default_link_color;
6102                        }
6103                        let mut final_bg = None;
6104                        // 【2026-08-03】テキスト要素へ `font-family` を渡す。
6105                        //
6106                        // `RenderElement` の生成箇所は 12 あるが、
6107                        // `font_family` を設定していたのは 2 箇所だけで、
6108                        // **本文テキストの要素は空のまま**だった。
6109                        // そのため Web フォントを取得・登録できても
6110                        // 描画で選ばれなかった(実測: 使われたのは
6111                        // アイコンフォントだけ)。
6112                        //
6113                        // `font-family` は継承プロパティなので、カスケード済みの
6114                        // `styled` から引けば子要素でも解決済みの値が得られる。
6115                        let final_font_family = styled
6116                            .value("font-family")
6117                            .map(|v| String::from(v.trim()))
6118                            .unwrap_or_default();
6119                        let mut final_size = current_font_size;
6120                        let mut final_bold = current_font_bold;
6121                        let mut final_italic = current_font_italic;
6122                        let mut final_underline = current_underline;
6123                        let mut final_line_through = current_line_through;
6124                        let mut final_overline = current_overline;
6125                        let mut final_decoration_color = current_decoration_color;
6126                        let mut final_decoration_style = current_decoration_style.clone();
6127                        let mut final_decoration_thickness = current_decoration_thickness;
6128                        let mut final_decoration_underline_offset = current_decoration_underline_offset;
6129                        if let Some(c_str) = styled.specified_values.get("color") {
6130                            if let Some(c_val) = parse_color(c_str) {
6131                                final_color = c_val;
6132                            }
6133                        }
6134                        if let Some(bg_val) =
6135                            extract_color(styled, "background-color", "background")
6136                        {
6137                            final_bg = Some(bg_val);
6138                        }
6139                        if let Some(sz_str) = styled.specified_values.get("font-size") {
6140                            if let Some(sz_val) = parse_font_size(sz_str) {
6141                                final_size = sz_val;
6142                            }
6143                        }
6144                        if let Some(fw_str) = styled.specified_values.get("font-weight") {
6145                            let fw_l = fw_str.trim().to_lowercase();
6146                            if fw_l == "bold"
6147                                || fw_l == "bolder"
6148                                || fw_l.parse::<u32>().unwrap_or(400) >= 700
6149                            {
6150                                final_bold = true;
6151                            }
6152                        }
6153                        // 【2026-10-03】数値のウェイト(Web フォントの 500 等を選ぶため)。
6154                        // `font-weight` は継承されるので文字ノードの値をそのまま使う。
6155                        let final_weight: u16 = {
6156                            let w = styled
6157                                .value("font-weight")
6158                                .map(|v| crate::kernel::font_select::parse_font_weight(&v))
6159                                .unwrap_or(400);
6160                            if final_bold { w.max(700) } else { w }
6161                        };
6162                        // 太字の上書き(::first-line 等)があるときのウェイト。
6163                        let weight_for = |b: bool| -> u16 {
6164                            if b {
6165                                final_weight.max(700)
6166                            } else if final_weight >= 700 {
6167                                400
6168                            } else {
6169                                final_weight
6170                            }
6171                        };
6172                        // letter-spacing/word-spacing の calc() 解決用の基準幅(% 解決の基準。
6173                        // letter-spacing/word-spacing は通常 % を取らないため主に
6174                        // `calc(1px + 1px)` 等の用途)。この時点ではまだ available_w が
6175                        // 未計算のため、同じフォールバック規則をここでも使う。
6176                        let ls_ws_base_w = if layout.dimensions.content.width > 0 {
6177                            layout.dimensions.content.width
6178                        } else {
6179                            800
6180                        };
6181                        // letter-spacing(文字間 px、負も可)。normal/未指定/不正は 0。
6182                        // calc()/min()/max()/clamp() や em 単位にも対応(要素フォントサイズ基準)。
6183                        let final_ls = crate::os_lib::layout::parse_letter_spacing_with_font(
6184                            styled.value("letter-spacing").as_deref(),
6185                            ls_ws_base_w,
6186                            final_size as f32,
6187                        );
6188                        // word-spacing(半角スペース1文字ごとに加える px、負も可)。normal/未指定/不正は 0。
6189                        let final_ws = crate::os_lib::layout::parse_word_spacing_with_font(
6190                            styled.value("word-spacing").as_deref(),
6191                            ls_ws_base_w,
6192                            final_size as f32,
6193                        );
6194                        // text-emphasis-style: "none"/未指定/空は無し。クォート付きカスタム
6195                        // マークはクォートを剥がして1文字目だけを使う簡略実装。
6196                        let final_emphasis_style = match styled.value("text-emphasis-style") {
6197                            None => String::new(),
6198                            Some(s) => {
6199                                let t = s.trim();
6200                                if t.is_empty() || t.eq_ignore_ascii_case("none") {
6201                                    String::new()
6202                                } else {
6203                                    String::from(t.trim_matches(|c| c == '"' || c == '\''))
6204                                }
6205                            }
6206                        };
6207                        let final_emphasis_color = styled
6208                            .value("text-emphasis-color")
6209                            .and_then(|s| crate::os_lib::css::parse_color(&s));
6210                        if let Some(fs_str) = styled.specified_values.get("font-style") {
6211                            let fs_l = fs_str.trim().to_lowercase();
6212                            if fs_l == "italic" || fs_l == "oblique" {
6213                                final_italic = true;
6214                            } else if fs_l == "normal" {
6215                                final_italic = false;
6216                            }
6217                        }
6218                        if let Some(td_str) = styled.specified_values.get("text-decoration") {
6219                            let (u, lt, ov, is_none, style, color) =
6220                                parse_text_decoration_shorthand(td_str);
6221                            if is_none {
6222                                final_underline = false;
6223                                final_line_through = false;
6224                                final_overline = false;
6225                            } else {
6226                                if u {
6227                                    final_underline = true;
6228                                }
6229                                if lt {
6230                                    final_line_through = true;
6231                                }
6232                                if ov {
6233                                    final_overline = true;
6234                                }
6235                                if let Some(s) = style {
6236                                    final_decoration_style = s;
6237                                }
6238                                if let Some(c) = color {
6239                                    final_decoration_color = Some(c);
6240                                }
6241                            }
6242                        }
6243                        if let Some(tdl) = styled.specified_values.get("text-decoration-line") {
6244                            let (u, lt, ov, is_none, _, _) = parse_text_decoration_shorthand(tdl);
6245                            if is_none {
6246                                final_underline = false;
6247                                final_line_through = false;
6248                                final_overline = false;
6249                            } else {
6250                                if u {
6251                                    final_underline = true;
6252                                }
6253                                if lt {
6254                                    final_line_through = true;
6255                                }
6256                                if ov {
6257                                    final_overline = true;
6258                                }
6259                            }
6260                        }
6261                        if let Some(dc) = styled.specified_values.get("text-decoration-color") {
6262                            if let Some(c) = parse_color(dc.trim()) {
6263                                final_decoration_color = Some(c);
6264                            }
6265                        }
6266                        if let Some(ds) = styled.specified_values.get("text-decoration-style") {
6267                            let ds_l = ds.trim().to_lowercase();
6268                            if matches!(ds_l.as_str(), "solid" | "dotted" | "dashed" | "wavy" | "double") {
6269                                final_decoration_style = ds_l;
6270                            }
6271                        }
6272                        if let Some(dt) = styled.specified_values.get("text-decoration-thickness") {
6273                            let dt_t = dt.trim();
6274                            if !dt_t.eq_ignore_ascii_case("auto") && !dt_t.eq_ignore_ascii_case("from-font") {
6275                                final_decoration_thickness = parse_px_val(dt_t).max(1);
6276                            }
6277                        }
6278                        if let Some(uo) = styled.specified_values.get("text-underline-offset") {
6279                            let uo_t = uo.trim();
6280                            if !uo_t.eq_ignore_ascii_case("auto") {
6281                                final_decoration_underline_offset = parse_px_val(uo_t);
6282                            }
6283                        }
6284
6285                        let is_actual_link = is_link;
6286                        let link_href = String::from(current_href);
6287
6288                        // text-indent: このテキストノードの最初の行だけを右へずらす簡易実装。
6289                        // 折返し幅(available_w)自体は変更しないため、vector_font 側の行数
6290                        // 計算との同期は崩れない(インデント分だけ最初の行の右端が浅く狭まる
6291                        // 近似になるが、実用上の見た目への影響は小さい)。`%`/`em`が丸ごと
6292                        // 未対応だったバグの詳細は`resolve_text_indent`のdocコメント参照。
6293                        let text_indent_px: i32 = styled
6294                            .value("text-indent")
6295                            .map(|s| resolve_text_indent(&s, layout.dimensions.content.width, final_size))
6296                            .unwrap_or(0);
6297
6298                        // ::first-line: このテキストノードの最初の行(line_index==0)にのみ
6299                        // color/font-size/font-weight/font-style を上書きする簡易実装。
6300                        // RenderElement は既に行ごとに分割されているため、::before/::after と
6301                        // 同じ合成プロパティ経由の値を line_index==0 の時だけ適用すればよい。
6302                        let fl_color = styled
6303                            .value("x-first-line-color")
6304                            .and_then(|s| parse_color(&s));
6305                        let fl_size = styled
6306                            .value("x-first-line-font-size")
6307                            .and_then(|s| parse_font_size(&s));
6308                        let fl_bold = styled.value("x-first-line-font-weight").map(|s| {
6309                            let l = s.trim().to_lowercase();
6310                            l == "bold" || l == "bolder" || l.parse::<u32>().unwrap_or(400) >= 700
6311                        });
6312                        let fl_italic = styled.value("x-first-line-font-style").map(|s| {
6313                            let l = s.trim().to_lowercase();
6314                            l == "italic" || l == "oblique"
6315                        });
6316
6317                        // ::first-letter: このテキストノードの最初の1文字だけを別の RenderElement
6318                        // として切り出し、color/font-size/font-weight/font-style を上書きする。
6319                        let flt_color = styled
6320                            .value("x-first-letter-color")
6321                            .and_then(|s| parse_color(&s));
6322                        let flt_size = styled
6323                            .value("x-first-letter-font-size")
6324                            .and_then(|s| parse_font_size(&s));
6325                        let flt_bold = styled.value("x-first-letter-font-weight").map(|s| {
6326                            let l = s.trim().to_lowercase();
6327                            l == "bold" || l == "bolder" || l.parse::<u32>().unwrap_or(400) >= 700
6328                        });
6329                        let flt_italic = styled.value("x-first-letter-font-style").map(|s| {
6330                            let l = s.trim().to_lowercase();
6331                            l == "italic" || l == "oblique"
6332                        });
6333                        let has_first_letter_override = flt_color.is_some()
6334                            || flt_size.is_some()
6335                            || flt_bold.is_some()
6336                            || flt_italic.is_some();
6337
6338                        // white-space / text-overflow / word-break from this node's own CSS or inheritance
6339                        let node_white_space_nowrap = styled
6340                            .value("white-space")
6341                            .map(|v| v.trim() == "nowrap")
6342                            .unwrap_or(false);
6343                        let node_white_space_pre_wrap = styled
6344                            .value("white-space")
6345                            .map(|v| v.trim() == "pre-wrap" || v.trim() == "pre-line")
6346                            .unwrap_or(false);
6347                        let node_word_break_all = styled
6348                            .value("word-break")
6349                            .map(|v| v.trim() == "break-all")
6350                            .unwrap_or(false);
6351                        let node_overflow_wrap = styled
6352                            .value("overflow-wrap")
6353                            .map(|v| v.trim() == "break-word" || v.trim() == "anywhere")
6354                            .unwrap_or(false)
6355                            || styled
6356                                .value("word-wrap")
6357                                .map(|v| v.trim() == "break-word" || v.trim() == "anywhere")
6358                                .unwrap_or(false)
6359                            || styled
6360                                .value("word-break")
6361                                .map(|v| v.trim() == "break-word")
6362                                .unwrap_or(false);
6363                        let node_text_overflow_ellipsis = styled
6364                            .value("text-overflow")
6365                            .map(|v| v.trim() == "ellipsis")
6366                            .unwrap_or(false);
6367                        // `text-overflow:ellipsis` は `direction:rtl` では省略記号を先頭(視覚上の
6368                        // 左)に出し、末尾ではなく先頭側の文字を切り詰めるべき(CSS仕様)。
6369                        // 以前はこの区別が無く、rtl でも常に末尾を切り詰め末尾に "…" を
6370                        // 付けていたため、rtl テキストの省略位置が仕様と逆になっていた。
6371                        let node_is_rtl = styled
6372                            .value("direction")
6373                            .map(|v| v.trim().eq_ignore_ascii_case("rtl"))
6374                            .unwrap_or(false);
6375
6376                        if !display_text.trim().is_empty() {
6377                            let available_w = if layout.dimensions.content.width > 0 {
6378                                layout.dimensions.content.width
6379                            } else {
6380                                800
6381                            };
6382                            // 【2026-10-04】折り返した行の行揃え(`text_align::line_start_offset`)。
6383                            // `text-align` は継承プロパティなので文字ノードから引ける。
6384                            let node_text_align = styled.value("text-align").unwrap_or_default();
6385                            let mut current_line = String::new();
6386                            let mut current_line_w = 0i32;
6387
6388                            // line-height の解釈
6389                            let mut line_height = (final_size + 4) as i32;
6390                            if let Some(lh_str) = styled.value("line-height") {
6391                                line_height = parse_line_height(&lh_str, final_size);
6392                            }
6393                            let half_lead = crate::os_lib::layout::half_leading(line_height, final_size);
6394
6395                            // white-space: nowrap — emit entire text as one RenderElement
6396                            if node_white_space_nowrap {
6397                                let text_w = crate::kernel::vector_font::get_vector_string_width_ls_ws(
6398                                    &display_text,
6399                                    final_size,
6400                                    final_ls,
6401                                    final_ws,
6402                                ) as i32;
6403                                let line_y = layout.dimensions.content.y;
6404                                self.elements.push(RenderElement {
6405                                    text: display_text.clone(),
6406                                    font_family: final_font_family.clone(),
6407                                    font_size: fl_size.unwrap_or(final_size),
6408                                    letter_spacing: final_ls,
6409                                    word_spacing: final_ws,
6410                                    text_emphasis_style: final_emphasis_style.clone(),
6411                                    text_emphasis_color: final_emphasis_color,
6412                                    color: fl_color.unwrap_or(final_color),
6413                                    bg_color: final_bg,
6414                                    font_bold: fl_bold.unwrap_or(final_bold),
6415                                    font_weight: weight_for(fl_bold.unwrap_or(final_bold)),
6416                                    font_italic: fl_italic.unwrap_or(final_italic),
6417                                    underline: final_underline,
6418                                    line_through: final_line_through,
6419                                    overline: final_overline,
6420                                    decoration_color: final_decoration_color,
6421                                    decoration_style: final_decoration_style.clone(),
6422                                    decoration_thickness: final_decoration_thickness,
6423                                    decoration_underline_offset: final_decoration_underline_offset,
6424                                    is_link: is_actual_link,
6425                                    pointer_events_none: current_pointer_events_none,
6426                                    href: link_href.clone(),
6427                                    width: if node_text_overflow_ellipsis && available_w > 0 && text_w > available_w {
6428                                        available_w
6429                                    } else {
6430                                        text_w
6431                                    },
6432                                    x_offset: layout.dimensions.content.x,
6433                                    y_offset: line_y + half_lead,
6434                                    height: line_height - 2 * half_lead,
6435                                    white_space_nowrap: true,
6436                                    text_overflow_ellipsis: node_text_overflow_ellipsis,
6437                                    text_overflow_rtl: node_is_rtl,
6438                                    z_index: self.inherited_paint_z,
6439                                    paint_depth: self.inherited_paint_depth,
6440                                    is_positioned: self.inherited_positioned,
6441                                    node_idx: styled.node.node_idx,
6442                                    ..Default::default()
6443                                });
6444                                if is_actual_link {
6445                                    let actual_w = if node_text_overflow_ellipsis && available_w > 0 && text_w > available_w {
6446                                        available_w
6447                                    } else {
6448                                        text_w
6449                                    };
6450                                    self.links.push(HyperlinkArea {
6451                                        href: link_href.clone(),
6452                                        x0: layout.dimensions.content.x,
6453                                        y0: line_y,
6454                                        x1: layout.dimensions.content.x + actual_w,
6455                                        y1: line_y + line_height,
6456                                    });
6457                                }
6458                                // skip normal text rendering
6459                            } else {
6460                                // 重要: この折返し規則 ('\n' 強制改行・行頭/行末禁則・改行時に
6461                                // 先頭文字を即消費) は vector_font::get_string_wrapped_size と
6462                                // 完全に同一でなければならない。ズレると layout の段落高さと
6463                                // 行数が食い違い <hr> 等が重なる。変更時は必ず両方を同期すること。
6464                                let mut line_index = 0;
6465                                let line_clamp_max: Option<usize> = styled
6466                                    .value("-webkit-line-clamp")
6467                                    .or_else(|| styled.value("line-clamp"))
6468                                    .and_then(|s| s.trim().parse::<usize>().ok());
6469                                let mut prev_char: Option<char> = None;
6470                                let mut prev_advance = 0i32;
6471
6472                                // ::first-letter: 先頭1文字を別 RenderElement として切り出し、
6473                                // 残りのテキストは通常どおり折返す(先頭文字ぶんだけ x をずらす)。
6474                                // 注意: 折返し判定に使う文字列から1文字減るため、極めて稀に
6475                                // os_lib::layout 側の段落高さ計算(元の文字列全体を使う)と
6476                                // 改行位置が1文字ぶんずれる可能性がある簡略実装(text-indent と同種の近似)。
6477                                let mut first_letter_x_shift = 0i32;
6478                                let first_letter_iter_buf;
6479                                // CSS の ::first-letter は前置の句読点・引用符(例: `"Hello`
6480                                // の `"H`、`«Bonjour»` の `«B`)を実際の最初の文字と一体で扱う
6481                                // 仕様(CSS Pseudo-Elements §3.2)のため、先に句読点類を読み飛ばして
6482                                // fc_str へ蓄積してから実際の最初の文字を1つ加える。
6483                                fn is_first_letter_leading_punct(c: char) -> bool {
6484                                    matches!(
6485                                        c,
6486                                        '!' | '"' | '#' | '$' | '%' | '&' | '\'' | '(' | ')'
6487                                            | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
6488                                            | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']'
6489                                            | '^' | '_' | '`' | '{' | '|' | '}' | '~'
6490                                            | '¡' | '¿' | '«' | '»'
6491                                            | '\u{201C}' | '\u{201D}' | '\u{2018}' | '\u{2019}'
6492                                    )
6493                                }
6494                                let wrap_text: &str = if has_first_letter_override {
6495                                    let mut chars_iter = display_text.chars();
6496                                    let mut fc_str = String::new();
6497                                    loop {
6498                                        let mut probe = chars_iter.clone();
6499                                        match probe.next() {
6500                                            Some(c) if is_first_letter_leading_punct(c) => {
6501                                                fc_str.push(c);
6502                                                chars_iter = probe;
6503                                            }
6504                                            _ => break,
6505                                        }
6506                                    }
6507                                    if let Some(fc) = chars_iter.next() {
6508                                        let fc_size = flt_size.unwrap_or(final_size);
6509                                        let fc_color = flt_color.unwrap_or(final_color);
6510                                        let fc_bold = flt_bold.unwrap_or(final_bold);
6511                                        let fc_italic = flt_italic.unwrap_or(final_italic);
6512                                        fc_str.push(fc);
6513                                        let fc_w = crate::kernel::vector_font::get_vector_string_width(
6514                                            &fc_str, fc_size,
6515                                        ) as i32;
6516                                        let line_y = layout.dimensions.content.y;
6517                                        self.elements.push(RenderElement {
6518                                            text: fc_str,
6519                                    font_family: final_font_family.clone(),
6520                                            font_size: fc_size,
6521                                            color: fc_color,
6522                                            bg_color: final_bg,
6523                                            font_bold: fc_bold,
6524                                            font_weight: weight_for(fc_bold),
6525                                            font_italic: fc_italic,
6526                                            underline: final_underline,
6527                                            line_through: final_line_through,
6528                                            overline: final_overline,
6529                                            decoration_color: final_decoration_color,
6530                                            decoration_style: final_decoration_style.clone(),
6531                                            decoration_thickness: final_decoration_thickness,
6532                                            decoration_underline_offset: final_decoration_underline_offset,
6533                                            is_link: is_actual_link,
6534                                            pointer_events_none: current_pointer_events_none,
6535                                            href: link_href.clone(),
6536                                            width: fc_w,
6537                                            x_offset: layout.dimensions.content.x + text_indent_px,
6538                                            y_offset: line_y + half_lead,
6539                                            height: line_height - 2 * half_lead,
6540                                            z_index: self.inherited_paint_z,
6541                                            paint_depth: self.inherited_paint_depth,
6542                                            is_positioned: self.inherited_positioned,
6543                                            node_idx: styled.node.node_idx,
6544                                            ..Default::default()
6545                                        });
6546                                        first_letter_x_shift = fc_w;
6547                                        first_letter_iter_buf = String::from(chars_iter.as_str());
6548                                        &first_letter_iter_buf
6549                                    } else {
6550                                        display_text.as_str()
6551                                    }
6552                                } else {
6553                                    display_text.as_str()
6554                                };
6555
6556                                // 【2026-09-26】折り返し位置は計測側と共通の純粋関数
6557                                // `line_break::break_positions` で先に決める(単語ごと次の行へ送る・
6558                                // 禁則・行末空白のぶら下げ)。字幅も描画と同じ書体で 1 回だけ測り、
6559                                // ループではその値を使う。従来は単語を送らずはみ出させており、
6560                                // 英語の文献リストで窓からはみ出した分が描画時に勝手に改行されて重なった。
6561                                let wrap_chars: alloc::vec::Vec<char> = wrap_text.chars().collect();
6562                                // 【2026-11-18 TODO R2 (d) ①】このタブだけ止める合図なら、残りの文字の字幅を測らない
6563                                // (4096 文字ごとに確かめる。足りない分は下の `.get` で 0 として扱われる)。
6564                                let mut wrap_advs: alloc::vec::Vec<i32> = alloc::vec::Vec::with_capacity(wrap_chars.len());
6565                                for (ci, &c) in wrap_chars.iter().enumerate() {
6566                                    if ci & (crate::os_lib::layout::line_break::BREAK_POLL_EVERY - 1) == 0
6567                                        && ci != 0
6568                                        && crate::kernel::window_mgr::layout_check()
6569                                    {
6570                                        break;
6571                                    }
6572                                    if c == '\n' || c == '\u{00AD}' {
6573                                        wrap_advs.push(0);
6574                                        continue;
6575                                    }
6576                                    let mut cs = String::new();
6577                                    cs.push(c);
6578                                    wrap_advs.push(
6579                                        crate::kernel::vector_font::get_vector_string_width_family(
6580                                            &cs,
6581                                            final_size,
6582                                            &final_font_family,
6583                                            final_weight,
6584                                            0,
6585                                            0,
6586                                        ) as i32
6587                                            + final_ls
6588                                            + if c == ' ' { final_ws } else { 0 },
6589                                    );
6590                                }
6591                                // 【2026-11-18 TODO R2 (b) ②】100 万文字の塊では折り返しの計算 1 回が長いので、4096 文字ごとに
6592                                // 止める確かめを呼ぶ(ここは字幅を測る関数と同じ錠の状況。錠を持っていない)。
6593                                let wrap_breaks = crate::os_lib::layout::line_break::break_positions_poll(
6594                                    &wrap_chars,
6595                                    &wrap_advs,
6596                                    available_w,
6597                                    node_word_break_all,
6598                                    node_overflow_wrap,
6599                                    |c| !node_word_break_all && crate::kernel::vector_font::is_line_start_forbidden(c),
6600                                    |c| !node_word_break_all && crate::kernel::vector_font::is_line_end_forbidden(c),
6601                                    crate::kernel::window_mgr::layout_check,
6602                                );
6603                                for (ci, c) in wrap_chars.iter().copied().enumerate() {
6604                                    // 行を組む 1 文字ずつのループも 4096 文字ごとに確かめる。このタブだけ止めるなら残りの行を作らない。
6605                                    if ci & (crate::os_lib::layout::line_break::BREAK_POLL_EVERY - 1) == 0
6606                                        && ci != 0
6607                                        && crate::kernel::window_mgr::layout_check()
6608                                    {
6609                                        break;
6610                                    }
6611                                    if c == '\n' {
6612                                        if node_white_space_pre_wrap {
6613                                            // pre-wrap: treat '\n' as an actual newline
6614                                        } else {
6615                                            // collapse mode: '\n' inside text that somehow survived tree.rs flattening
6616                                            // (usually tree.rs flattens it to a space, but if it got here, we still break)
6617                                        }
6618                                        let line_y =
6619                                            layout.dimensions.content.y + line_index * line_height;
6620                                        self.elements.push(RenderElement {
6621                                            text: current_line.clone(),
6622                                        font_family: final_font_family.clone(),
6623                                            font_size: if line_index == 0 { fl_size.unwrap_or(final_size) } else { final_size },
6624                                            letter_spacing: final_ls,
6625                                            word_spacing: final_ws,
6626                                            text_emphasis_style: final_emphasis_style.clone(),
6627                                            text_emphasis_color: final_emphasis_color,
6628                                            color: if line_index == 0 { fl_color.unwrap_or(final_color) } else { final_color },
6629                                            bg_color: final_bg,
6630                                            hover_bg_color: extract_hover_color_alt(
6631                                                styled,
6632                                                "background-color",
6633                                                "background",
6634                                            ),
6635                                            hover_color: extract_hover_color(styled, "color"),
6636                                            hover_border_color: extract_hover_color(
6637                                                styled,
6638                                                "border-color",
6639                                            ),
6640                                            filter: styled.value("filter").unwrap_or_default(),
6641                                            mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
6642                                            backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
6643                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
6644                                text_stroke_width: extract_text_stroke(styled).0,
6645                                text_stroke_color: extract_text_stroke(styled).1,
6646                                            marker_color: extract_marker_color(styled),
6647                                            marker_font_size: extract_marker_font_size(styled),
6648                                            marker_content: extract_marker_content(styled),
6649                                            focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
6650                                            focus_color: extract_focus_color(styled, "color"),
6651                                            focus_border_color: extract_focus_color(styled, "border-color"),
6652                                            active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
6653                                            active_color: extract_active_color(styled, "color"),
6654                                            active_border_color: extract_active_color(styled, "border-color"),
6655                                            border_color: None,
6656                                            border_style: super::BorderStyle::None,
6657                                            font_bold: if line_index == 0 { fl_bold.unwrap_or(final_bold) } else { final_bold },
6658                                            font_weight: weight_for(if line_index == 0 { fl_bold.unwrap_or(final_bold) } else { final_bold }),
6659                                            font_italic: if line_index == 0 { fl_italic.unwrap_or(final_italic) } else { final_italic },
6660                                            underline: final_underline,
6661                                            line_through: final_line_through,
6662                                            overline: final_overline,
6663                                            decoration_color: final_decoration_color,
6664                                            decoration_style: final_decoration_style.clone(),
6665                                            decoration_thickness: final_decoration_thickness,
6666                                            decoration_underline_offset: final_decoration_underline_offset,
6667                                            is_video: false,
6668                                            video_src: String::new(),
6669                                            is_link: is_actual_link,
6670                                            pointer_events_none: current_pointer_events_none,
6671                                            href: link_href.clone(),
6672                                            is_hr: false,
6673                                            is_img: false,
6674                                canvas_ctx_id: None,
6675                                            img_alt: String::new(),
6676                                            is_input: false,
6677                                            is_textarea: false,
6678                                            is_button: false,
6679                                            button_icon: 0,
6680                                            element_id: String::new(),
6681                                            onclick: String::new(),
6682                                            form_action: String::new(),
6683                                            form_method: String::new(),
6684                                            width: current_line_w,
6685                                            x_offset: layout.dimensions.content.x + if line_index == 0 { first_letter_x_shift } else { 0 }
6686                                                + super::text_align::line_start_offset(
6687                                                    // ::first-letter は 1 文字目を別要素で描くので揃えない(従来どおり左)。
6688                                                    if first_letter_x_shift != 0 { "left" } else { &node_text_align },
6689                                                    node_is_rtl,
6690                                                    available_w,
6691                                                    if line_index == 0 { text_indent_px } else { 0 },
6692                                                    current_line_w,
6693                                                ),
6694                                            y_offset: line_y + half_lead,
6695                                            height: line_height - 2 * half_lead,
6696                                            border_radius: (0, 0, 0, 0),
6697                                            is_li: parent_tag == "li" && line_index == 0,
6698                                            li_num: if parent_tag == "li" && line_index == 0 {
6699                                                if let Some((true, count)) = list_state {
6700                                                    Some(count)
6701                                                } else {
6702                                                    None
6703                                                }
6704                                            } else {
6705                                                None
6706                                            },
6707                                            list_style_type: extract_list_style(styled),
6708                                            list_style_inside: extract_list_style_inside(styled),
6709                                            list_style_image: extract_list_style_image(styled),
6710                                            is_blockquote: false,
6711                                            z_index: self.inherited_paint_z,
6712                                            paint_depth: self.inherited_paint_depth,
6713                                            is_positioned: self.inherited_positioned,
6714                                            node_idx: styled.node.node_idx,
6715                                            ..Default::default()
6716                                        });
6717
6718                                        if is_actual_link {
6719                                            self.links.push(HyperlinkArea {
6720                                                href: link_href.clone(),
6721                                                // 行揃えでずらした行に合わせる(直前に積んだ行の要素の位置)。
6722
6723                                                x0: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x),
6724                                                y0: line_y,
6725                                                x1: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x) + current_line_w,
6726                                                y1: line_y + line_height,
6727                                            });
6728                                        }
6729
6730                                        line_index += 1;
6731                                        // `-webkit-line-clamp`(テキスト中の明示的な`\n`による
6732                                        // 改行フラッシュ経路)。同種の改行フラッシュがもう1箇所
6733                                        // (自然な折返しオーバーフロー経路。約80行下)にもあり、
6734                                        // そちらにしかこのチェックが配線されていなかったため、
6735                                        // `\n`を含むテキストでは`-webkit-line-clamp`が効かない
6736                                        // バグだった(2026-07-22発見・修正)。
6737                                        if let Some(max) = line_clamp_max {
6738                                            if line_index >= max as i32 {
6739                                                break;
6740                                            }
6741                                        }
6742                                        current_line.clear();
6743                                        current_line_w = 0;
6744                                        prev_char = None;
6745                                        prev_advance = 0;
6746                                        continue;
6747                                    }
6748
6749                                    // 描画と同じ書体で測った字幅(折り返し位置の計算と同じ値)。
6750                                    let advance = wrap_advs.get(ci).copied().unwrap_or(0);
6751
6752                                    if !current_line.is_empty() && wrap_breaks.binary_search(&ci).is_ok()
6753                                    {
6754                                        // 折り返し位置で改行する(禁則・単語送りは計算済み)。
6755                                        let send_prev = false;
6756                                        let actual_w;
6757                                        let mut next_line = String::new();
6758                                        let mut next_line_w = 0;
6759
6760                                        if send_prev {
6761                                            if let Some(pc) = prev_char {
6762                                                current_line.pop();
6763                                                next_line.push(pc);
6764                                                next_line_w = prev_advance;
6765                                            }
6766                                            actual_w = current_line_w - prev_advance;
6767                                        } else {
6768                                            actual_w = current_line_w;
6769                                        }
6770
6771                                        let line_y =
6772                                            layout.dimensions.content.y + line_index * line_height;
6773                                        self.elements.push(RenderElement {
6774                                            text: current_line.clone(),
6775                                        font_family: final_font_family.clone(),
6776                                            font_size: if line_index == 0 { fl_size.unwrap_or(final_size) } else { final_size },
6777                                            letter_spacing: final_ls,
6778                                            word_spacing: final_ws,
6779                                            text_emphasis_style: final_emphasis_style.clone(),
6780                                            text_emphasis_color: final_emphasis_color,
6781                                            color: if line_index == 0 { fl_color.unwrap_or(final_color) } else { final_color },
6782                                            bg_color: final_bg,
6783                                            hover_bg_color: extract_hover_color_alt(
6784                                                styled,
6785                                                "background-color",
6786                                                "background",
6787                                            ),
6788                                            hover_color: extract_hover_color(styled, "color"),
6789                                            hover_border_color: extract_hover_color(
6790                                                styled,
6791                                                "border-color",
6792                                            ),
6793                                            filter: styled.value("filter").unwrap_or_default(),
6794                                            mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
6795                                            backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
6796                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
6797                                text_stroke_width: extract_text_stroke(styled).0,
6798                                text_stroke_color: extract_text_stroke(styled).1,
6799                                            marker_color: extract_marker_color(styled),
6800                                            marker_font_size: extract_marker_font_size(styled),
6801                                            marker_content: extract_marker_content(styled),
6802                                            focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
6803                                            focus_color: extract_focus_color(styled, "color"),
6804                                            focus_border_color: extract_focus_color(styled, "border-color"),
6805                                            active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
6806                                            active_color: extract_active_color(styled, "color"),
6807                                            active_border_color: extract_active_color(styled, "border-color"),
6808                                            border_color: None,
6809                                            border_style: super::BorderStyle::None,
6810                                            font_bold: if line_index == 0 { fl_bold.unwrap_or(final_bold) } else { final_bold },
6811                                            font_weight: weight_for(if line_index == 0 { fl_bold.unwrap_or(final_bold) } else { final_bold }),
6812                                            font_italic: if line_index == 0 { fl_italic.unwrap_or(final_italic) } else { final_italic },
6813                                            underline: final_underline,
6814                                            line_through: final_line_through,
6815                                            overline: final_overline,
6816                                            decoration_color: final_decoration_color,
6817                                            decoration_style: final_decoration_style.clone(),
6818                                            decoration_thickness: final_decoration_thickness,
6819                                            decoration_underline_offset: final_decoration_underline_offset,
6820                                            is_video: false,
6821                                            video_src: String::new(),
6822                                            is_link: is_actual_link,
6823                                            pointer_events_none: current_pointer_events_none,
6824                                            href: link_href.clone(),
6825                                            is_hr: false,
6826                                            is_img: false,
6827                                canvas_ctx_id: None,
6828                                            img_alt: String::new(),
6829                                            is_input: false,
6830                                            is_textarea: false,
6831                                            is_button: false,
6832                                            button_icon: 0,
6833                                            element_id: String::new(),
6834                                            onclick: String::new(),
6835                                            form_action: String::new(),
6836                                            form_method: String::new(),
6837                                            width: actual_w,
6838                                            x_offset: layout.dimensions.content.x + if line_index == 0 { first_letter_x_shift } else { 0 }
6839                                                + super::text_align::line_start_offset(
6840                                                    // ::first-letter は 1 文字目を別要素で描くので揃えない(従来どおり左)。
6841                                                    if first_letter_x_shift != 0 { "left" } else { &node_text_align },
6842                                                    node_is_rtl,
6843                                                    available_w,
6844                                                    if line_index == 0 { text_indent_px } else { 0 },
6845                                                    actual_w,
6846                                                ),
6847                                            y_offset: line_y + half_lead,
6848                                            height: line_height - 2 * half_lead,
6849                                            border_radius: (0, 0, 0, 0),
6850                                            is_li: parent_tag == "li" && line_index == 0,
6851                                            li_num: if parent_tag == "li" && line_index == 0 {
6852                                                if let Some((true, count)) = list_state {
6853                                                    Some(count)
6854                                                } else {
6855                                                    None
6856                                                }
6857                                            } else {
6858                                                None
6859                                            },
6860                                            list_style_type: extract_list_style(styled),
6861                                            list_style_inside: extract_list_style_inside(styled),
6862                                            list_style_image: extract_list_style_image(styled),
6863                                            is_blockquote: false,
6864                                            z_index: self.inherited_paint_z,
6865                                            paint_depth: self.inherited_paint_depth,
6866                                            is_positioned: self.inherited_positioned,
6867                                            node_idx: styled.node.node_idx,
6868                                            ..Default::default()
6869                                        });
6870
6871                                        if is_actual_link {
6872                                            self.links.push(HyperlinkArea {
6873                                                href: link_href.clone(),
6874                                                // 行揃えでずらした行に合わせる(直前に積んだ行の要素の位置)。
6875
6876                                                x0: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x),
6877                                                y0: line_y,
6878                                                x1: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x) + actual_w,
6879                                                y1: line_y + line_height,
6880                                            });
6881                                        }
6882
6883                                        line_index += 1;
6884                                        if let Some(max) = line_clamp_max {
6885                                            if line_index >= max as i32 {
6886                                                break;
6887                                            }
6888                                        }
6889                                        current_line = next_line;
6890                                        // 折り返した位置の空白は次の行頭に持ち越さない
6891                                        // (CSS: 行頭の空白は取り除く。2026-09-26)。
6892                                        if c == ' ' && current_line.is_empty() {
6893                                            current_line_w = next_line_w;
6894                                        } else {
6895                                            current_line.push(c);
6896                                            current_line_w = next_line_w + advance;
6897                                        }
6898
6899                                        prev_char = Some(c);
6900                                        prev_advance = advance;
6901                                        continue;
6902                                    }
6903
6904                                    current_line.push(c);
6905                                    current_line_w += advance;
6906                                    prev_char = Some(c);
6907                                    prev_advance = advance;
6908                                }
6909
6910                                if !current_line.is_empty() {
6911                                    let line_y =
6912                                        layout.dimensions.content.y + line_index * line_height;
6913                                    self.elements.push(RenderElement {
6914                                        text: current_line.clone(),
6915                                        font_family: final_font_family.clone(),
6916                                        font_size: final_size,
6917                                        letter_spacing: final_ls,
6918                                        word_spacing: final_ws,
6919                                        text_emphasis_style: final_emphasis_style.clone(),
6920                                        text_emphasis_color: final_emphasis_color,
6921                                        color: final_color,
6922                                        bg_color: final_bg,
6923                                        hover_bg_color: extract_hover_color_alt(
6924                                            styled,
6925                                            "background-color",
6926                                            "background",
6927                                        ),
6928                                        hover_color: extract_hover_color(styled, "color"),
6929                                        hover_border_color: extract_hover_color(
6930                                            styled,
6931                                            "border-color",
6932                                        ),
6933                                        filter: styled.value("filter").unwrap_or_default(),
6934                                        mix_blend_mode: styled.value("mix-blend-mode").unwrap_or_default(),
6935                                        backdrop_filter: styled.value("backdrop-filter").unwrap_or_default(),
6936                                image_rendering: styled.value("image-rendering").unwrap_or_default(),
6937                                text_stroke_width: extract_text_stroke(styled).0,
6938                                text_stroke_color: extract_text_stroke(styled).1,
6939                                        marker_color: extract_marker_color(styled),
6940                                        marker_font_size: extract_marker_font_size(styled),
6941                                        marker_content: extract_marker_content(styled),
6942                                        focus_bg_color: extract_focus_color_alt(styled, "background-color", "background"),
6943                                        focus_color: extract_focus_color(styled, "color"),
6944                                        focus_border_color: extract_focus_color(styled, "border-color"),
6945                                        active_bg_color: extract_active_color_alt(styled, "background-color", "background"),
6946                                        active_color: extract_active_color(styled, "color"),
6947                                        active_border_color: extract_active_color(styled, "border-color"),
6948                                        border_color: None,
6949                                        border_style: super::BorderStyle::None,
6950                                        font_bold: final_bold,
6951                                        font_weight: weight_for(final_bold),
6952                                        font_italic: final_italic,
6953                                        underline: final_underline,
6954                                        line_through: final_line_through,
6955                                        overline: final_overline,
6956                                        decoration_color: final_decoration_color,
6957                                        decoration_style: final_decoration_style.clone(),
6958                                        decoration_thickness: final_decoration_thickness,
6959                                        decoration_underline_offset: final_decoration_underline_offset,
6960                                        is_video: false,
6961                                        video_src: String::new(),
6962                                        is_link: is_actual_link,
6963                                        pointer_events_none: current_pointer_events_none,
6964                                        href: link_href.clone(),
6965                                        is_hr: false,
6966                                        is_img: false,
6967                                canvas_ctx_id: None,
6968                                        img_alt: String::new(),
6969                                        is_input: false,
6970                                        is_textarea: false,
6971                                        is_button: false,
6972                                        button_icon: 0,
6973                                        element_id: String::new(),
6974                                        onclick: String::new(),
6975                                        form_action: String::new(),
6976                                        form_method: String::new(),
6977                                        width: current_line_w,
6978                                        x_offset: layout.dimensions.content.x + if line_index == 0 { first_letter_x_shift } else { 0 }
6979                                                + super::text_align::line_start_offset(
6980                                                    // ::first-letter は 1 文字目を別要素で描くので揃えない(従来どおり左)。
6981                                                    if first_letter_x_shift != 0 { "left" } else { &node_text_align },
6982                                                    node_is_rtl,
6983                                                    available_w,
6984                                                    if line_index == 0 { text_indent_px } else { 0 },
6985                                                    current_line_w,
6986                                                ),
6987                                        y_offset: line_y + half_lead,
6988                                        height: line_height - 2 * half_lead,
6989                                        border_radius: (0, 0, 0, 0),
6990                                        is_li: parent_tag == "li" && line_index == 0,
6991                                        li_num: if parent_tag == "li" && line_index == 0 {
6992                                            if let Some((true, count)) = list_state {
6993                                                Some(count)
6994                                            } else {
6995                                                None
6996                                            }
6997                                        } else {
6998                                            None
6999                                        },
7000                                        is_blockquote: false,
7001                                        z_index: self.inherited_paint_z,
7002                                        paint_depth: self.inherited_paint_depth,
7003                                        is_positioned: self.inherited_positioned,
7004                                        node_idx: styled.node.node_idx,
7005                                        ..Default::default()
7006                                    });
7007
7008                                    if is_actual_link {
7009                                        self.links.push(HyperlinkArea {
7010                                            href: link_href.clone(),
7011                                            // 行揃えでずらした行に合わせる(直前に積んだ行の要素の位置)。
7012
7013                                            x0: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x),
7014                                            y0: line_y,
7015                                            x1: self.elements.last().map(|e| e.x_offset).unwrap_or(layout.dimensions.content.x) + current_line_w,
7016                                            y1: line_y + line_height,
7017                                        });
7018                                    }
7019                                }
7020                            } // end else (non-nowrap)
7021                        }
7022                    }
7023                }
7024            }
7025            _ => {
7026                // 匿名ボックス等、要素を生成しない中間ノードでも子はツリー上 1 段深い。
7027                // ここで深さを進めないと、祖先より子孫が浅く見えて描画順が逆転する。
7028                let saved_paint_depth = self.inherited_paint_depth;
7029                self.inherited_paint_depth = self.inherited_paint_depth.saturating_add(1);
7030                for child in &layout.children {
7031                    self.flatten_layout(
7032                        child,
7033                        current_form_action,
7034                        current_form_method,
7035                        current_href,
7036                        current_font_bold,
7037                        current_font_italic,
7038                        current_underline,
7039                        current_line_through,
7040                        current_color,
7041                        current_font_size,
7042                        parent_id,
7043                        list_state,
7044                        parent_tag,
7045                        current_decoration_color,
7046                        current_decoration_style.clone(),
7047                        current_decoration_thickness,
7048                        current_decoration_underline_offset,
7049                        current_overline,
7050                        current_pointer_events_none,
7051                    );
7052                }
7053                self.inherited_paint_depth = saved_paint_depth;
7054            }
7055        }
7056    }
7057}
7058
7059fn extract_text_stroke(styled: &crate::os_lib::css::StyledNode) -> (i32, Option<u32>) {
7060    let val_str = styled
7061        .value("text-stroke")
7062        .or_else(|| styled.value("-webkit-text-stroke"))
7063        .unwrap_or_default();
7064    if val_str.is_empty() {
7065        let width_str = styled.value("-webkit-text-stroke-width").unwrap_or_default();
7066        let color_str = styled.value("-webkit-text-stroke-color").unwrap_or_default();
7067        let w = parse_px_val(&width_str);
7068        let c = parse_color(&color_str);
7069        return (w, c);
7070    }
7071    let mut width = 0;
7072    let mut color = None;
7073    for p in val_str.split_whitespace() {
7074        let w = parse_px_val(p);
7075        if w > 0 {
7076            width = w;
7077        } else if let Some(c) = parse_color(p) {
7078            color = Some(c);
7079        }
7080    }
7081    (width, color)
7082}
7083
7084/// 位置指定された疑似要素の箱(`layout::pseudo_box` の矩形と枠線の太さ)。`cb` は包含ブロック。
7085fn make_pseudo_box<'a>(
7086    ps: &'a crate::os_lib::css::StyledNode<'a>,
7087    cb: &crate::os_lib::layout::Rect,
7088) -> crate::os_lib::layout::LayoutBox<'a> {
7089    let (x, y, w, h) =
7090        crate::os_lib::layout::pseudo_box::abs_rect((cb.x, cb.y, cb.width, cb.height), &ps.specified_values);
7091    let b = crate::os_lib::layout::pseudo_box::border_px(&ps.specified_values)
7092        .min(w / 2)
7093        .min(h / 2)
7094        .max(0);
7095    crate::os_lib::layout::LayoutBox {
7096        trim_leading_space: false,
7097        dimensions: crate::os_lib::layout::Dimensions {
7098            content: crate::os_lib::layout::Rect {
7099                x: x + b,
7100                y: y + b,
7101                width: (w - 2 * b).max(0),
7102                height: (h - 2 * b).max(0),
7103            },
7104            border: crate::os_lib::layout::EdgeSizes { top: b, right: b, bottom: b, left: b },
7105            ..Default::default()
7106        },
7107        box_type: crate::os_lib::layout::BoxType::BlockNode(ps),
7108        children: alloc::vec::Vec::new(),
7109        subtree_boxes: 1,
7110    }
7111}
7112
7113/// レイアウト箱が `position:absolute` の要素か。
7114fn box_is_absolute(b: &crate::os_lib::layout::LayoutBox) -> bool {
7115    match &b.box_type {
7116        crate::os_lib::layout::BoxType::BlockNode(s)
7117        | crate::os_lib::layout::BoxType::InlineNode(s)
7118        | crate::os_lib::layout::BoxType::InlineBlockNode(s)
7119        | crate::os_lib::layout::BoxType::FlexNode(s)
7120        | crate::os_lib::layout::BoxType::GridNode(s) => {
7121            s.value("position").map(|p| p.trim() == "absolute").unwrap_or(false)
7122        }
7123        _ => false,
7124    }
7125}
7126
7127/// レイアウト箱の `visibility` が hidden/collapse か(スタイルを持たない無名の箱は None)。
7128fn box_visibility_hidden(b: &crate::os_lib::layout::LayoutBox) -> Option<bool> {
7129    match &b.box_type {
7130        crate::os_lib::layout::BoxType::BlockNode(s)
7131        | crate::os_lib::layout::BoxType::InlineNode(s)
7132        | crate::os_lib::layout::BoxType::InlineBlockNode(s)
7133        | crate::os_lib::layout::BoxType::FlexNode(s)
7134        | crate::os_lib::layout::BoxType::GridNode(s) => {
7135            Some(s.value("visibility").is_some_and(|v| matches!(v.trim(), "hidden" | "collapse")))
7136        }
7137        _ => None,
7138    }
7139}
7140
7141/// レイアウト箱の `pointer-events` の指定(none なら Some(true)、auto 等なら Some(false)、指定無しは None)。
7142fn box_pointer_events_none(b: &crate::os_lib::layout::LayoutBox) -> Option<bool> {
7143    match &b.box_type {
7144        crate::os_lib::layout::BoxType::BlockNode(s)
7145        | crate::os_lib::layout::BoxType::InlineNode(s)
7146        | crate::os_lib::layout::BoxType::InlineBlockNode(s)
7147        | crate::os_lib::layout::BoxType::FlexNode(s)
7148        | crate::os_lib::layout::BoxType::GridNode(s) => {
7149            s.value("pointer-events").map(|v| v.trim().eq_ignore_ascii_case("none"))
7150        }
7151        _ => None,
7152    }
7153}
7154
7155/// スタイル付きの `<svg>` 部分木を `inline_svg::SvgNode` にする(テキストは捨てる)。
7156/// `fill` は継承プロパティなので、親と同じ値は継承されたもの(表示属性より弱い)とみなし、
7157/// 親と違う値だけを CSS の指定(`css_fill`、表示属性より強い)として渡す。
7158fn inline_svg_node(styled: &crate::os_lib::css::StyledNode, parent_fill: Option<&str>) -> Option<super::inline_svg::SvgNode> {
7159    let crate::os_lib::dom::NodeType::Element { tag_name, attributes, .. } = &styled.node.node_type else {
7160        return None;
7161    };
7162    let own_fill = styled.specified_values.get("fill");
7163    Some(super::inline_svg::SvgNode {
7164        tag: tag_name.clone(),
7165        attrs: attributes.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
7166        css_fill: own_fill.filter(|f| Some(f.as_str()) != parent_fill).cloned(),
7167        children: styled.children.iter().filter_map(|c| inline_svg_node(c, own_fill.map(String::as_str))).collect(),
7168    })
7169}
7170
7171/// 表示される要素群(`display: none` の部分木は除く)から、使用されている `(font-family, weight)` と
7172/// テキスト・`::before`/`::after` の文字コード集合を収集する(TODO P3)。
7173pub(crate) fn collect_used_fonts_and_chars(
7174    node: &crate::os_lib::css::StyledNode,
7175    inherited_family: &str,
7176    inherited_weight: u16,
7177    out_fonts: &mut alloc::collections::BTreeSet<(String, u16)>,
7178    out_chars: &mut alloc::collections::BTreeSet<u32>,
7179) {
7180    if node
7181        .specified_values
7182        .get("display")
7183        .is_some_and(|v| v.trim().eq_ignore_ascii_case("none"))
7184    {
7185        return;
7186    }
7187    match &node.node.node_type {
7188        crate::os_lib::dom::NodeType::Text(t) => {
7189            for ch in t.chars() {
7190                if !ch.is_whitespace() {
7191                    out_chars.insert(ch as u32);
7192                }
7193            }
7194        }
7195        crate::os_lib::dom::NodeType::Element { tag_name, attributes, .. } => {
7196            if matches!(
7197                tag_name.as_str(),
7198                "head" | "script" | "style" | "meta" | "link" | "title" | "noscript" | "template"
7199            ) {
7200                return;
7201            }
7202            let fam_list = node
7203                .specified_values
7204                .get("font-family")
7205                .map(|s| s.as_str())
7206                .unwrap_or(inherited_family);
7207            let mut weight = node
7208                .specified_values
7209                .get("font-weight")
7210                .map(|s| crate::kernel::font_select::parse_font_weight(s))
7211                .unwrap_or(inherited_weight);
7212            if matches!(tag_name.as_str(), "b" | "strong" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "th")
7213                && !node.specified_values.contains_key("font-weight")
7214            {
7215                weight = weight.max(700);
7216            }
7217            let record_family = |fl: &str, w: u16, out: &mut alloc::collections::BTreeSet<(String, u16)>| {
7218                for raw in fl.split(',') {
7219                    let f = raw.trim().trim_matches('"').trim_matches('\'').trim().to_ascii_lowercase();
7220                    if f.is_empty() {
7221                        continue;
7222                    }
7223                    out.insert((f.clone(), w));
7224                    for cand in crate::kernel::font_select::generic_family_candidates(&f) {
7225                        out.insert((String::from(*cand), w));
7226                    }
7227                }
7228            };
7229            record_family(fam_list, weight, out_fonts);
7230
7231            for attr_key in ["value", "placeholder", "alt"] {
7232                if let Some(val) = attributes.get(attr_key) {
7233                    for ch in val.chars() {
7234                        if !ch.is_whitespace() {
7235                            out_chars.insert(ch as u32);
7236                        }
7237                    }
7238                }
7239            }
7240
7241            for (c_prop, f_prop, w_prop) in [
7242                ("__before_content", "__before_font-family", "__before_font-weight"),
7243                ("__after_content", "__after_font-family", "__after_font-weight"),
7244                ("content", "font-family", "font-weight"),
7245            ] {
7246                if let Some(content) = node.specified_values.get(c_prop) {
7247                    let trimmed = content.trim().trim_matches('"').trim_matches('\'');
7248                    if !trimmed.is_empty() && !matches!(trimmed, "none" | "normal") {
7249                        for ch in trimmed.chars() {
7250                            if !ch.is_whitespace() {
7251                                out_chars.insert(ch as u32);
7252                            }
7253                        }
7254                        let pf = node
7255                            .specified_values
7256                            .get(f_prop)
7257                            .map(|s| s.as_str())
7258                            .unwrap_or(fam_list);
7259                        let pw = node
7260                            .specified_values
7261                            .get(w_prop)
7262                            .map(|s| crate::kernel::font_select::parse_font_weight(s))
7263                            .unwrap_or(weight);
7264                        record_family(pf, pw, out_fonts);
7265                    }
7266                }
7267            }
7268
7269            for c in &node.children {
7270                collect_used_fonts_and_chars(c, fam_list, weight, out_fonts, out_chars);
7271            }
7272        }
7273    }
7274}