atmos/os_lib/web_engine/paint_order.rs
1//! 描画順(スタッキング順)の算出。
2//!
3//! ## 背景 — 実際に踏んだバグ
4//! 描画側は全要素を `z_index` でフラットにソートしていた。ところが実サイトの CSS には
5//! ```css
6//! section { position: relative; z-index: 5 }
7//! ```
8//! があり、`<section class="hero" id="home">` は z=5、その子孫
9//! (`.hero-overlay` / `.hero-content` / `.hero-title`)は `position: static` なので z=0 だった。
10//! フラットソートでは **セクションが自分の子孫より後に描かれ、自分の背景で
11//! 自分の中身を丸ごと消してしまう**。実測でも、ヒーローテキストは描画直後に
12//! 1655px 残っているのに `draw()` 終了時点で 0 になっていた。
13//!
14//! ## 仕様(CSS 2.1 Appendix E)
15//! スタッキングコンテキストを作る要素は、**自分の背景を先に**描き、子孫はその
16//! コンテキストの中で描かれる。**子孫が祖先の背景より前に描かれることは無い**。
17//!
18//! ## 実装方針
19//! 各要素の「実効 z」を `max(自分の z, 祖先の実効 z)` とする。
20//! 文書順では祖先が必ず子孫より先に現れるため、実効 z が同値なら安定ソートが
21//! 祖先→子孫の順を保つ。これで祖先の背景が子孫を塗り潰す事故は起きない。
22//! 子孫が自前でより大きい `z-index` を持つ場合はその値が勝ち、祖先より後=
23//! 手前に描かれる(これも仕様どおり)。
24//!
25//! グローバル状態にもハードウェアにも依存しない純粋ロジックのみで構成する。
26
27extern crate alloc;
28
29/// 実効 z の算出でおかしな入力を検出した場合のエラー。
30#[derive(Debug, PartialEq, Eq, Clone, Copy)]
31pub enum PaintOrderError {
32 /// 祖先チェーンの深さが上限を超えた(循環参照や壊れたツリーの疑い)。
33 DepthLimitExceeded(usize),
34}
35
36/// 祖先チェーンの深さ上限。これを超えるツリーは異常とみなす。
37pub const MAX_DEPTH: usize = 512;
38
39/// 要素の実効 z を求める。
40///
41/// - `own_z` … その要素自身の `z-index`(`position: static` なら 0)。
42/// - `ancestor_effective_z` … 親要素の**実効 z**(ルートなら `None`)。
43///
44/// 祖先より小さい z は祖先の値まで引き上げる。これにより
45/// 「子孫が祖先の背景より先に描かれる」ことが構造的に起こらなくなる。
46pub fn effective_z(own_z: i32, ancestor_effective_z: Option<i32>) -> i32 {
47 match ancestor_effective_z {
48 Some(a) if a > own_z => a,
49 _ => own_z,
50 }
51}
52
53/// CSS 2.1 Appendix E に基づくスタッキングコンテキスト内の描画段階(Stage)。
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
55#[repr(u8)]
56pub enum PaintStage {
57 /// 段階 2: スタッキングコンテキスト自身の背景・ボーダー
58 ContextBackground = 2,
59 /// 段階 3: 負の z-index 子スタッキングコンテキスト(奥から手前)
60 NegativeZ = 3,
61 /// 段階 4: 通常フローの非位置指定ブロックの背景・ボーダー
62 BlockBackground = 4,
63 /// 段階 5: 非位置指定の浮動(float)要素とその内容
64 Float = 5,
65 /// 段階 7: 通常フローのインライン内容(テキスト、画像、インライン置換要素)
66 InlineContent = 7,
67 /// 段階 8: z-index が 0 または auto の位置指定(positioned)要素
68 PositionedZero = 8,
69 /// 段階 9: 正の z-index 子スタッキングコンテキスト(手前から順)
70 PositiveZ = 9,
71 /// 段階 10: アウトライン(要素および子孫の outline。全要素の描画後に最前面へ描画)
72 Outline = 10,
73}
74
75/// 要素の属性から CSS 2.1 Appendix E の描画段階を分類する。
76pub fn classify_paint_stage(
77 effective_z: i32,
78 is_positioned: bool,
79 is_float: bool,
80 is_inline_content: bool,
81) -> PaintStage {
82 if effective_z < 0 {
83 PaintStage::NegativeZ
84 } else if effective_z > 0 {
85 PaintStage::PositiveZ
86 } else if is_positioned {
87 PaintStage::PositionedZero
88 } else if is_inline_content {
89 PaintStage::InlineContent
90 } else if is_float {
91 PaintStage::Float
92 } else {
93 PaintStage::BlockBackground
94 }
95}
96
97/// 拡張描画ソートキー。`(実効 z, 描画段階, ツリー深さ)` の昇順で並べる。
98pub fn paint_sort_key_ext(
99 effective_z: i32,
100 is_positioned: bool,
101 is_float: bool,
102 is_inline_content: bool,
103 depth: u32,
104) -> (i32, u8, u32) {
105 let stage = classify_paint_stage(effective_z, is_positioned, is_float, is_inline_content);
106 (effective_z, stage as u8, depth)
107}
108
109/// 描画ソートキー。`(実効 z, 位置指定層, ツリー深さ)` の昇順で並べる。
110///
111/// **CSS 2.1 Appendix E によるスタッキング順序準拠**:
112/// - `effective_z != 0`: そのまま z-index の昇順(負 z は最奥、正 z は最前面)。
113/// - `effective_z == 0`:
114/// - `!is_positioned`: 通常フロー(ブロック、背景、インライン)→ Stage 4 (BlockBackground)
115/// - `is_positioned`: position: fixed/absolute/relative/sticky 要素とその子孫 → Stage 8 (PositionedZero)
116///
117/// これにより、先行する position:fixed 等のバナーやヘッダーが、後続の通常ブロックの
118/// 背景(z=0, !is_positioned)によって塗り潰される事故を防ぐ。
119/// 深さを第 3 キーにすることで、同一層内では浅い祖先が先に描画される(不変条件 I-1)。
120pub fn paint_sort_key(effective_z: i32, is_positioned: bool, depth: u32) -> (i32, u8, u32) {
121 paint_sort_key_ext(effective_z, is_positioned, false, false, depth)
122}
123
124/// 祖先チェーン(ルート→親の順)から実効 z を求める。
125///
126/// 深さが `MAX_DEPTH` を超えた場合は黙って打ち切らず、
127/// エラーログを出して `Err` を返す。呼び出し側は安全側
128/// (その要素の own_z をそのまま使う)へフォールバックすること。
129pub fn effective_z_from_chain(own_z: i32, ancestor_zs: &[i32]) -> Result<i32, PaintOrderError> {
130 if ancestor_zs.len() > MAX_DEPTH {
131 crate::error!(
132 "[PAINT][ORDER] 祖先チェーンが深すぎます: {} (上限 {})。own_z をそのまま使います",
133 ancestor_zs.len(),
134 MAX_DEPTH
135 );
136 return Err(PaintOrderError::DepthLimitExceeded(ancestor_zs.len()));
137 }
138 let mut acc: Option<i32> = None;
139 for &z in ancestor_zs {
140 acc = Some(effective_z(z, acc));
141 }
142 Ok(effective_z(own_z, acc))
143}
144
145/// 入れ子のスタッキングコンテキストの 1 段(`(z, 位置指定層, 文書順, 深さ)`)。
146/// 要素の描画キーは「祖先のコンテキストの段の列 + 自分の段」。
147pub type StackStep = (i32, u8, u32, u32);
148
149/// 要素自身の段(拡張版)。Stage 4 (ブロック背景) と Stage 7 (インライン内容) を分離可能。
150pub fn stack_step_ext(
151 effective_z: i32,
152 is_positioned: bool,
153 is_float: bool,
154 is_inline_content: bool,
155 depth: u32,
156 seq: u32,
157) -> StackStep {
158 let (z, stage_u8, d) = paint_sort_key_ext(effective_z, is_positioned, is_float, is_inline_content, depth);
159 (z, stage_u8, seq, d)
160}
161
162/// 要素自身の段。`seq` はその要素を生んだ箱の文書順(箱が要素列へ積み始めた位置)で、
163/// 祖先の箱の `seq` は子孫の箱の `seq` 以下になる。同値(祖先が子孫より後に積まれた場合)は
164/// 深さの浅い方が先(I-1)。深さを第 1 にしていた平坦版と違い、別の部分木どうしは文書順で並ぶ。
165pub fn stack_step(effective_z: i32, is_positioned: bool, depth: u32, seq: u32) -> StackStep {
166 stack_step_ext(effective_z, is_positioned, false, false, depth, seq)
167}
168
169/// 2 要素の描画順の比較(`Less` が先=奥)。`path` は祖先のスタッキングコンテキストの段の列。
170///
171/// 【2026-10-18】CSS 2.1 Appendix E の入れ子。`z-index` はそれを含むスタッキングコンテキストの
172/// 中でだけ比べる。`#movie_player{position:relative;z-index:0}` の中の
173/// `.html5-video-container{z-index:10}` が、player の外の後続の操作部(z auto)より手前に
174/// 描かれていた(平坦な実効 z では 10 > 0)。段の列を辞書順で比べ、コンテキストを作る要素の
175/// 段は子孫の列の接頭辞になるので、その要素は自分の中身より必ず先(I-1)。
176pub fn paint_cmp(a_path: &[StackStep], a: StackStep, b_path: &[StackStep], b: StackStep) -> core::cmp::Ordering {
177 a_path
178 .iter()
179 .copied()
180 .chain(core::iter::once(a))
181 .cmp(b_path.iter().copied().chain(core::iter::once(b)))
182}