Skip to main content

atmos/os_lib/web_engine/
mod.rs

1//! HTML パーサ・レイアウトエンジン・レンダラ(ブラウザエンジン本体)。
2//!
3//! [`WebEngine`] が HTML 文字列を受け取り、パース → CSS カスケード → レイアウト →
4//! 描画までの一連のパイプラインを提供する。JavaScript 実行は [`crate::os_lib::ecma`] へ、
5//! ネットワーク取得は [`crate::kernel::net_stack`] へ委譲する。
6//!
7//! アーキテクチャ詳細(コンポーネント構成・タブモデル・座標規約・テーブルレイアウト等)は
8//! `spec/DESIGN.md` §3「ブラウザエンジン アーキテクチャ」を参照。
9//!
10//! 暴走ページ対策として [`MAX_RENDER_ELEMENTS`](要素数上限)と [`MAX_HTML_BYTES`]
11//! (HTML サイズ上限)で打ち切る。
12// web_engine.rs - HTML Parser & Vector Font HTML Renderer Engine for AtmOS
13#![allow(dead_code)]
14
15use alloc::string::String;
16use alloc::vec::Vec;
17use spin::Mutex;
18
19/// flatten 時に生成する RenderElement の上限。病的なページでのヒープ枯渇を防ぐ。
20/// 1 要素あたり数百バイト程度なので、2 万要素でも十数 MB に収まる。
21const MAX_RENDER_ELEMENTS: usize = 20000;
22/// パース対象 HTML の上限バイト数。これを超える分は切り捨てる。
23const MAX_HTML_BYTES: usize = 2 * 1024 * 1024;
24
25/// ブラウザ内蔵のホームページ(OS 同梱 of 静的ページ)。
26/// YouTubeへのリンクは、DNS解決フォールバックやYouTubeモック解除の修正に伴い、
27/// ダミーURLではなく公式のYouTubeアドレスに設定されています。
28pub const HOME_HTML: &str = r#"<html><title>AtmOS Browser</title><body style="background-color: #282a36; color: #f8f8f2;"><h1 style="color: #bd93f9;">AtmOS Browser</h1><p style="color: #f8f8f2;">アトモス(AtmOS)の内蔵ブラウザへようこそ。HTML/CSS パーサ・レイアウトエンジン・レンダラと JavaScript エンジンをすべて自前実装しています。</p><hr style="color: #44475a;"><h2 style="color: #8be9fd;">リンク</h2><div style="background-color: #1e1f29; color: #f8f8f2;"><p><a href="https://www.sugi-lab.net/">www.sugi-lab.net</a></p><p style="color: #6272a4;">Sugimura Lab の Web サイト。AtmOS の開発元です。研究・教育・各種プロジェクト of 情報を掲載しています。</p><p><a href="https://www.youtube.com/">YouTube を観る(ホーム)</a></p><p style="color: #6272a4;">YouTube の Web サイトを開きます。</p><p><a href="https://www.youtube.com/watch?v=aqz-KE-bpKQ">YouTube 動画再生テスト(Big Buck Bunny / H.264)</a></p><p style="color: #6272a4;">動画視聴ページを開き、H.264/AAC 自律デコーダで動画を再生します。</p></div><h2 style="color: #8be9fd;">検索</h2><p><a href="https://www.google.com/">Google で検索する</a></p><p style="color: #6272a4;">Google の検索トップページを開きます。「g キーワード」でも Google 検索できます。</p><p><a href="https://duckduckgo.com/">DuckDuckGo で検索する</a></p><p style="color: #6272a4;">上のアドレスバーにキーワードを入力しても、そのまま DuckDuckGo で検索できます。</p><hr style="color: #44475a;"><p style="font-size: 12; color: #6272a4;">AtmOS — bare-metal OS on Raspberry Pi 3B+ / ARM64 + Rust</p></body></html>"#;
29
30// ---------------------------------------------------------------------------
31// ディスクキャッシュ (SylFS /cache/browser/<host>/<path_hash>)
32// ---------------------------------------------------------------------------
33
34// URL を SylFS のキャッシュパスへ変換する
35mod cache;
36pub(crate) mod draw_helpers;
37pub(crate) mod helpers;
38mod image;
39mod layout;
40pub(crate) use layout::forget_flatten_memo_of_closed_groups;
41pub(crate) use image::forget_shared_images_of_group;
42mod render;
43pub(crate) mod anim_budget;
44pub(crate) use crate::os_lib::css::units as css_units;
45pub(crate) mod font_budget;
46pub(crate) mod cache_path;
47pub(crate) mod rel_path;
48pub(crate) mod sticky;
49pub(crate) mod fetch_limit;
50pub(crate) mod queue_batch;
51pub(crate) mod perf;
52pub(crate) mod font_queue;
53pub(crate) mod fq_owners;
54pub(crate) mod image_budget;
55pub(crate) mod flatten_memo_budget;
56pub(crate) mod decided_spans;
57pub(crate) mod alpha_blend;
58pub(crate) mod doc_title;
59pub(crate) mod backdrop;
60pub(crate) mod text_align;
61pub(crate) mod paint_order;
62pub(crate) mod button_paint;
63pub(crate) mod inline_svg;
64pub(crate) mod repaint_scope;
65pub(crate) mod paint_update;
66pub(crate) mod inline_style_cache;
67pub(crate) mod gradient_lut;
68pub(crate) mod blur_box;
69pub mod font_gamma;
70pub mod selection;
71pub mod selection_style;
72pub mod media_controls;
73pub mod vtt;
74pub mod omnibox;
75pub mod site_hooks;
76pub(crate) mod box_shadow;
77pub(crate) mod embed_map;
78pub(crate) mod iframe_preview;
79pub(crate) mod paint_cull;
80pub(crate) mod url_resolve;
81pub(crate) mod referrer;
82pub(crate) mod video_fit;
83pub(crate) mod frames;
84pub(crate) mod clip_path;
85pub(crate) use crate::os_lib::css::filters as css_filters;
86pub(crate) mod text_ellipsis;
87pub(crate) mod scrollbar;
88pub(crate) mod bilinear;
89mod video;
90pub mod dynamic_scripts;
91
92pub use css_filters::*;
93pub use clip_path::*;
94pub use text_ellipsis::*;
95pub use scrollbar::*;
96
97pub use cache::clear_browser_cache;
98pub use draw_helpers::{draw_border, draw_gradation};
99// 自己テスト(`css/selftest.rs`)から`line-height`/`text-indent`の`%`/`em`
100// 単位対応、`box-shadow`/`text-shadow`/`border-radius`の`rem`単位対応
101// (いずれも2026-07-17)を直接検証するための再エクスポート。
102pub(crate) use layout::{parse_line_height, parse_shadow_len_tok, resolve_border_radius, resolve_text_indent};
103pub use helpers::{hash_str, url_encode};
104pub use image::image_results_ready;
105pub use image::shared_image;
106pub use fetch_limit::set_draw_stage;
107
108/// 取得待ちのフォント件数。再描画の判定から使う。
109pub fn font_pending() -> usize {
110    font_queue::pending_len()
111}
112
113// Bring submodule items into scope for use within this module
114use cache::{cache_path_for, write_cache};
115use image::{enqueue_image, ImageFetchReq, IMAGE_QUEUE};
116use video::stop_video_playback;
117
118pub(crate) fn parse_url_scheme(url: &str) -> Option<(bool, alloc::string::String, alloc::string::String)> {
119    let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
120        (true, r)
121    } else if let Some(r) = url.strip_prefix("http://") {
122        (false, r)
123    } else {
124        return None;
125    };
126    if let Some(slash_idx) = rest.find('/') {
127        let (host, path) = rest.split_at(slash_idx);
128        Some((
129            is_https,
130            alloc::string::String::from(host),
131            alloc::string::String::from(path),
132        ))
133    } else {
134        Some((
135            is_https,
136            alloc::string::String::from(rest),
137            alloc::string::String::from("/"),
138        ))
139    }
140}
141
142fn parse_url(url: &str) -> Option<(alloc::string::String, alloc::string::String)> {
143    let (_, host, path) = parse_url_scheme(url)?;
144    Some((host, path))
145}
146
147/// 非印字キーの keycode を DOM の `KeyboardEvent.key` 風の名前に変換する。
148fn key_name_for(keycode: u8) -> &'static str {
149    match keycode {
150        0x1C => "Enter",
151        0x0E => "Backspace",
152        0x0F => "Tab",
153        0x01 => "Escape",
154        0x39 => " ", // Space
155        0x53 => "Delete",
156        0x48 => "ArrowUp",
157        0x50 => "ArrowDown",
158        0x4B => "ArrowLeft",
159        0x4D => "ArrowRight",
160        0x47 => "Home",
161        0x4F => "End",
162        _ => "Unidentified",
163    }
164}
165
166#[derive(Clone)]
167struct AsyncLoadRequest {
168    owner: u64, // 発行元エンジン(タブ)の一意 ID。結果は同じ owner だけが消費する
169    /// 発行元アプリのメモリの帳簿の組(TODO R2 (c)・R5)。ローダーは処理の間この組を借り、
170    /// そのアプリが止まったら要求と結果を捨てる。
171    group: u8,
172    is_https: bool,
173    host: String,
174    path: String,
175    method: String,       // "GET" or "POST"
176    body: Option<String>, // POST body (application/x-www-form-urlencoded)
177    /// 送る `Referer`(iframe の文書の読み込み。`referrer::referrer_for` で決めた値)。
178    referer: Option<String>,
179    status: u8,           // 0: 空, 1: 処理中, 2: 成功, 3: 失敗
180    result_body: Option<String>,
181    result_dom: Option<crate::os_lib::dom::Node>,
182    error_msg: Option<String>,
183}
184
185/// 全タブ共有の非同期ロードキュー。owner ID で各タブの結果を分離する。
186struct AsyncLoadState {
187    requests: Vec<AsyncLoadRequest>,
188    thread_active: bool,
189}
190
191// ---------------------------------------------------------------------------
192// 画像非同期ロードキュー
193// ---------------------------------------------------------------------------
194
195static SVG_BACK: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.5 16.5L6 10L12.5 3.5\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
196
197static SVG_HOME: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5L3.5 8V16.5C3.5 17 4 17.5 4.5 17.5H7.5V12.5H12.5V17.5H15.5C16 17.5 16.5 17 16.5 16.5V8L10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/></svg>";
198
199static SVG_SHIELD_SECURE: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5C13 3.5 16.5 3.5 16.5 3.5V8.5C16.5 13 13 16.5 10 17.5C7 16.5 3.5 13 3.5 8.5V3.5C3.5 3.5 7 3.5 10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/><path d=\"M7 10L9 12L13 8\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
200
201static SVG_SHIELD_WARN: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5C13 3.5 16.5 3.5 16.5 3.5V8.5C16.5 13 13 16.5 10 17.5C7 16.5 3.5 13 3.5 8.5V3.5C3.5 3.5 7 3.5 10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/><path d=\"M4.5 4.5L15.5 15.5\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
202
203static SVG_SAVE: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M16 18H4C3 18 2 17 2 16V4C2 3 3 2 4 2H13L18 7V16C18 17 17 18 16 18Z\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M14 18V11H6V18\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M6 2V6H12\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
204
205static SVG_LOAD: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M18 16C18 17 17 18 16 18H4C3 18 2 17 2 16V4C2 3 3 2 4 2H8L10 4H16C17 4 18 5 18 6V16Z\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M2 8H18\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
206
207static SVG_WRAP: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M3 5H17\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M3 10H13C15 10 16 11 16 13C16 15 15 16 13 16H11\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M13 14L11 16L13 18\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M3 15H6\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
208
209static ASYNC_LOAD: Mutex<AsyncLoadState> = Mutex::new(AsyncLoadState {
210    requests: Vec::new(),
211    thread_active: false,
212});
213static NEXT_ENGINE_ID: spin::Mutex<u64> = spin::Mutex::new(1);
214
215/// 止めたアプリ(組 `g`)の、ページの読み込みの要求・結果と画像の取得の要求、フォント・CSS・スクリプトの
216/// 背景取得の待ちを捨てる(TODO R2 (c)、2026-11-17 続報)。
217/// 戻り値は(捨てたページの要求・結果の数, 捨てた画像の要求の数, 捨てたフォント等の待ちの数)。
218///
219/// ローダーと画像のワーカーは組をまたいで使う共有のワーカーなので止めない。panic の回復からも呼ばれるので、
220/// 錠は `try_lock`(取れなければ何もしない。ワーカーが取り出すときに捨てる)。
221/// フォント・CSS・スクリプトの待ち行列(`font_queue`)は URL ごとに重複を省いている(`seen`)ので、
222/// 【2026-11-17】URL ごとに積んだアプリの組を持たせ(`fq_owners.rs`)、止めたアプリだけが積んだ URL を
223/// 待ち行列と `seen` の両方から外す(`seen` に残すと、同じページを開き直したときにその URL が二度と積まれない)。
224/// ほかのアプリも積んだ URL はそのまま取る。錠が取れなければ、次に錠を取った者が片付ける(その場合 0 件と数える)。
225pub fn forget_requests_of_group(g: u8) -> (usize, usize, usize) {
226    let mut pages = 0;
227    if let Some(mut lock) = ASYNC_LOAD.try_lock() {
228        let before = lock.requests.len();
229        lock.requests.retain(|r| r.group != g);
230        pages = before - lock.requests.len();
231    }
232    let images = image::forget_requests_of_group(g);
233    let fonts = font_queue::forget_group(g);
234    (pages, images, fonts)
235}
236
237/// タブ(`WebEngine`)を捨てたとき、そのタブが積んだページの読み込みの要求と画像の取得の待ちを捨てる(TODO R2 (d) ③、2026-11-18)。
238///
239/// 以前は組(アプリ)を閉じたときと、同じタブでページを移ったときにしか捨てておらず、1 つのタブだけを閉じた・止めたときは
240/// そのタブの画像を最後まで取っていた。取得中の画像は最後まで取る(結果は全部のタブで共有の置き場に入る。画像は小さい)。
241/// 2 つのタブが同じ画像を積んだ要求は持ち主を 0 にしてあり(`image::enqueue_image`)、ここでは捨てない。
242/// 錠は `try_lock`(panic の回復の途中で捨てられることもあるので待たない。取れなければ最後まで取る)。
243impl Drop for WebEngine {
244    fn drop(&mut self) {
245        let id = self.engine_id;
246        let mut pages = 0;
247        if let Some(mut lock) = ASYNC_LOAD.try_lock() {
248            let before = lock.requests.len();
249            lock.requests.retain(|r| r.owner != id);
250            pages = before - lock.requests.len();
251        }
252        let images = image::forget_requests_of_owner(id);
253        if pages + images != 0 {
254            crate::warn!("[WEB] 捨てたタブ(エンジン {})のページの読み込み {} 件・画像の取得の待ち {} 件を捨てた", id, pages, images);
255        }
256    }
257}
258
259fn async_load_thread_entry() {
260    loop {
261        let req_opt = {
262            let mut lock = ASYNC_LOAD.lock();
263            // 止めたアプリの要求と、取り込まれないままの結果を捨てる(TODO R2 (c))。
264            let before = lock.requests.len();
265            lock.requests.retain(|r| !crate::kernel::window_mgr::group_stopped(r.group));
266            if lock.requests.len() != before {
267                crate::warn!("[NET] BROWSER_LOADER: 止めたアプリの要求・結果を {} 件捨てた", before - lock.requests.len());
268            }
269            // 処理中(status 1)のリクエストを1件複製して処理する
270            lock.requests.iter().find(|r| r.status == 1).cloned()
271        };
272
273        let req = match req_opt {
274            Some(r) => r,
275            None => {
276                // 処理待ちが無くなったらスレッド終了
277                let mut lock = ASYNC_LOAD.lock();
278                if !lock.requests.iter().any(|r| r.status == 1) {
279                    lock.thread_active = false;
280                    drop(lock);
281                    // 【2026-08-05】メイン HTML の取得が終わったので、
282                    // 止めていたリソース取得を再開させる(`fetch_limit` 参照)。
283                    fetch_limit::set_main_load_in_flight(false);
284                    crate::kernel::scheduler::exit();
285                }
286                fetch_limit::set_main_load_in_flight(false);
287                continue;
288            }
289        };
290        // 【2026-08-05】メイン HTML の取得中はリソース取得を新たに始めない。
291        //
292        // フォント 4 + 画像 4 で最大 8 本の TLS 接続を張れており、
293        // この自作スタックは同時接続に弱い。CSS/JS も非同期化したときに
294        // **メイン HTML が読み込めなくなった**(`[NET][STATS] total=3`)。
295        // ページの他の何よりもメイン HTML が優先される
296        // (それが無ければ描くものが無い)。
297        fetch_limit::set_main_load_in_flight(true);
298        // 要求を出したアプリの組を借りる(この周の終わりで組 0 へ戻る)。そのアプリが止まると通信の待ちが失敗を返し、
299        // 結果は書き戻す先(同じ要求)がもう無いので捨てられる(TODO R2 (c))。
300        let _loan = crate::kernel::scheduler::borrow_mem_group(req.group);
301
302        {
303            // crate::warn!(
304            //     "BROWSER_LOADER: thread started. is_https={}, host={}, path={}",
305            //     req.is_https,
306            //     req.host,
307            //     req.path
308            // );
309
310            let mut current_is_https = req.is_https;
311            let mut current_host = req.host.clone();
312            let mut current_path = req.path.clone();
313
314            let is_post = req.method.eq_ignore_ascii_case("POST");
315            let post_body = req.body.clone().unwrap_or_default();
316
317            // --- POST は常にネットワーク(キャッシュしない) ---
318            // --- GET: キャッシュチェック(デコード失敗時はネットワーク取得にフォールスルー)---
319            // 参照元付きの要求は応答が参照元で変わり得る(YouTube の埋め込み)ので
320            // ページキャッシュを読み書きしない。
321            let use_cache = req.referer.is_none();
322            let res = if !is_post && use_cache {
323                if let Some(cached) = cache::read_cache_strict(&current_host, &current_path) {
324                    match alloc::string::String::from_utf8(cached) {
325                        Ok(s) => {
326                            crate::info!(
327                                "BROWSER_LOADER: cache hit. host={}, path={}",
328                                current_host,
329                                current_path
330                            );
331                            Some(Ok(s))
332                        }
333                        Err(_) => {
334                            // 壊れたキャッシュは削除してネットワーク取得
335                            crate::warn!("[NET] BROWSER_LOADER: cache decode error, fetching from network. host={}", current_host);
336                            let cp = cache_path_for(&current_host, &current_path);
337                            let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
338                            let _ = crate::kernel::fs::get_fs().delete_file(&cp);
339                            None
340                        }
341                    }
342                } else {
343                    None
344                }
345            } else {
346                None
347            };
348
349            let res = if let Some(r) = res {
350                r
351            } else {
352                // --- ネットワーク取得 ---
353                // リンクが up していなければ即エラー(ただし DuckDuckGo の場合はオフラインシミュレーションを起動)
354                if !crate::kernel::net::status().link_up {
355                    if let Some(html) = site_hooks::hooks().offline_page(&current_host, &current_path, current_is_https, is_post, &post_body) {
356                        Ok(html)
357                    } else {
358                        crate::warn!("[NET] BROWSER_LOADER: network link is down");
359                        Err(String::from("Network link is down. Check QEMU network settings or USB-Ethernet adapter."))
360                    }
361                } else {
362                    let stack = crate::kernel::net_stack::TcpIpStack::new();
363
364                    // POST の場合は1回だけ送信(リダイレクトは GET に変換)
365                    if is_post {
366                        crate::info!(
367                            "BROWSER_LOADER: POST {} host={}, path={}",
368                            if current_is_https { "HTTPS" } else { "HTTP" },
369                            current_host,
370                            current_path
371                        );
372                        match stack.web_post(
373                            current_is_https,
374                            &current_host,
375                            &current_path,
376                            "application/x-www-form-urlencoded",
377                            post_body.as_bytes(),
378                        ) {
379                            Ok(r) => {
380                                // 303 See Other は GET でリダイレクト
381                                if r.status_code == 303
382                                    || r.status_code == 301
383                                    || r.status_code == 302
384                                {
385                                    if let Some(loc) = r.headers.get("location") {
386                                        let loc_str = loc.as_str();
387                                        if let Some(no_proto) = loc_str.strip_prefix("https://") {
388                                            current_is_https = true;
389                                            if let Some(idx) = no_proto.find('/') {
390                                                let (h, p) = no_proto.split_at(idx);
391                                                current_host = String::from(h);
392                                                current_path = String::from(p);
393                                            } else {
394                                                current_host = String::from(no_proto);
395                                                current_path = String::from("/");
396                                            }
397                                        } else if let Some(no_proto) =
398                                            loc_str.strip_prefix("http://")
399                                        {
400                                            current_is_https = false;
401                                            if let Some(idx) = no_proto.find('/') {
402                                                let (h, p) = no_proto.split_at(idx);
403                                                current_host = String::from(h);
404                                                current_path = String::from(p);
405                                            } else {
406                                                current_host = String::from(no_proto);
407                                                current_path = String::from("/");
408                                            }
409                                        } else if loc_str.starts_with('/') {
410                                            current_path = String::from(loc_str);
411                                        }
412                                        // GET でリダイレクト先を取得
413                                        match stack.web_get(
414                                            current_is_https,
415                                            &current_host,
416                                            &current_path,
417                                        ) {
418                                            Ok(r2) => {
419                                                write_cache(
420                                                    &current_host,
421                                                    &current_path,
422                                                    r2.body.as_bytes(),
423                                                );
424                                                Ok(r2.body)
425                                            }
426                                            Err(e) => Err(String::from(e.message)),
427                                        }
428                                    } else {
429                                        Ok(r.body)
430                                    }
431                                } else {
432                                    Ok(r.body)
433                                }
434                            }
435                            Err(e) => Err(String::from(e.message)),
436                        }
437                    } else {
438                        let mut final_res = None;
439                        // 【2026-07-26】従来はネットワークエラーが1回起きた時点で
440                        // 即座に失敗確定にしていた。この自作TCP/TLSスタックは
441                        // 実測でパケット消失・タイムアウトが頻発しており
442                        // (詳細は spec/TODO.md)、メインHTMLの取得が1回失敗する
443                        // だけでページ全体が表示されない。外部CSS取得側
444                        // (`https_get_binary`) は既に最大3回の再試行を持つのに、
445                        // 最も重要なメインHTMLだけが再試行なしだった。
446                        // リダイレクト追従とは別枠で再試行回数を確保する。
447                        let mut fetch_retries = 2u32;
448                        for _ in 0..6 {
449                            // リダイレクト追従(最大3回)+ 取得失敗時の再試行
450                            match stack.web_get_with_referer(current_is_https, &current_host, &current_path, req.referer.as_deref()) {
451                                Ok(r) => {
452                                    let code = r.status_code;
453                                    if code == 301
454                                        || code == 302
455                                        || code == 303
456                                        || code == 307
457                                        || code == 308
458                                    {
459                                        if let Some(loc) = r.headers.get("location") {
460                                            crate::info!("[NET] BROWSER_LOADER: Redirect to {}", loc);
461                                            let loc_str = loc.as_str();
462                                            if let Some(no_proto) = loc_str.strip_prefix("http://")
463                                            {
464                                                current_is_https = false;
465                                                if let Some(idx) = no_proto.find('/') {
466                                                    let (h, p) = no_proto.split_at(idx);
467                                                    current_host = String::from(h);
468                                                    current_path = String::from(p);
469                                                } else {
470                                                    current_host = String::from(no_proto);
471                                                    current_path = String::from("/");
472                                                }
473                                                continue;
474                                            } else if let Some(no_proto) =
475                                                loc_str.strip_prefix("https://")
476                                            {
477                                                current_is_https = true;
478                                                if let Some(idx) = no_proto.find('/') {
479                                                    let (h, p) = no_proto.split_at(idx);
480                                                    current_host = String::from(h);
481                                                    current_path = String::from(p);
482                                                } else {
483                                                    current_host = String::from(no_proto);
484                                                    current_path = String::from("/");
485                                                }
486                                                continue;
487                                            } else if loc_str.starts_with('/') {
488                                                current_path = String::from(loc_str);
489                                                continue;
490                                            }
491                                        }
492                                    }
493                                    // キャッシュに保存
494                                    if use_cache {
495                                        write_cache(&current_host, &current_path, r.body.as_bytes());
496                                    }
497                                    final_res = Some(Ok(r.body));
498                                    break;
499                                }
500                                Err(e) => {
501                                    if fetch_retries > 0 {
502                                        fetch_retries -= 1;
503                                        crate::warn!(
504                                            "[NET] BROWSER_LOADER: fetch failed ({}), retrying ({} left) host={} path={}",
505                                            e.message,
506                                            fetch_retries,
507                                            current_host,
508                                            current_path
509                                        );
510                                        continue;
511                                    }
512                                    final_res = Some(Err(String::from(e.message)));
513                                    break;
514                                }
515                            }
516                        }
517                        final_res.unwrap_or_else(|| Err(String::from("Too many redirects")))
518                    } // end GET block
519                } // end link_up check
520            }; // end res
521
522            // crate::warn!("[NET][DIAG] async_load: res computed, about to lock ASYNC_LOAD");
523            // 【2026-11-18 TODO R2 (b) ②】HTML の解析は `ASYNC_LOAD` の錠の外でする(下)。20MB の HTML では解析に数秒かかり、
524            // その間アプリのスレッドが描画の頭の `ASYNC_LOAD.lock()` で待ち続けて、止める確かめを通れなかった。
525            let mut parse_later: Option<String> = None;
526            let mut lock = ASYNC_LOAD.lock();
527            // crate::warn!("[NET][DIAG] async_load: ASYNC_LOAD locked");
528            // owner が一致し、まだ処理中(status 1)のリクエストへ結果を書き戻す。
529            // (処理中に同じタブが再ロードした場合は古いリクエストが置換されているため、
530            //   status==1 のものだけを対象にすることで取り違えを防ぐ)
531            if let Some(current_req) = lock
532                .requests
533                .iter_mut()
534                .find(|r| r.owner == req.owner && r.status == 1)
535            {
536                match res {
537                    Ok(body) => {
538                        crate::info!("[NET] BROWSER_LOADER: load done. size={}", body.len());
539                        // DuckDuckGo の検索結果が含まれている場合は AtmOS 最適化 HTML に整形して爆速レンダリング
540                        let final_body = site_hooks::hooks().rewrite_response(&current_host, &current_path, current_is_https, body);
541                        // 処理中(status 1)のまま錠を外し、錠の外で解析してから書き戻す(下)。
542                        parse_later = Some(final_body);
543                    }
544                    Err(e) => {
545                        if let Some(fallback_html) = site_hooks::hooks().load_failed_page(&current_host, &current_path, current_is_https, &e) {
546                            let dom_tree = crate::os_lib::dom::parse_html(&fallback_html);
547                            current_req.status = 2; // 成功としてフォールバック
548                            current_req.result_body = Some(fallback_html);
549                            current_req.result_dom = Some(dom_tree);
550                        } else {
551                            crate::warn!("[NET] BROWSER_LOADER: load failed. err=[{}] len={}", e, e.len());
552                            current_req.status = 3; // 失敗
553                            current_req.error_msg = Some(e);
554                        }
555                    }
556                }
557            }
558            drop(lock);
559            if let Some(mut final_body) = parse_later {
560                // 【2026-11-18 TODO R5 (c)】アプリの側(`parse_and_layout`)と同じ大きさ(`MAX_HTML_BYTES`)で先に切る。
561                // 以前はここで本文を丸ごと解析しており、20MB のページでヒープ(805MB)を使い切っていた。
562                let full_len = final_body.len();
563                if full_len > MAX_HTML_BYTES {
564                    let mut cut = MAX_HTML_BYTES;
565                    while cut > 0 && !final_body.is_char_boundary(cut) {
566                        cut -= 1;
567                    }
568                    final_body.truncate(cut);
569                    final_body.shrink_to_fit();
570                    crate::warn!("[NET] BROWSER_LOADER: HTML が大きすぎるので {} → {} バイトで切って解析する", full_len, cut);
571                }
572                // 錠の外で解析する。背景のスレッドなので止める確かめは呼ばない。代わりに、要求が捨てられた
573                // (タブ・アプリを閉じた・止めた・同じタブで別のページへ移った)ら途中でやめる(錠は `try_lock`。塞がっていれば続ける)。
574                // 【2026-11-18 TODO R5 (c)】借りているアプリの組がメモリの上限に当たったときもやめる(解析の木を捨てて失敗を返す)。
575                let owner = req.owner;
576                let mut over_quota = false;
577                let gone = || {
578                    if crate::kernel::window_mgr::borrowed_group_should_stop() {
579                        over_quota = true;
580                        return true;
581                    }
582                    ASYNC_LOAD
583                        .try_lock()
584                        .is_some_and(|l| !l.requests.iter().any(|r| r.owner == owner && r.status == 1))
585                };
586                // XHTML(拡張子 .xht / .xhtml)は XML として解析する(HTML §1.8: XML 構文の文書は XML の解析器で読む)。
587                // 【2026-11-28】以前は HTML として解析し、`<style><![CDATA[ … ]]></style>` の CDATA が CSS に残って
588                // 最初の規則が捨てられていた(WPT の CSS 2.1 試験と共通の正解のページ `css/reference/*.xht` の多数)。
589                // XML として正しくない文書は従来どおり HTML として解析する。
590                let lower_path = current_path.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
591                let is_xhtml = lower_path.ends_with(".xht") || lower_path.ends_with(".xhtml");
592                let xml_tree = if is_xhtml {
593                    match crate::os_lib::xml_parser::parse_xml(final_body.strip_prefix('\u{FEFF}').unwrap_or(&final_body)) {
594                        Ok(t) => Some(t),
595                        Err(e) => {
596                            crate::warn!("[NET] BROWSER_LOADER: XHTML を XML として解析できず HTML として解析する: {} ({}:{})", e.message, e.line, e.column);
597                            None
598                        }
599                    }
600                } else {
601                    None
602                };
603                let (dom_tree, stats) = match xml_tree {
604                    Some(t) => (t, crate::os_lib::dom::ParseStats::default()),
605                    None => crate::os_lib::dom::parse_html_poll_counted(&final_body, gone),
606                };
607                if stats.node_limit_hit || stats.depth_capped != 0 {
608                    crate::warn!(
609                        "[NET] BROWSER_LOADER: HTML の解析を上限で抑えた: ノード {} 個(上限 {}、届いた={})・深さの上限で開かなかったタグ {} 個",
610                        stats.nodes,
611                        crate::os_lib::dom::MAX_DOM_NODES,
612                        stats.node_limit_hit,
613                        stats.depth_capped
614                    );
615                }
616                let mut lock = ASYNC_LOAD.lock();
617                if over_quota {
618                    // 作りかけの木と本文を錠の外で捨ててから、失敗(エラーのページ)として返す。
619                    let heap_mb = crate::kernel::allocator::get_heap_stats().0 >> 20;
620                    drop(lock);
621                    drop(dom_tree);
622                    drop(final_body);
623                    crate::warn!(
624                        "[NET] BROWSER_LOADER: メモリの上限に当たったので HTML の解析をやめた(ノード {} 個まで、ヒープ {}MB → {}MB)",
625                        stats.nodes,
626                        heap_mb,
627                        crate::kernel::allocator::get_heap_stats().0 >> 20
628                    );
629                    let mut lock = ASYNC_LOAD.lock();
630                    if let Some(current_req) = lock.requests.iter_mut().find(|r| r.owner == owner && r.status == 1) {
631                        current_req.status = 3; // 失敗(エラーのページを出す)
632                        current_req.error_msg = Some(String::from("the page is too large for the memory of this app"));
633                    }
634                } else if let Some(current_req) = lock.requests.iter_mut().find(|r| r.owner == owner && r.status == 1) {
635                    current_req.status = 2; // 成功
636                    current_req.result_body = Some(final_body);
637                    current_req.result_dom = Some(dom_tree);
638                } else {
639                    // 要求が捨てられていた(途中までの木は使わない)。大きい物は錠の外で解放する。
640                    drop(lock);
641                    drop(dom_tree);
642                    drop(final_body);
643                }
644            }
645        }
646    } // loop
647}
648
649/// CSS `border-style` の値。RenderElement は要素あたり最大 5 個(全体 + 4辺)保持するため、
650/// String(24バイト)ではなく 1 バイトの enum にしてメモリを節約する。
651#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
652pub enum BorderStyle {
653    #[default]
654    None,
655    Solid,
656    Dashed,
657    Dotted,
658    Double,
659}
660
661impl BorderStyle {
662    pub fn as_str(self) -> &'static str {
663        match self {
664            BorderStyle::None => "none",
665            BorderStyle::Solid => "solid",
666            BorderStyle::Dashed => "dashed",
667            BorderStyle::Dotted => "dotted",
668            BorderStyle::Double => "double",
669        }
670    }
671
672    pub fn parse(s: &str) -> Self {
673        match s.trim().to_ascii_lowercase().as_str() {
674            "solid" => BorderStyle::Solid,
675            "dashed" => BorderStyle::Dashed,
676            "dotted" => BorderStyle::Dotted,
677            "double" => BorderStyle::Double,
678            _ => BorderStyle::None,
679        }
680    }
681
682    pub fn is_none(self) -> bool {
683        matches!(self, BorderStyle::None)
684    }
685}
686
687/// CSS `list-style-type` の値。同じ理由で String の代わりに enum を使う。
688#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
689pub enum ListStyleType {
690    /// 未指定(コンテキストに応じたデフォルトマーカーを使う)
691    #[default]
692    Unset,
693    None,
694    Disc,
695    Circle,
696    Square,
697    Decimal,
698    UpperAlpha,
699    LowerAlpha,
700    UpperRoman,
701    LowerRoman,
702}
703
704impl ListStyleType {
705    pub fn parse(s: &str) -> Self {
706        match s.trim().to_ascii_lowercase().as_str() {
707            "none" => ListStyleType::None,
708            "disc" => ListStyleType::Disc,
709            "circle" => ListStyleType::Circle,
710            "square" => ListStyleType::Square,
711            "decimal" => ListStyleType::Decimal,
712            "upper-alpha" | "upper-latin" => ListStyleType::UpperAlpha,
713            "lower-alpha" | "lower-latin" => ListStyleType::LowerAlpha,
714            "upper-roman" => ListStyleType::UpperRoman,
715            "lower-roman" => ListStyleType::LowerRoman,
716            _ => ListStyleType::Unset,
717        }
718    }
719}
720
721pub use crate::os_lib::util::ordinal::{number_to_alpha, number_to_roman};
722
723/// CSS `background-size` の1軸ぶんの値。
724#[derive(Clone, Copy, PartialEq, Debug)]
725pub enum BgSizeVal {
726    Auto,
727    Px(i32),
728    Percent(f32),
729}
730
731/// CSS `background-size` のモード。
732#[derive(Clone, Copy, PartialEq, Debug, Default)]
733pub enum BgSizeMode {
734    /// 未指定時の既定挙動(このエンジンの互換維持のため box 全面に引き伸ばす)。
735    #[default]
736    Stretch,
737    Cover,
738    Contain,
739    Explicit(BgSizeVal, BgSizeVal),
740}
741
742/// CSS `background-repeat` の1軸ぶんのモード。
743#[derive(Clone, Copy, PartialEq, Debug, Default)]
744pub enum BgRepeatMode {
745    #[default]
746    Repeat,
747    NoRepeat,
748    /// タイルを等間隔に敷き詰め、余った分は境界を切らずタイル間の隙間として配分する。
749    Space,
750    /// タイルの寸法をこの軸に整数個ちょうど収まるよう拡縮する。
751    Round,
752}
753
754/// CSS `object-fit`(<img> 要素の内容フィッティング)。
755#[derive(Clone, Copy, PartialEq, Debug, Default)]
756pub enum ObjectFit {
757    /// 既定値。box 全面へ引き伸ばす(従来互換)。
758    #[default]
759    Fill,
760    Contain,
761    Cover,
762    /// スケーリングせず原寸のまま配置。
763    None,
764    /// contain と none の小さい方(画像を原寸より拡大しない)。
765    ScaleDown,
766}
767
768// 描画されるフラットなレイアウト要素
769#[derive(Debug, Clone, PartialEq)]
770pub struct GradientStop {
771    pub color: u32,
772    pub position: f32, // 0.0 ~ 1.0
773}
774
775#[derive(Debug, Clone, PartialEq)]
776pub struct LinearGradient {
777    pub angle_deg: f32,
778    pub stops: alloc::vec::Vec<GradientStop>,
779}
780
781#[derive(Debug, Clone, PartialEq)]
782pub enum RadialShape {
783    Circle,
784    Ellipse,
785}
786
787#[derive(Debug, Clone, PartialEq)]
788pub struct RadialGradient {
789    pub shape: RadialShape,
790    pub pos_x: f32, // 0.0 ~ 1.0
791    pub pos_y: f32, // 0.0 ~ 1.0
792    pub stops: alloc::vec::Vec<GradientStop>,
793}
794
795#[derive(Debug, Clone, PartialEq)]
796pub enum CssFilter {
797    Blur(i32), // radius in px
798    HueRotate(f32), // angle in degrees
799    DropShadow(i32, i32, i32, u32), // ox, oy, blur, color
800}
801
802#[derive(Debug, Clone, PartialEq)]
803pub struct RenderElement {
804    pub text: String,
805    pub font_size: u32,
806    pub color: u32,
807    pub bg_color: Option<u32>, // 背景色の追加
808    pub hover_bg_color: Option<u32>,
809    pub hover_color: Option<u32>,
810    pub hover_border_color: Option<u32>,
811    /// :focus 時の算出値差分(hover 系と同じ仕組み。実際の適用可否は
812    /// 描画側で focused_id と element_id の一致を見て選ぶ)。
813    pub focus_bg_color: Option<u32>,
814    pub focus_color: Option<u32>,
815    pub focus_border_color: Option<u32>,
816    /// :active 時の算出値差分(hover/focus 系と同じ仕組み。実際の適用可否は
817    /// 描画側で「ホバー中 かつ マウス左ボタン押下中」を見て選ぶ)。
818    pub active_bg_color: Option<u32>,
819    pub active_color: Option<u32>,
820    pub active_border_color: Option<u32>,
821    /// `::marker{color:...}` による箇条書き/番号マーカーの色上書き(無指定なら `color` を継承)。
822    pub marker_color: Option<u32>,
823    /// `::marker{font-size:...}` によるマーカーのフォントサイズ上書き(無指定なら周囲のサイズを継承)。
824    pub marker_font_size: Option<u32>,
825    /// `::marker{content:...}` によるマーカー文字列そのものの上書き(無指定なら
826    /// `list-style-type` から導出した既定の記号/番号を使う)。
827    pub marker_content: Option<alloc::string::String>,
828    pub border_color: Option<u32>,
829    pub border_style: BorderStyle,
830    pub font_bold: bool,    // font-weight: bold
831    /// `font-weight` の数値(100〜1000)。0 は未設定(`font_bold` から 700/400 とみなす)。
832    /// 【2026-10-03】Web フォントのウェイト選択に使う(500 等の中間ウェイト)。
833    pub font_weight: u16,
834    pub font_italic: bool,  // font-style: italic
835    pub underline: bool,    // text-decoration: underline
836    pub line_through: bool, // text-decoration: line-through
837    pub overline: bool,     // text-decoration: overline
838    /// text-decoration-color(未指定なら文字色を使う)。
839    pub decoration_color: Option<u32>,
840    /// text-decoration-style(solid/dotted/dashed/wavy/double、既定 solid)。
841    pub decoration_style: String,
842    /// text-decoration-thickness(px。`auto`/未指定は1px相当)。
843    pub decoration_thickness: i32,
844    /// text-underline-offset(px。underline のみに適用、0/負値も可。`auto`/未指定は0)。
845    pub decoration_underline_offset: i32,
846    /// `scroll-margin-top`(px。アンカー/フラグメントナビゲーションのスクロール位置から
847    /// この分だけ引く。固定ヘッダーの下にターゲットが隠れないようにする用途)。
848    pub scroll_margin_top: i32,
849    pub client_insets: Option<(i32, i32, i32, i32)>, // (top, right, bottom, left) in px
850    /// `caret-color`(テキスト入力のキャレット色。未指定なら IME 状態に応じた既定色を使う)。
851    pub caret_color: Option<u32>,
852    /// `accent-color`(checkbox/radio のチェック時の塗り色。未指定ならテーマ既定色を使う)。
853    pub accent_color: Option<u32>,
854    /// `::placeholder{color:...}`(合成プロパティ `x-placeholder-color` 経由)。
855    /// 未指定ならテーマの薄色(`editor_dim_fg`)を使う。
856    pub placeholder_color: Option<u32>,
857    /// `<input>`/`<textarea>` の `placeholder` 属性(値が空のときだけ薄色で表示する)。
858    pub placeholder: String,
859    pub is_video: bool,     // 動画要素フラグ
860    pub video_src: String,  // 動画ソースURL
861    /// `<video controls>`(ブラウザ既定の操作 UI を出す)。無ければクリックで既定の再生切替をしない。
862    pub video_has_controls: bool,
863    /// `<video autoplay>`(自動再生フラグ)
864    pub video_autoplay: bool,
865    /// `<video poster="...">`(ポスター画像URL)
866    pub video_poster: String,
867    /// `<video loop>`(ループ再生フラグ)
868    pub video_loop: bool,
869    pub is_iframe: bool,    // iframe 要素フラグ
870    pub iframe_src: String, // iframe の src URL
871    /// iframe の代替表示(埋め込み先 HTML の OGP。`iframe_preview` 参照)。OSM 埋め込みや取得失敗時は None。
872    pub iframe_preview: Option<iframe_preview::Preview>,
873    pub is_link: bool,
874    /// `pointer-events:none` — true ならこの要素はクリック/ホバー判定の対象から除外する
875    /// (リンク登録をスキップする簡略実装。子孫への `pointer-events:auto` による
876    /// 個別復元は非対応)。
877    pub pointer_events_none: bool,
878    pub href: String,
879    pub is_hr: bool,
880    pub is_img: bool,
881    /// `<img loading="lazy">`。これだけは画面に入ってから取得する(2026-09-26)。
882    pub img_lazy: bool,
883    pub img_alt: String,
884    /// `<canvas>` の 2D コンテキスト id(`os_lib/canvas2d` の registry)。
885    ///
886    /// JS が描いた内容はその registry の `Surface` にあり、ここに id が
887    /// 入っていれば描画時に要素の矩形へ転送する。`None` なら canvas 以外か、
888    /// まだ `getContext("2d")` が呼ばれていない。
889    pub canvas_ctx_id: Option<u32>,
890    /// `aspect-ratio`(CSS Box Sizing Level 4。幅と高さの比率 `width / height`)。
891    pub aspect_ratio: Option<f32>,
892    pub is_input: bool,
893    pub is_textarea: bool,
894    pub is_button: bool,
895    /// type=reset のボタンか。クリックで所属 form を初期値へ戻す(送信しない)。
896    pub is_reset: bool,
897    /// ボタンの背景を作者 CSS が指定したか(透明でも既定のボタン背景に戻さない。`button_paint`)。
898    pub btn_author_bg: bool,
899    /// 入力種別: 0=テキスト, 1=checkbox, 2=radio, 3=select。
900    /// checkbox/radio/select は is_input=false(テキスト編集対象ではない)として扱い、
901    /// クリックでトグル/循環し change イベントを発火する。
902    pub input_kind: u8,
903    /// radio のグループ名(name 属性)。同一グループ内で1つだけ checked になる。
904    pub radio_group: String,
905    /// radio/checkbox の value 属性(送信値・radio選択値)。
906    pub input_value: String,
907    /// select の選択肢 (value, ラベル) 一覧。input_kind==3 のときのみ有効。
908    pub select_options: alloc::vec::Vec<(String, String)>,
909    /// <label> 要素の関連付け先。for 属性の値、または内包 input の id。
910    /// 非空なら、この要素クリックで該当 input をトグル/フォーカスする。
911    pub label_for: String,
912    pub button_icon: u8, // 0: なし, 1: Save, 2: Load, 3: Wrap
913    pub element_id: String,
914    pub onclick: String,
915    pub form_action: String,
916    pub form_method: String,
917    pub width: i32,
918    pub x_offset: i32, // コンテンツ全体でのX相対座標 (px)
919    pub y_offset: i32, // コンテンツ全体でのY相対座標 (px)
920    pub height: i32,
921    pub border_radius: (i32, i32, i32, i32), // (tl, tr, br, bl)
922    pub is_li: bool,
923    pub li_num: Option<u32>,
924    pub list_style_type: ListStyleType,
925    /// list-style-position: inside なら true(マーカーを content 内で本文の直前に描画)。
926    pub list_style_inside: bool,
927    /// `list-style-image: url(...)`(`list-style` ショートハンド内の url() も含む)で
928    /// 解決された画像パス。空文字なら未指定(従来通り list_style_type のグリフを使う)。
929    pub list_style_image: String,
930    pub is_blockquote: bool,
931    pub border_top_width: i32,
932    pub border_right_width: i32,
933    pub border_bottom_width: i32,
934    pub border_left_width: i32,
935    pub border_top_color: Option<u32>,
936    pub border_right_color: Option<u32>,
937    pub border_bottom_color: Option<u32>,
938    pub border_left_color: Option<u32>,
939    pub border_top_style: BorderStyle,
940    pub border_right_style: BorderStyle,
941    pub border_bottom_style: BorderStyle,
942    pub border_left_style: BorderStyle,
943    pub padding_top: i32,
944    pub padding_right: i32,
945    pub padding_bottom: i32,
946    pub padding_left: i32,
947    /// `background-clip`/`background-origin`(`"border-box"`/`"padding-box"`/`"content-box"`)。
948    /// `background-clip: text` は非対応で `border-box` にフォールバック。
949    pub bg_clip: String,
950    pub bg_origin: String,
951    /// `background-attachment`(`"scroll"`(既定)/`"fixed"`)。`local` は `scroll` と同一視する。
952    pub bg_attachment: String,
953    pub bg_image: Option<String>,
954    /// `background-image: url(a), url(b)` のような複数レイヤー全体(`bg_image` は先頭と同じ値)。
955    /// 全レイヤーが同じ position/size/repeat を共有する簡略実装(レイヤーごとの個別指定は非対応)。
956    pub bg_images: Vec<String>,
957    /// `background-blend-mode`(`background-image` を `background-color` に対して
958    /// 合成する際のブレンドモード。`mix-blend-mode` と同じ `blend_pixel` を再利用する)。
959    /// 空文字列/`"normal"` は通常のアルファ合成。
960    pub background_blend_mode: String,
961    /// 複数レイヤー(`bg_images.len() > 1`)向けの、レイヤーごとの
962    /// (size, repeat_x, repeat_y, pos_x, pos_y)。単一レイヤーの場合は空(`bg_size`/
963    /// `bg_repeat_*`/`bg_pos_*` をそのまま使う)。
964    pub bg_layers: alloc::vec::Vec<(BgSizeMode, BgRepeatMode, BgRepeatMode, f32, f32)>,
965    // --- New CSS feature fields ---
966    pub pos_top: Option<i32>,
967    pub pos_left: Option<i32>,
968    pub pos_right: Option<i32>,
969    pub pos_bottom: Option<i32>,
970    pub z_index: i32,
971    /// DOM ツリー上の深さ。描画ソートの第 2 キー。
972    /// 要素列は祖先が先に積まれるとは限らないため、同一 z 内で祖先(浅い方)を
973    /// 先に描くにはこれが要る(`spec/paint_order.md` の不変条件 I-1)。
974    pub paint_depth: u32,
975    pub is_fixed: bool,
976    /// `position: relative | absolute | fixed | sticky` を持つ要素、またはその子孫であるか否か。
977    /// CSS 2.1 Appendix E に基づき、z-index: auto/0 の位置指定要素を通常フローの
978    /// ブロック/インライン要素より手前に描画するために使う。
979    pub is_positioned: bool,
980    pub overflow_hidden: bool,
981    /// 切り取り矩形(clip_x0..clip_y1)の角丸半径。0 は角丸なし(2026-10-03)。
982    pub clip_radius: i32,
983    pub clip_x0: i32,
984    pub clip_y0: i32,
985    pub clip_x1: i32,
986    pub clip_y1: i32,
987    /// box-shadow: カンマ区切りの複数シャドウに対応(各要素は (offset_x, offset_y, blur, color, is_inset))。
988    /// 空 Vec = 未指定。CSSの重なり順(先頭が最前面)どおり Vec の先頭から順に並ぶ。
989    pub box_shadow: alloc::vec::Vec<(i32, i32, i32, u32, bool)>,
990    pub white_space_nowrap: bool,
991    pub text_overflow_ellipsis: bool,
992    /// `direction:rtl` かどうか。`text-overflow:ellipsis` の省略記号を先頭側に出し、
993    /// 末尾ではなく先頭側の文字を切り詰める(CSS仕様どおりの挙動)ために使う。
994    pub text_overflow_rtl: bool,
995    pub linear_gradient: Option<LinearGradient>,
996    pub radial_gradient: Option<RadialGradient>,
997    /// `conic-gradient(c1, c2, ...)` の全カラーストップ(12時方向から時計回り、等間隔配置)。
998    /// 以前は先頭2色のみを保持する `(u32, u32)` で、3色目以降が丸ごと失われるバグがあった。
999    pub conic_gradient: Option<alloc::vec::Vec<GradientStop>>,
1000    /// (全カラーストップ, cycle_px, is_vertical)。以前は先頭2色固定の `(u32,u32,i32,bool)`
1001    /// で3色目以降が失われていた。周期内で全色を均等割りして補間する。
1002    pub repeating_linear_gradient: Option<(alloc::vec::Vec<u32>, i32, bool)>,
1003    /// (全カラーストップ, cycle_px)。以前は先頭2色固定の `(u32,u32,i32)` で
1004    /// 3色目以降が失われていた。
1005    pub repeating_radial_gradient: Option<(alloc::vec::Vec<u32>, i32)>,
1006    pub opacity: u8,                               // 0=transparent, 255=opaque
1007    pub visibility_hidden: bool,
1008    /// `visibility` を(その要素を生んだ箱の値で)決め終えたか。平坦化の後処理用。
1009    pub visibility_decided: bool,
1010    /// `pointer_events_none` を(その要素を生んだ箱の値で)決め終えたか。平坦化の後処理用。
1011    pub pointer_events_decided: bool,
1012    /// 祖先のスタッキングコンテキストの段の列(`paint_order::paint_cmp`)。
1013    pub stack_path: Vec<paint_order::StackStep>,
1014    /// この要素を生んだ箱の文書順(描画順の比較用)。
1015    pub paint_seq: u32,
1016    /// `stack_path`/`paint_seq` を決め終えたか(平坦化の後処理用)。
1017    pub stack_decided: bool,
1018    /// text-shadow: カンマ区切りの複数シャドウに対応(各要素は (offset_x, offset_y, blur, color))。
1019    /// 空 Vec = 未指定。CSSの重なり順(先頭が最前面)どおり Vec の先頭から順に並ぶ。
1020    pub text_shadow: alloc::vec::Vec<(i32, i32, i32, u32)>,
1021    /// ::before / ::after content string (empty = no pseudo element)
1022    pub before_content: String,
1023    pub after_content: String,
1024    /// `::before { font-family: "Font Awesome 6 Free"; }` 等、疑似要素専用の
1025    /// `font-family`(空 = 指定なし = 通常のグローバルフォントで描画)。
1026    /// FontAwesome等のアイコンフォントは複数ファミリーが同じprivate-use-area
1027    /// コードポイントに異なるグリフを割り当てるため、要素の`content`が
1028    /// アイコン専用(`el.text`が空でicon用の`before_content`のみ)の場合に限り、
1029    /// このファミリー名で登録済みカスタムフォントを優先的に探して描画する。
1030    /// 【2026-08-03】要素自身の `font-family`(カンマ区切りのまま保持)。
1031    ///
1032    /// `@font-face` で登録した Web フォントを字形へ反映するには、
1033    /// 描画時にどの family を使うかが要る。従来は `::before` 用の
1034    /// `before_font_family` しか持っておらず、**本文の family がどこにも
1035    /// 渡っていなかった**ため、フォントを取得・登録しても反映されなかった。
1036    pub font_family: String,
1037    pub before_font_family: String,
1038    /// CSS transform: translate(x,y) / scale(sx,sy) / rotate(deg) の簡易表現
1039    /// 描画時に足す translate(px)。レイアウトが既に箱と子孫をずらした分
1040    /// (`layout_tx`/`layout_ty`)は**含まない**残り。
1041    pub transform_tx: i32, // translateX px
1042    pub transform_ty: i32,         // translateY px
1043    /// レイアウト(`layout::box_translate`)が既に適用した translate(px)。
1044    /// 【2026-10-09】描画側もこれを丸ごと足しており、translate が二重に効いていた
1045    /// (`translateY(100px)` の箱が 200px 下に出た。index.htm のパララックスで
1046    /// ヒーローの写真が下の節に透けた)。アニメーションの再ペイント経路が
1047    /// 新しい transform から差し引くために保持する。
1048    pub layout_tx: i32,
1049    pub layout_ty: i32,
1050    pub transform_scale_x: f32,    // X軸 scale factor (1.0 = no scale)。scale()/scaleX() で設定
1051    pub transform_scale_y: f32,    // Y軸 scale factor (1.0 = no scale)。scale()/scaleY() で設定
1052    pub transform_rotate_deg: f32, // rotate degrees
1053    /// transform: skewX(deg) せん断変換のX軸角度(度。既定 0.0 = 変換なし)。
1054    pub transform_skew_x: f32,
1055    /// transform: skewY(deg) せん断変換のY軸角度(度。既定 0.0 = 変換なし)。
1056    pub transform_skew_y: f32,
1057    /// transform-origin(scale の基準点。0.0-1.0 の割合、既定は (0.5,0.5)=中央)。
1058    pub transform_origin_x: f32,
1059    pub transform_origin_y: f32,
1060    /// letter-spacing(文字間に加える px、負も可)。0 = normal。
1061    pub letter_spacing: i32,
1062    /// word-spacing(半角スペース1文字ごとに加える px、負も可)。0 = normal。
1063    pub word_spacing: i32,
1064    /// text-emphasis-style: 各文字の上に付す強調記号("dot"/"circle"/"double-circle"/
1065    /// "triangle"/"sesame"、またはクォート付きカスタム1文字、"none"/空文字列 = 無し)。
1066    /// `text-emphasis-position` は非対応で常に文字の上(横書き前提)に描く。
1067    pub text_emphasis_style: String,
1068    /// text-emphasis-color(未指定なら文字色 `color` を使う)。
1069    pub text_emphasis_color: Option<u32>,
1070    /// CSS `cursor`。`"text"` のみ実際のマウスカーソル形状(I-beam)へ反映する。
1071    /// それ以外の非対応キーワード(`pointer`/`wait`/`help` 等)は既定の矢印にフォールバックする。
1072    pub cursor_style: String,
1073    /// このエレメントが所属するスクロールコンテナの element_id(空 = ページスクロール)。
1074    pub scroll_container_id: String,
1075    /// CSS clip-path value (e.g. "circle(50%)", empty = no clip)
1076    pub clip_path: String,
1077    /// position: sticky
1078    pub is_sticky: bool,
1079    /// sticky の吸着オフセット(top/bottom)。両方指定時は top を優先する。
1080    pub sticky_top: Option<i32>,
1081    pub sticky_bottom: Option<i32>,
1082    /// sticky の可動範囲下限(吸着後にこれ以上下げない、含む要素の下端 - height)。
1083    /// 未設定時(属するコンテナが無い等)は i32::MAX として無制限に振る舞う。
1084    pub sticky_bound_max_y: i32,
1085    /// background-size(既定は Stretch = box 全面に引き伸ばし、従来互換)。
1086    pub bg_size: BgSizeMode,
1087    /// background-repeat: x/y 各軸のモード(Stretch モードでは効果なし)。
1088    pub bg_repeat_x: BgRepeatMode,
1089    pub bg_repeat_y: BgRepeatMode,
1090    /// background-position のアンカー位置(0.0=左/上, 1.0=右/下, 0.5=中央)。
1091    pub bg_pos_x: f32,
1092    pub bg_pos_y: f32,
1093    /// outline(レイアウトに影響しない装飾線。border-box の外側に描画)。
1094    pub outline_color: Option<u32>,
1095    pub outline_width: i32,
1096    /// outline-offset(border-box からの追加オフセット px)。
1097    pub outline_offset: i32,
1098    /// outline-style("solid"/"dashed"/"dotted"、既定 "solid")。
1099    pub outline_style: String,
1100    /// <img> 要素の object-fit / object-position。
1101    pub object_fit: ObjectFit,
1102    /// 既定は (0.5, 0.5)(中央)。background-position とは既定値が異なる点に注意。
1103    pub object_pos_x: f32,
1104    pub object_pos_y: f32,
1105    /// CSS `filter`(生の宣言値、例 "grayscale(1) brightness(1.2)")。
1106    /// <img> のピクセル描画時にのみ適用する簡略実装(grayscale/brightness/invert/sepia/contrast/saturate のみ対応)。
1107    pub filter: String,
1108    /// CSS `mix-blend-mode`(生の宣言値)。単色背景の塗り(クリップ無し・不透明・角丸無しの
1109    /// 最も単純な経路)にのみ適用する簡略実装。multiply/screen/darken/lighten/difference のみ対応。
1110    pub mix_blend_mode: String,
1111    /// CSS `backdrop-filter`(生の宣言値)。
1112    pub backdrop_filter: String,
1113    /// CSS `image-rendering`("pixelated", "crisp-edges", "smooth" 等)。
1114    pub image_rendering: String,
1115    /// CSS `text-stroke` / `-webkit-text-stroke`(幅と色)。
1116    pub text_stroke_width: i32,
1117    pub text_stroke_color: Option<u32>,
1118    /// `-webkit-line-clamp`(複数行テキストの末尾を `...` で省略表示する行数上限。
1119    /// 0 = 無制限。`display: -webkit-box` かつ `-webkit-box-orient: vertical` と
1120    /// 併用されるが、この実装では値が 0 でなければ常に有効にする簡略実装)。
1121    pub line_clamp: i32,
1122    pub node_idx: Option<usize>,
1123    /// モーダルダイアログ(<dialog.showModal()> 等)か否か。
1124    pub is_modal: bool,
1125    /// `::backdrop` の背景色(RGBA)。
1126    pub backdrop_color: Option<u32>,
1127}
1128
1129impl RenderElement {
1130    /// 描画・計測に使うウェイト(`font_weight` が未設定なら太字フラグから)。
1131    pub fn weight(&self) -> u16 {
1132        if self.font_weight != 0 {
1133            self.font_weight
1134        } else if self.font_bold {
1135            700
1136        } else {
1137            400
1138        }
1139    }
1140
1141    /// CSS 2.1 Appendix E に基づくインライン内容(テキスト、画像、置換要素等)か否か。
1142    /// ブロック背景(Stage 4)とインライン内容(Stage 7)の描画順分離に使用する。
1143    pub fn is_inline_content(&self) -> bool {
1144        !self.text.is_empty()
1145            || self.is_img
1146            || self.is_video
1147            || self.is_iframe
1148            || self.is_input
1149            || self.is_textarea
1150            || self.is_button
1151            || self.is_hr
1152            || self.button_icon != 0
1153            || !self.before_content.is_empty()
1154            || !self.after_content.is_empty()
1155            || self.is_li
1156            || self.canvas_ctx_id.is_some()
1157    }
1158}
1159
1160impl Default for RenderElement {
1161    fn default() -> Self {
1162        RenderElement {
1163            node_idx: None,
1164            text: String::new(),
1165            font_size: 0,
1166            color: 0,
1167            bg_color: None,
1168            hover_bg_color: None,
1169            hover_color: None,
1170            hover_border_color: None,
1171            focus_bg_color: None,
1172            focus_color: None,
1173            focus_border_color: None,
1174            active_bg_color: None,
1175            active_color: None,
1176            active_border_color: None,
1177            marker_color: None,
1178            marker_font_size: None,
1179            marker_content: None,
1180            border_color: None,
1181            client_insets: None,
1182            border_style: BorderStyle::None,
1183            font_bold: false,
1184            font_weight: 0,
1185            font_italic: false,
1186            underline: false,
1187            line_through: false,
1188            overline: false,
1189            decoration_color: None,
1190            decoration_style: String::new(),
1191            decoration_thickness: 1,
1192            decoration_underline_offset: 0,
1193            scroll_margin_top: 0,
1194            caret_color: None,
1195            accent_color: None,
1196            placeholder_color: None,
1197            placeholder: String::new(),
1198            is_video: false,
1199            video_src: String::new(),
1200            video_has_controls: false,
1201            video_autoplay: false,
1202            video_poster: String::new(),
1203            video_loop: false,
1204            is_iframe: false,
1205            iframe_src: String::new(),
1206            iframe_preview: None,
1207            is_link: false,
1208            pointer_events_none: false,
1209            href: String::new(),
1210            is_hr: false,
1211            is_img: false,
1212            img_lazy: false,
1213            canvas_ctx_id: None,
1214            img_alt: String::new(),
1215            aspect_ratio: None,
1216            is_input: false,
1217            is_textarea: false,
1218            is_button: false,
1219            is_reset: false,
1220            btn_author_bg: false,
1221            input_kind: 0,
1222            radio_group: String::new(),
1223            input_value: String::new(),
1224            select_options: alloc::vec::Vec::new(),
1225            label_for: String::new(),
1226            button_icon: 0,
1227            element_id: String::new(),
1228            onclick: String::new(),
1229            form_action: String::new(),
1230            form_method: String::new(),
1231            width: 0,
1232            x_offset: 0,
1233            y_offset: 0,
1234            height: 0,
1235            border_radius: (0, 0, 0, 0),
1236            is_li: false,
1237            li_num: None,
1238            list_style_type: ListStyleType::Unset,
1239            list_style_inside: false,
1240            list_style_image: String::new(),
1241            is_blockquote: false,
1242            border_top_width: 0,
1243            border_right_width: 0,
1244            border_bottom_width: 0,
1245            border_left_width: 0,
1246            border_top_color: None,
1247            border_right_color: None,
1248            border_bottom_color: None,
1249            border_left_color: None,
1250            border_top_style: BorderStyle::None,
1251            border_right_style: BorderStyle::None,
1252            border_bottom_style: BorderStyle::None,
1253            border_left_style: BorderStyle::None,
1254            padding_top: 0,
1255            padding_right: 0,
1256            padding_bottom: 0,
1257            padding_left: 0,
1258            bg_clip: String::from("border-box"),
1259            bg_origin: String::from("padding-box"),
1260            bg_attachment: String::from("scroll"),
1261            bg_image: None,
1262            bg_images: Vec::new(),
1263            background_blend_mode: String::new(),
1264            bg_layers: alloc::vec::Vec::new(),
1265            pos_top: None,
1266            pos_left: None,
1267            pos_right: None,
1268            pos_bottom: None,
1269            z_index: 0,
1270            paint_depth: 0,
1271            is_fixed: false,
1272            is_positioned: false,
1273            overflow_hidden: false,
1274            clip_radius: 0,
1275            clip_x0: 0,
1276            clip_y0: 0,
1277            clip_x1: i32::MAX,
1278            clip_y1: i32::MAX,
1279            box_shadow: alloc::vec::Vec::new(),
1280            white_space_nowrap: false,
1281            text_overflow_ellipsis: false,
1282            text_overflow_rtl: false,
1283            linear_gradient: None,
1284            radial_gradient: None,
1285            conic_gradient: None,
1286            repeating_linear_gradient: None,
1287            repeating_radial_gradient: None,
1288            opacity: 255,
1289            visibility_hidden: false,
1290            visibility_decided: false,
1291            pointer_events_decided: false,
1292            stack_path: Vec::new(),
1293            paint_seq: 0,
1294            stack_decided: false,
1295            text_shadow: alloc::vec::Vec::new(),
1296            before_content: String::new(),
1297            after_content: String::new(),
1298            font_family: String::new(),
1299            before_font_family: String::new(),
1300            transform_tx: 0,
1301            transform_ty: 0,
1302            layout_tx: 0,
1303            layout_ty: 0,
1304            transform_scale_x: 1.0,
1305            transform_scale_y: 1.0,
1306            transform_rotate_deg: 0.0,
1307            transform_skew_x: 0.0,
1308            transform_skew_y: 0.0,
1309            transform_origin_x: 0.5,
1310            transform_origin_y: 0.5,
1311            letter_spacing: 0,
1312            word_spacing: 0,
1313            text_emphasis_style: String::new(),
1314            text_emphasis_color: None,
1315            cursor_style: String::new(),
1316            scroll_container_id: String::new(),
1317            clip_path: String::new(),
1318            is_sticky: false,
1319            sticky_top: None,
1320            sticky_bottom: None,
1321            sticky_bound_max_y: i32::MAX,
1322            bg_size: BgSizeMode::Stretch,
1323            bg_repeat_x: BgRepeatMode::Repeat,
1324            bg_repeat_y: BgRepeatMode::Repeat,
1325            bg_pos_x: 0.0,
1326            bg_pos_y: 0.0,
1327            outline_color: None,
1328            outline_width: 0,
1329            outline_offset: 0,
1330            outline_style: String::from("solid"),
1331            object_fit: ObjectFit::Fill,
1332            object_pos_x: 0.5,
1333            object_pos_y: 0.5,
1334            filter: String::new(),
1335            mix_blend_mode: String::new(),
1336            backdrop_filter: String::new(),
1337            image_rendering: String::new(),
1338            text_stroke_width: 0,
1339            text_stroke_color: None,
1340            line_clamp: 0,
1341            is_modal: false,
1342            backdrop_color: None,
1343        }
1344    }
1345}
1346
1347// クリック判定用のリンク座標領域
1348#[derive(Clone, Debug)]
1349pub struct HyperlinkArea {
1350    pub href: String,
1351    pub x0: i32,
1352    pub y0: i32,
1353    pub x1: i32,
1354    pub y1: i32,
1355}
1356
1357// ブラウザエンジン (HTML/CSS レンダラ・DOM操作コア)
1358#[derive(Clone)]
1359pub struct DecodedImage {
1360    pub width: u32,
1361    pub height: u32,
1362    pub rgba: alloc::vec::Vec<u8>,
1363}
1364
1365pub struct WebEngine {
1366    /// このエンジン(タブ)の一意 ID。非同期ロードの結果分離に使う。
1367    pub engine_id: u64,
1368    pub active: bool,
1369    pub current_is_https: bool,
1370    pub current_host: String,
1371    pub current_path: String,
1372    /// 現在ページの完全URL(フラグメント #hash を含む)。アンカーナビの
1373    /// hashchange 発火で oldURL/newURL を組み立てる基準として使う。
1374    pub current_url_with_hash: String,
1375    pub title: String,
1376    pub scroll_y: i32,
1377    pub max_scroll_y: i32,
1378    /// `html{scroll-behavior:smooth}` が指定されているか(ルート要素の算出値から判定)。
1379    /// アンカー/フラグメントナビゲーションのスクロールのみを対象とし、ホイール/スクロール
1380    /// バードラッグは対象外(実ブラウザでも `scrollIntoView`/アンカー遷移のみが対象)。
1381    pub scroll_smooth: bool,
1382    /// `html{scrollbar-width}`(CSS Scrollbars Module Level 1。ルート要素の算出値から判定)。
1383    pub scrollbar_width: ScrollbarWidth,
1384    /// `html{scrollbar-color}`(CSS Scrollbars Module Level 1。ルート要素の算出値から判定)。
1385    pub scrollbar_color: Option<ScrollbarColor>,
1386    /// `html{scrollbar-width:none}`(後方互換用。`scrollbar_width == ScrollbarWidth::None` と同期)。
1387    pub scrollbar_width_none: bool,
1388    /// スムーススクロール進行中かどうか。
1389    pub scroll_anim_active: bool,
1390    pub scroll_anim_from: i32,
1391    pub scroll_anim_to: i32,
1392    pub scroll_anim_start_ms: f32,
1393    /// 【2026-08-03】URL のフラグメント(`#id`)。レイアウト完了後に
1394    /// 対象要素までスクロールするために保持する。適用したら空にする。
1395    pub pending_fragment: String,
1396    pub elements: Vec<RenderElement>,
1397    /// 【2026-08-01計測】`dirty` を最後に立てた箇所(`ファイル:行`)。
1398    /// 再描画が毎フレーム走る原因を特定するため。
1399    pub dirty_reason: &'static str,
1400    pub links: Vec<HyperlinkArea>,
1401    pub history: Vec<(bool, String, String)>,
1402    pub forward_history: Vec<(bool, String, String)>,
1403    pub dirty: bool,
1404    pub form_values: alloc::collections::BTreeMap<String, String>,
1405    /// element_id → HTML 由来の初期値。フォーム reset でこの値へ戻す。
1406    pub initial_form_values: alloc::collections::BTreeMap<String, String>,
1407    /// element_id → input の `name` 属性。フォーム送信時のパラメータ名に使う。
1408    pub field_names: alloc::collections::BTreeMap<String, String>,
1409    pub dom_contents: alloc::collections::BTreeMap<String, String>,
1410    pub executing_script: bool,
1411    /// 次のフレームで実行する <script>(外部 URL, インライン本文, is_module)。`run_pending_scripts` 参照。
1412    pub pending_scripts: alloc::vec::Vec<(Option<String>, String, bool)>,
1413    /// 初期スクリプトを流し終えた(document は interactive)。次のフレームで complete にする。
1414    pub ready_complete_pending: bool,
1415    /// interactive にした時刻(ms)。complete は副資源の取得が済み、少し経ってから。
1416    pub ready_interactive_at: u64,
1417    /// このフレームで complete にしてよいと決まった(`render.rs` の判定の結果)。
1418    pub ready_complete_now: bool,
1419    /// 前のフレームの DOM 節点数(complete の判定で、DOM が落ち着いたかを見る)。
1420    pub ready_last_nodes: usize,
1421    /// スクリプトを実行済みの文書(HTML の `hash_str`)。同じ文書の再レイアウト(フォント到着等)で
1422    /// スクリプトを再実行しないため。ナビゲーション開始時に `None` へ戻す(2026-10-05)。
1423    pub scripts_ran_for: Option<u32>,
1424    /// 次の parse_and_layout で DOM ブリッジを再構築するか(新ページ読込時に true)。
1425    pub dom_needs_rebuild: bool,
1426    /// リソース到着による再レイアウトを溜めておく(0 なら保留なし)。
1427    ///
1428    /// 【2026-08-05】フォントは 4 並列で 1 本ずつ届くため、
1429    /// 到着のたびに再レイアウトすると**1 回 4.6 秒**をその回数だけ払う。
1430    /// 実測では 100 フレーム中 5972 tick(全体の 44%)が
1431    /// `draw()` 内の再レイアウトだった。
1432    /// 少し待って**まとめて 1 回**にする。値は最初の到着時刻(tick)。
1433    pub pending_reflow_since: usize,
1434    /// 直近の到着時刻(tick)。これが止まったらまとめて実行する。
1435    pub pending_reflow_last: usize,
1436    pub focused_id: Option<String>,
1437    /// フォーカス取得時の入力値(blur 時の change 判定用)。
1438    pub focus_value: String,
1439    /// 現在マウスが乗っている要素 id(mouseover/mouseout 判定用)。
1440    pub hovered_id: Option<String>,
1441    pub cursor_pos: usize,
1442    pub env: crate::os_lib::aura::eval::Env,
1443    /// 組込み JavaScript ランタイム(<script>/onclick を実行)。aura は .aura 用に存続。
1444    pub js_runtime: crate::os_lib::ecma::JsRuntime,
1445    // --- Video Player Animation Fields ---
1446    pub video_playing: bool,
1447    pub video_tick: u32,
1448    pub video_controls: media_controls::MediaControlsState,
1449    // --- Async Loading Animation Fields ---
1450    /// 背景画像(`background-image`)として参照されている URL の集合。
1451    /// これらは取得を省略して描画を優先する(`ensure_image_cached` 参照)。
1452    pub background_image_urls: alloc::collections::BTreeSet<String>,
1453    /// iframe の src(解決済み URL)→ 代替表示。取得は 1 ページにつき 1 回(失敗も None として覚える)。
1454    pub iframe_previews: alloc::collections::BTreeMap<String, Option<iframe_preview::Preview>>,
1455    pub loading: bool,
1456    pub loading_tick: u32,
1457    pub mouse_x: i32,
1458    pub mouse_y: i32,
1459    /// 直近の `draw()` 呼び出し時点でマウスが `cursor: text` を持つ要素の上にあったか。
1460    /// OS 側(`main.rs` の `gui_shell_process`)がマウスカーソルの実描画形状を
1461    /// 決めるために参照する(`apps::browser::hovered_cursor_is_text()` 経由)。
1462    pub hovered_cursor_is_text: bool,
1463    /// CSS `cursor` のキーワード(`"pointer"`/`"grab"`/`"crosshair"` 等)。
1464    /// ホバー中の要素が持つ `cursor_style` 値をそのまま格納する。
1465    /// `"text"` は従来どおり `hovered_cursor_is_text` でも判定可能。
1466    pub hovered_cursor_kind: alloc::string::String,
1467    /// 前フレームの左ボタン状態。押下/解放のエッジ検出に使う
1468    /// (on_mouse は WM から毎フレーム現在値で呼ばれるため)。
1469    pub prev_btn_left: bool,
1470    /// 現在フレームの左ボタン押下状態(`:active` 疑似クラス判定用。
1471    /// `is_hovered && mouse_btn_left_down` で押下中の要素を判定する)。
1472    pub mouse_btn_left_down: bool,
1473    /// 右ボタンの前フレーム状態(contextmenu の押下エッジ検出用)。
1474    pub prev_btn_right: bool,
1475    /// 最後にクリックした要素 id と、その時刻(tick)。dblclick 判定用。
1476    pub last_click_id: Option<String>,
1477    pub last_click_tick: usize,
1478    /// 動画画面上の最後のクリック時刻(tick)。ダブルクリック全画面トグル判定用。
1479    pub last_video_click_tick: usize,
1480    // --- Window and Editor Scroll / Wrap Fields ---
1481    pub win_w: u32,
1482    pub win_h: u32,
1483    pub top_offset: i32,
1484    pub editor_wrap: bool,
1485    pub editor_scroll_y: i32,
1486    pub editor_scroll_x: i32,
1487    pub last_html: String,
1488    pub dragging_scrollbar: bool,
1489    /// デコード済み画像。`Arc` なのは、JS の `drawImage` から引く
1490    /// 共有の置き場(`image::shared_image`)と**同じ画素を指す**ため。
1491    /// 複製すると数 MB の写真を二重に持つことになる。
1492    pub image_cache:
1493        alloc::collections::BTreeMap<String, alloc::sync::Arc<DecodedImage>>,
1494    /// 取得を試みた画像 src(成功・失敗を問わず)。毎フレームの再フェッチ暴走を防ぐ。
1495    pub image_attempted: alloc::collections::BTreeSet<String>,
1496    /// `elements` を作り直した・書き換えた回数(描画の画像の取得要求の走査を省く判定に使う)。
1497    pub elements_gen: u64,
1498    /// 前回の画像の取得要求の走査の条件と、そこからのフレーム数。
1499    pub image_scan_key: Option<(u64, i32, i32, u32, usize, usize, usize)>,
1500    pub image_scan_frames: u32,
1501    pub active_text_box: Option<crate::kernel::text_box::TextBox>,
1502    /// `active_text_box` が破棄されても保持し続けるキャレット位置(文字単位)。
1503    ///
1504    /// 【2026-09-08 バグ修正】`parse_and_layout` は `active_text_box` を毎回捨てる。
1505    /// autofocus 付きの入力欄はその直後に再フォーカスされるが、TextBox は
1506    /// `with_text*()` で作り直されるためカーソルが**末尾へ飛んでいた**。
1507    /// note アプリの「↑で 1 行しか上がらない」「行の途中で打つと末尾に入る」は
1508    /// これが原因。再生成時にこの値からキャレットを復元する。
1509    /// フォーカスが別要素へ移ったときは復元しない(`focus_caret_owner` で判定)。
1510    pub focus_cursor_pos: usize,
1511    /// `focus_cursor_pos` がどの element_id のものかを覚えておく。
1512    pub focus_caret_owner: String,
1513    /// body/html 要素から取り出したページ背景色(None の場合はデフォルト色を使用)
1514    pub page_bg_color: Option<u32>,
1515    /// body/html 要素から取り出したデフォルト文字色
1516    pub page_text_color: Option<u32>,
1517    /// CSS アニメーション/トランジション駆動エンジン。
1518    pub anim_engine: crate::os_lib::css::AnimationEngine,
1519    /// 直近の parse_and_layout で収集した、id付き要素ごとの (transition 指定, animation 指定)。
1520    /// element_id → (transition 文字列, animation 文字列)。
1521    pub anim_specs: alloc::collections::BTreeMap<String, (String, String)>,
1522    /// element_id → property → 直近の確定値(トランジション開始の from 算出に使う)。
1523    pub anim_prev_values:
1524        alloc::collections::BTreeMap<String, alloc::collections::BTreeMap<String, String>>,
1525    /// アニメ駆動の再レイアウト中は true。この間は sync_animations のトランジション
1526    /// 検出と prev 更新を抑止し、補間値による逆向きトランジションの誤発火を防ぐ。
1527    pub in_anim_relayout: bool,
1528    /// `flatten_layout` 再帰中の「祖先の実効 z」。描画順が祖先を追い越さないよう
1529    /// 各要素の z をこの値まで引き上げる(`spec/paint_order.md` の不変条件 I-1)。
1530    pub inherited_paint_z: i32,
1531    /// `flatten_layout` 再帰中の現在のツリー深さ。`RenderElement::paint_depth` の元。
1532    pub inherited_paint_depth: u32,
1533    /// `flatten_layout` 再帰中の「位置指定要素(relative/absolute/fixed/sticky)配下か否か」。
1534    /// CSS 2.1 Appendix E に基づき、z-index: auto/0 の位置指定要素とその子孫を通常フローの
1535    /// ブロック・インラインより手前に描画するために使う。
1536    pub inherited_positioned: bool,
1537    /// `flatten_layout` 再帰中、根から今の親までにある位置指定要素の数(包含ブロックの深さ)。
1538    pub inherited_pos_count: u32,
1539    /// `position:absolute` の部分木が生成した要素の範囲と、その包含ブロックの深さ
1540    /// `(開始, 終了, inherited_pos_count)`。祖先の overflow で切るかの判定に使う。
1541    pub abs_marks: Vec<(usize, usize, u32)>,
1542    /// `flatten_layout` 再帰中の、今いるスタッキングコンテキストの段の列。
1543    pub stack_prefix: Vec<paint_order::StackStep>,
1544    /// `flatten_layout` 再帰中、今までに作った要素のうち flatten の使い回し表の項目(当たり・登録)から来た数(2026-11-18)。
1545    /// 部分木を表に入れるかの判定(`flatten_memo_budget::worth_storing`)に使う。
1546    pub flatten_memo_covered: usize,
1547    /// `flatten_layout` 再帰中、スタッキングの段と `pointer-events` が決まった要素の区間(2026-11-18、TODO R5 (e) ④)。
1548    /// 祖先ごとに子孫の要素を全部見直さないため(`decided_spans.rs`)。
1549    pub flatten_decided: decided_spans::DecidedSpans,
1550    /// 同じく `visibility` が決まった要素の区間(`visibility` は要素の箱のときだけ決まるので別に持つ)。
1551    pub flatten_visibility_decided: decided_spans::DecidedSpans,
1552    /// `flatten_decided` から取り出したすき間の置き場(確保を使い回す)。
1553    pub flatten_gaps: Vec<(usize, usize)>,
1554    /// 背景(色・画像・グラデーション)を持つ要素の添字。`draw` がフレームごとに集め、`effective_bg_behind` が使う(2026-11-18)。
1555    pub bg_layer_idx: Vec<u32>,
1556    /// 直近のアニメーション由来 `parse_and_layout` の所要時間 [ms]。
1557    /// 再レイアウトを実測コストに応じて間引くために使う。
1558    pub last_anim_layout_ms: f32,
1559    /// 最後にアニメーション由来の再レイアウトを完了した時刻 [ms]。
1560    pub last_anim_relayout_end_ms: f32,
1561    /// 直近の DOM 変更由来の再レイアウトの所要時間と終了時刻 [ms](間引き用)。
1562    pub last_dom_layout_ms: f32,
1563    pub last_dom_relayout_end_ms: f32,
1564    /// この描画で全再レイアウトを既に 1 回したか(1 描画あたり 1 回まで。残りは次の描画へ)。
1565    pub relayout_done_this_draw: bool,
1566    /// `relayout_now_if_dom_dirty` の間だけ立つ(間引きを無視する)。
1567    pub force_relayout: bool,
1568    /// サブスクロール領域ごとの現在スクロール量 (element_id → scroll_y)。
1569    /// overflow:scroll/auto コンテナの独立スクロール位置を保持する。
1570    pub scroll_regions: alloc::collections::BTreeMap<String, i32>,
1571    /// サブスクロール領域ごとの現在水平スクロール量 (element_id → scroll_x)。
1572    pub scroll_regions_x: alloc::collections::BTreeMap<String, i32>,
1573    /// サブスクロールバーをドラッグ中のコンテナ ID(None = ドラッグなし)。
1574    pub dragging_sub_scrollbar: Option<String>,
1575    /// parse_and_layout で収集したスクロールコンテナのメタ情報。
1576    /// (element_id, max_scroll_y, content_x, content_y, width, height, scrollbar_width, scrollbar_color)
1577    /// スクロールバー描画とホバー判定に使う。ページ再レイアウトのたびに再構築される。
1578    pub scroll_containers: alloc::vec::Vec<(String, i32, i32, i32, i32, i32, ScrollbarWidth, Option<ScrollbarColor>)>,
1579    /// 動的 `<script>` の非同期フェッチ・状態管理マネージャ。
1580    pub dynamic_scripts: dynamic_scripts::DynamicScriptManager,
1581    /// インクリメンタル再レイアウト用の CSS パースキャッシュ。
1582    /// 直近にパースした `<style>` ブロック列の 128 ビットハッシュをキーに、parse_css 結果を再利用する。
1583    /// 同一 HTML の再レイアウト(JS による textContent/style 変更など)では
1584    /// CSS パースも文字列コピー・連結も丸ごと省略でき、大きなスタイルシートで効く(TODO P5b)。
1585    pub cached_css_hash: Option<(u64, u64)>,
1586    /// `<style>` ブロック単位のパースキャッシュ(1 つの `<style>` の追加・変更時に他ブロックの再パースを省略)。
1587    pub(crate) inline_style_memo: inline_style_cache::InlineStyleParseMemo,
1588    /// 直近の CSS パース結果(`cached_css_hash` に対応)。None なら未キャッシュ。
1589    pub cached_stylesheet: Option<alloc::rc::Rc<crate::os_lib::css::StyleSheet>>,
1590    /// `cached_stylesheet` から作った規則の索引(スタイルシートが同じ間は作り直さない)。
1591    pub cached_rule_index: Option<alloc::rc::Rc<crate::os_lib::css::rule_index::RuleIndex>>,
1592    /// スタイル計算の結果の使い回しの表(TODO A8。`css/style_memo.rs`)。
1593    pub style_memo: crate::os_lib::css::style_memo::StyleMemo,
1594    /// 外部 `<link rel="stylesheet">` から取得した CSS を連結してキャッシュする
1595    /// (None = 未取得)。`parse_and_layout` は再レイアウトのたびに呼ばれ得るため、
1596    /// 毎回フェッチすると致命的に重く(かつ毎フレーム HTTP リクエストになる)、
1597    /// ここで初回だけ取得して以降は再利用する。ページ遷移時に None へリセットする。
1598    pub external_css_cache: Option<String>,
1599    /// JS が挿入した `<link rel="stylesheet">` のうち CSS を取得中のもの `(要素, host, path)`(`layout::run_dynamic_scripts`)。
1600    pub pending_link_css: alloc::vec::Vec<(usize, String, String)>,
1601    /// 解析済みの外部 CSS の要素数 `(rules, keyframes, counter_styles, font_faces, layers)`。
1602    /// 外部 CSS は一度だけ解析して `cached_stylesheet` の先頭に置き、再レイアウト時は
1603    /// インライン `<style>` の差分だけを解析して末尾を差し替える。
1604    pub external_css_counts: Option<(usize, usize, usize, usize, alloc::vec::Vec<String>)>,
1605    /// `external_css_counts` の外部 CSS に解析済みの `<link>` の (host, path)。動的な `<link>` の CSS が届いたとき、
1606    /// 既に解析済みなら外部 CSS を解析し直さない(`run_dynamic_links`)。
1607    pub external_css_parsed: alloc::vec::Vec<(String, String)>,
1608    /// OpenStreetMap 埋め込みごとのインタラクティブ操作状態(パン・ズーム指定)。
1609    pub osm_states: alloc::collections::BTreeMap<String, crate::os_lib::web_engine::embed_map::MapState>,
1610    /// 地図をドラッグ中の状態: (iframe_src, 直前マウスX, 直前マウスY)。
1611    pub dragging_osm: Option<(String, i32, i32)>,
1612    /// テキスト選択範囲(None = 選択なし)。
1613    pub selection: Option<selection::SelectionRange>,
1614    /// ドラッグ選択の開始点(アンカー)。
1615    pub selecting_anchor: Option<selection::TextPosition>,
1616    /// 現在テキストをドラッグ選択中か。
1617    pub is_selecting_text: bool,
1618    /// CSS `::selection` 疑似要素から解決された選択ハイライトスタイル。
1619    pub selection_style: selection_style::SelectionStyle,
1620    /// この文書の参照元(`document.referrer`。読み込み時に送った `Referer` と同じ値)。
1621    pub referrer: String,
1622    /// 次の読み込みで送る `Referer`(`load_frame` が立て、`load_page_with_method` が消費する)。
1623    pending_referer: Option<String>,
1624    /// iframe の入れ子の文書(キーは `iframe_frame_key`)。【2026-10-17】従来の iframe は
1625    /// プレビュー表示だけだった。iframe ごとに独立したエンジン(文書・JS・レイアウト)を持ち、
1626    /// iframe の矩形を窓として描画する。
1627    pub child_frames: alloc::collections::BTreeMap<String, alloc::boxed::Box<WebEngine>>,
1628    /// iframe の中の文書か(入れ子の深さ。最上位は 0)。
1629    pub frame_depth: u32,
1630    /// 直近の描画で子フレームを描いた矩形(窓内座標 `(キー, x, y, w, h)`)。マウスの転送先を決める。
1631    pub frame_hits: Vec<(String, i32, i32, i32, i32)>,
1632    /// 直近でクリックされた子フレームのキー(キー入力の転送先)。
1633    pub focused_frame: Option<String>,
1634}
1635
1636impl Default for WebEngine {
1637    fn default() -> Self {
1638        Self::new()
1639    }
1640}
1641
1642impl WebEngine {
1643    pub fn new() -> Self {
1644        let env = crate::os_lib::aura::eval::Env::new();
1645        let engine_id = {
1646            let mut g = NEXT_ENGINE_ID.lock();
1647            let id = *g;
1648            *g += 1;
1649            id
1650        };
1651        Self {
1652            dirty_reason: "init",
1653            pending_fragment: String::new(),
1654            engine_id,
1655            active: false,
1656            current_is_https: true,
1657            current_host: String::from(site_hooks::hooks().initial_page().0),
1658            current_path: String::from("/"),
1659            current_url_with_hash: alloc::format!("https://{}/", site_hooks::hooks().initial_page().0),
1660            title: String::from(site_hooks::hooks().initial_page().1),
1661            scroll_y: 0,
1662            max_scroll_y: 0,
1663            scroll_smooth: false,
1664            scrollbar_width: ScrollbarWidth::Auto,
1665            scrollbar_color: None,
1666            scrollbar_width_none: false,
1667            scroll_anim_active: false,
1668            scroll_anim_from: 0,
1669            scroll_anim_to: 0,
1670            scroll_anim_start_ms: 0.0,
1671            elements: Vec::new(),
1672            links: Vec::new(),
1673            history: Vec::new(),
1674            forward_history: Vec::new(),
1675            dirty: true,
1676            form_values: alloc::collections::BTreeMap::new(),
1677            initial_form_values: alloc::collections::BTreeMap::new(),
1678            field_names: alloc::collections::BTreeMap::new(),
1679            dom_contents: alloc::collections::BTreeMap::new(),
1680            executing_script: false,
1681            pending_scripts: alloc::vec::Vec::new(),
1682            ready_complete_pending: false,
1683            ready_interactive_at: 0,
1684            ready_complete_now: false,
1685            ready_last_nodes: 0,
1686            scripts_ran_for: None,
1687            dom_needs_rebuild: false,
1688            pending_reflow_since: 0,
1689            pending_reflow_last: 0,
1690            focused_id: None,
1691            focus_value: String::new(),
1692            hovered_id: None,
1693            cursor_pos: 0,
1694            env,
1695            js_runtime: crate::os_lib::ecma::JsRuntime::new(),
1696            video_playing: false,
1697            video_tick: 0,
1698            video_controls: media_controls::MediaControlsState::new(120.0),
1699            background_image_urls: alloc::collections::BTreeSet::new(),
1700            iframe_previews: alloc::collections::BTreeMap::new(),
1701            loading: false,
1702            loading_tick: 0,
1703            mouse_x: -1000,
1704            mouse_y: -1000,
1705            hovered_cursor_is_text: false,
1706            hovered_cursor_kind: alloc::string::String::new(),
1707            prev_btn_left: false,
1708            mouse_btn_left_down: false,
1709            prev_btn_right: false,
1710            last_click_id: None,
1711            last_click_tick: 0,
1712            last_video_click_tick: 0,
1713            win_w: 1366,
1714            win_h: 768,
1715            top_offset: 0,
1716            editor_wrap: true,
1717            editor_scroll_y: 0,
1718            editor_scroll_x: 0,
1719            last_html: String::new(),
1720            dragging_scrollbar: false,
1721            image_cache: alloc::collections::BTreeMap::new(),
1722            image_attempted: alloc::collections::BTreeSet::new(),
1723            elements_gen: 0,
1724            image_scan_key: None,
1725            image_scan_frames: 0,
1726            active_text_box: None,
1727            focus_cursor_pos: 0,
1728            focus_caret_owner: String::new(),
1729            page_bg_color: None,
1730            page_text_color: None,
1731            anim_engine: crate::os_lib::css::AnimationEngine::new(),
1732            anim_specs: alloc::collections::BTreeMap::new(),
1733            anim_prev_values: alloc::collections::BTreeMap::new(),
1734            in_anim_relayout: false,
1735            inherited_paint_z: 0,
1736            inherited_paint_depth: 0,
1737            inherited_positioned: false,
1738            inherited_pos_count: 0,
1739            abs_marks: Vec::new(),
1740            stack_prefix: Vec::new(),
1741            flatten_memo_covered: 0,
1742            flatten_decided: decided_spans::DecidedSpans::new(),
1743            flatten_visibility_decided: decided_spans::DecidedSpans::new(),
1744            flatten_gaps: Vec::new(),
1745            bg_layer_idx: Vec::new(),
1746            last_anim_layout_ms: 0.0,
1747            last_anim_relayout_end_ms: 0.0,
1748            last_dom_layout_ms: 0.0,
1749            last_dom_relayout_end_ms: 0.0,
1750            relayout_done_this_draw: false,
1751            force_relayout: false,
1752            scroll_regions: alloc::collections::BTreeMap::new(),
1753            scroll_regions_x: alloc::collections::BTreeMap::new(),
1754            dragging_sub_scrollbar: None,
1755            scroll_containers: alloc::vec::Vec::new(),
1756            dynamic_scripts: dynamic_scripts::DynamicScriptManager::new(),
1757            cached_css_hash: None,
1758            inline_style_memo: Default::default(),
1759            cached_stylesheet: None,
1760            cached_rule_index: None,
1761            style_memo: Default::default(),
1762            external_css_cache: None,
1763            pending_link_css: alloc::vec::Vec::new(),
1764            external_css_counts: None,
1765            external_css_parsed: alloc::vec::Vec::new(),
1766            osm_states: alloc::collections::BTreeMap::new(),
1767            dragging_osm: None,
1768            selection: None,
1769            selecting_anchor: None,
1770            is_selecting_text: false,
1771            selection_style: selection_style::SelectionStyle::default(),
1772            referrer: String::new(),
1773            pending_referer: None,
1774            child_frames: alloc::collections::BTreeMap::new(),
1775            frame_depth: 0,
1776            frame_hits: Vec::new(),
1777            focused_frame: None,
1778        }
1779    }
1780
1781    /// JS が挿入した未実行・取得中の `<script>` があるか。
1782    pub fn has_pending_dynamic_scripts(&self) -> bool {
1783        self.dynamic_scripts.has_pending()
1784            || self.js_runtime.dom().try_borrow().is_ok_and(|d| !d.pending_dynamic_scripts.is_empty())
1785    }
1786
1787    /// 子フレーム(iframe の文書)のどれかが描き直しを要るか(読み込み中・変更あり・
1788    /// 保留スクリプト・期限の来たタイマー)。子は親の `draw` の中でしか進まないので、
1789    /// 親のアプリはこれが真なら再描画する。
1790    pub fn frames_want_redraw(&self) -> bool {
1791        self.child_frames.values().any(|c| {
1792            c.loading
1793                || (c.video_playing && !video::VIDEO_STATE.lock().as_ref().is_some_and(|st| st.paused))
1794                || c.dirty
1795                || c.scroll_anim_active
1796                || c.dragging_scrollbar
1797                || c.dragging_sub_scrollbar.is_some()
1798                // 先送りした DOM 変更の再レイアウト(間引き)を反映する描画が要る。
1799                || c.js_runtime.dom().try_borrow().is_ok_and(|d| d.dirty)
1800                || !c.pending_scripts.is_empty()
1801                || c.has_pending_dynamic_scripts()
1802                || c.js_runtime.has_due_timers()
1803                || c.frames_want_redraw()
1804        })
1805    }
1806
1807    /// iframe の文書として `url`(絶対 URL)を読み込む。`referer` は埋め込み元ページから
1808    /// 参照元ポリシーで決めた値(`referrer::referrer_for`)。
1809    pub fn load_frame(&mut self, url: &str, referer: Option<String>) {
1810        let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
1811            (true, r)
1812        } else if let Some(r) = url.strip_prefix("http://") {
1813            (false, r)
1814        } else {
1815            crate::warn!("[FRAME] 未対応の iframe URL: {}", url);
1816            return;
1817        };
1818        let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1819        let (host, tail) = rest.split_at(end);
1820        let path = if tail.starts_with('/') {
1821            String::from(tail)
1822        } else {
1823            alloc::format!("/{}", tail)
1824        };
1825        crate::info!("[FRAME] 読み込み depth={} url={} referer={:?}", self.frame_depth, url, referer);
1826        self.pending_referer = referer;
1827        self.load_page(is_https, host, &path, false, 0);
1828    }
1829
1830    /// 選択中のテキスト文字列を取得する。選択が無い場合は空文字列。
1831    pub fn get_selected_text(&self) -> String {
1832        if let Some(ref range) = self.selection {
1833            let layouts: alloc::vec::Vec<selection::TextElementLayout> = self
1834                .elements
1835                .iter()
1836                .enumerate()
1837                .filter(|(_, el)| !el.text.is_empty() && !el.is_button)
1838                .map(|(idx, el)| selection::TextElementLayout {
1839                    element_index: idx,
1840                    text: el.text.clone(),
1841                    x: el.x_offset,
1842                    y: el.y_offset,
1843                    width: el.width,
1844                    height: el.height,
1845                })
1846                .collect();
1847            selection::extract_selected_text(&layouts, range)
1848        } else {
1849            String::new()
1850        }
1851    }
1852
1853    /// テキスト選択を解除する。
1854    pub fn clear_selection(&mut self) {
1855        if self.selection.is_some() || self.selecting_anchor.is_some() || self.is_selecting_text {
1856            self.selection = None;
1857            self.selecting_anchor = None;
1858            self.is_selecting_text = false;
1859            self.dirty = true;
1860            self.dirty_reason = "clear_selection";
1861        }
1862    }
1863
1864    fn parse_image_url(url: &str) -> Option<(bool, String, String)> {
1865        if let Some(rest) = url.strip_prefix("http://") {
1866            if let Some(idx) = rest.find('/') {
1867                let (h, p) = rest.split_at(idx);
1868                let host = String::from(h);
1869                let path = String::from(p);
1870                Some((false, host, path))
1871            } else {
1872                let host = String::from(rest);
1873                let path = String::from("/");
1874                Some((false, host, path))
1875            }
1876        } else if let Some(rest) = url.strip_prefix("https://") {
1877            if let Some(idx) = rest.find('/') {
1878                let (h, p) = rest.split_at(idx);
1879                let host = String::from(h);
1880                let path = String::from(p);
1881                Some((true, host, path))
1882            } else {
1883                let host = String::from(rest);
1884                let path = String::from("/");
1885                Some((true, host, path))
1886            }
1887        } else {
1888            None
1889        }
1890    }
1891
1892    /// 画像ロードをノンブロッキングでリクエストする。
1893    /// フォーカスが文字入力の場所(`input`・`textarea`・`contenteditable`)にあるか。
1894    /// キーによるスクロール等は、このときだけ文字入力を優先して何もしない。
1895    /// 【2026-10-24】従来は何かにフォーカスがあるだけでスクロールキーを無視しており、
1896    /// YouTube(プレーヤーの `div` などにフォーカスを置く)で PageDown が効かなかった。
1897    pub fn focus_is_text_entry(&self) -> bool {
1898        let Some(id) = self.focused_id.as_deref() else { return false };
1899        if self.elements.iter().any(|e| e.element_id == id && (e.is_input || e.is_textarea)) {
1900            return true;
1901        }
1902        let dom = self.js_runtime.dom().borrow();
1903        dom.nodes.iter().any(|n| {
1904            n.id == id
1905                && (matches!(n.tag.as_str(), "input" | "textarea" | "select")
1906                    || n.attrs.get("contenteditable").is_some_and(|v| !v.eq_ignore_ascii_case("false")))
1907        })
1908    }
1909
1910    /// キャッシュにあれば即返す。なければバックグラウンドスレッドにキューイングして即return。
1911    fn ensure_image_cached(&mut self, src: &str) {
1912        if src.is_empty() {
1913            return;
1914        }
1915        if self.image_cache.contains_key(src) {
1916            return;
1917        }
1918        // 取得結果は全エンジン共通の待ち行列から最初に見たエンジンが取り出す。iframe の文書
1919        // (子フレーム)が要求した画像を親が取り出した場合も、共有キャッシュから取り込む。
1920        if let Some(img) = image::shared_image(src) {
1921            self.image_cache.insert(String::from(src), img);
1922            self.dirty = true;
1923            return;
1924        }
1925        // 既に取得を試みた src は再フェッチしない(毎フレームの再取得暴走を防止)。
1926        // デコード失敗(WebP 等の非対応)でも 1 回で打ち切る。
1927        if self.image_attempted.contains(src) {
1928            return;
1929        }
1930        self.image_attempted.insert(String::from(src));
1931
1932        let req = if src.starts_with("http://") || src.starts_with("https://") {
1933            if let Some((is_https, host, path)) = Self::parse_image_url(src) {
1934                if self.current_is_https && !is_https {
1935                    crate::warn!(
1936                        "MIXED CONTENT BLOCKED: Image {} over HTTP in HTTPS page",
1937                        src
1938                    );
1939                    return;
1940                }
1941                ImageFetchReq {
1942                    src_key: String::from(src),
1943                    is_https,
1944                    host,
1945                    path,
1946                    is_local: false,
1947                    owner: self.engine_id,
1948                    group: crate::kernel::scheduler::current_mem_group(),
1949                }
1950            } else {
1951                return;
1952            }
1953        } else if self.current_host == "localhost" {
1954            ImageFetchReq {
1955                src_key: String::from(src),
1956                is_https: false,
1957                host: String::new(),
1958                path: String::from(src),
1959                is_local: true,
1960                owner: self.engine_id,
1961                group: crate::kernel::scheduler::current_mem_group(),
1962            }
1963        } else {
1964            let host = self.current_host.clone();
1965            let path = if src.starts_with('/') {
1966                String::from(src)
1967            } else {
1968                let base_dir = self
1969                    .current_path
1970                    .rfind('/')
1971                    .map(|i| self.current_path.get(..=i).unwrap_or("/"))
1972                    .unwrap_or("/");
1973                let combined = alloc::format!("{}{}", base_dir, src);
1974                let mut parts: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
1975                for seg in combined.split('/') {
1976                    match seg {
1977                        "" | "." => {}
1978                        ".." => {
1979                            parts.pop();
1980                        }
1981                        s => parts.push(s),
1982                    }
1983                }
1984                alloc::format!("/{}", parts.join("/"))
1985            };
1986            ImageFetchReq {
1987                src_key: String::from(src),
1988                is_https: self.current_is_https,
1989                host,
1990                path,
1991                is_local: false,
1992                owner: self.engine_id,
1993                group: crate::kernel::scheduler::current_mem_group(),
1994            }
1995        };
1996
1997        enqueue_image(req);
1998    }
1999
2000    /// バックグラウンドスレッドが完了した画像を image_cache に取り込む。
2001    /// 新規取り込みがあった場合 true を返す(再描画が必要)。
2002    fn poll_image_results(&mut self) -> bool {
2003        let mut q = IMAGE_QUEUE.lock();
2004        if q.results.is_empty() {
2005            return false;
2006        }
2007        let results: Vec<(String, DecodedImage)> = core::mem::take(&mut q.results);
2008        // 取り出したら写しも 0 に戻す(再描画判定はこの写しだけを見る)。
2009        image::store_results_len(0);
2010        drop(q);
2011        for (key, decoded) in results {
2012            // crate::info!(
2013            //     "IMAGE_LOADER: decoded '{}' {}x{}",
2014            //     key,
2015            //     decoded.width,
2016            //     decoded.height
2017            // );
2018            // レイアウトが自然サイズを使えるよう登録する。
2019            // これが無いと寸法未指定の `<img>` が既定の 400×200 のままになる。
2020            crate::os_lib::layout::register_image_natural_size(
2021                &key,
2022                decoded.width as i32,
2023                decoded.height as i32,
2024            );
2025            let shared = alloc::sync::Arc::new(decoded);
2026            image::share_image(&key, shared.clone());
2027            self.image_cache.insert(key, shared);
2028        }
2029        true
2030    }
2031
2032    // ローカルHTMLファイルを直接パースして表示する処理
2033    /// 新しい文書のために JS 実行環境(グローバル)を作り直す。
2034    ///
2035    /// 【2026-10-23】従来は文書が変わっても DOM だけ作り直し、前の文書の関数・クロージャ・
2036    /// タイマー・登録済みカスタム要素が残っていた。YouTube のトップから視聴ページへ移ると
2037    /// 両方のスクリプト(各 10MB 超)の構文木が積み上がり、ヒープ 512MB を使い切った
2038    /// (QEMU の run-full で実測)。古い実行環境の循環参照は `JsRuntime` の Drop が切る。
2039    fn reset_js_for_new_document(&mut self) {
2040        self.js_runtime = crate::os_lib::ecma::JsRuntime::new();
2041        self.dynamic_scripts.clear();
2042        self.ready_complete_pending = false;
2043        self.ready_last_nodes = 0;
2044    }
2045
2046    pub fn load_html(&mut self, html: &str, filename: &str, top_offset: i32) {
2047        // 新しいナビゲーション: この文書のスクリプトはまだ実行していない。
2048        self.scripts_ran_for = None;
2049        self.video_playing = false;
2050        stop_video_playback();
2051        self.reset_js_for_new_document();
2052        self.dom_contents.clear();
2053        self.dom_needs_rebuild = true;
2054        // ページ遷移: 外部 CSS キャッシュを破棄し、新ページの <link> を取り直す。
2055        self.external_css_cache = None;
2056        self.pending_link_css.clear();
2057        self.external_css_counts = None;
2058        self.cached_stylesheet = None;
2059        self.cached_rule_index = None;
2060        self.cached_css_hash = None;
2061        self.inline_style_memo.clear();
2062        // ローカルページへの遷移でも旧ページの画像取得とフォーム値を破棄する。
2063        IMAGE_QUEUE
2064            .lock()
2065            .pending
2066            .retain(|r| r.owner != self.engine_id);
2067        self.form_values.clear();
2068        self.initial_form_values.clear();
2069        self.field_names.clear();
2070        self.current_host = String::from("localhost");
2071        self.current_path = alloc::format!("/{}", filename);
2072        self.title = alloc::format!("Local: {}", filename);
2073        // 【2026-07-27診断】ローカルページ読み込み由来の再レイアウト回数。
2074        {
2075            static N: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2076            let n = N.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2077            if n < 8 {
2078                crate::warn!("[LAYOUT][SRC] load_html('{}') #{}", filename, n + 1);
2079            }
2080        }
2081        self.parse_and_layout(html, None, top_offset, self.win_w, self.win_h);
2082        self.dirty = true;
2083        self.dirty_reason = "mod.rs:1432";
2084    }
2085
2086    // 現在のURLを取得
2087    /// `history.pushState`/`replaceState` で変わった文書の URL を、表示中の URL(`current_path`)に反映する。
2088    /// 同じスキーム・ホストのときだけ(`pushState` は同一オリジンに限られる)。変わったら true。
2089    ///
2090    /// 【2026-10-29】従来は JS の `location` だけが変わり、アドレス欄は元の URL のままだった(YouTube の
2091    /// 自動再生で次の動画へ移っても `watch?v=` が変わらなかった)。実ブラウザでは文書の URL そのものが変わる。
2092    pub fn sync_url_from_script(&mut self) -> bool {
2093        // 読み込み中(この文書のスクリプトをまだ実行していない)は、`location` が前の文書のままのことがある。
2094        if self.scripts_ran_for.is_none() {
2095            return false;
2096        }
2097        let Some(href) = self.js_runtime.location_href() else { return false };
2098        let scheme = if self.current_is_https { "https://" } else { "http://" };
2099        let Some(rest) = href.strip_prefix(scheme) else { return false };
2100        let (host, path) = match rest.find('/') {
2101            Some(i) => rest.split_at(i),
2102            None => (rest, "/"),
2103        };
2104        if host != self.current_host {
2105            return false;
2106        }
2107        let (path_only, frag) = match path.split_once('#') {
2108            Some((p, f)) => (p, Some(f)),
2109            None => (path, None),
2110        };
2111        if path_only == self.current_path {
2112            return false;
2113        }
2114        self.current_path = String::from(path_only);
2115        self.current_url_with_hash = match frag {
2116            Some(f) => alloc::format!("{}{}{}#{}", scheme, host, path_only, f),
2117            None => alloc::format!("{}{}{}", scheme, host, path_only),
2118        };
2119        true
2120    }
2121
2122    pub fn get_url(&self) -> String {
2123        // `about:` ページは `about:blank` のまま(スキームもパスも付けない)。
2124        if url_resolve::is_about_host(&self.current_host) {
2125            return self.current_host.clone();
2126        }
2127        let schema = if self.current_is_https {
2128            "https://"
2129        } else {
2130            "http://"
2131        };
2132        alloc::format!("{}{}{}", schema, self.current_host, self.current_path)
2133    }
2134
2135    /// 内蔵の `about:` ページを表示する(【2026-11-17】ネットワークは使わない)。
2136    /// `about:blank` は空の文書。未知の `about:xxx` は簡単な「見つかりません」ページ。
2137    fn load_about_page(&mut self, host: &str) {
2138        // 撮影の手順(`scripts/screenshot_site.sh`)は `host=<URL のホスト>` の行でブラウザの起動を判断する。
2139        // 通信しない内蔵ページでも同じ形の行を 1 行出す(出さないと起動の打ち直しでウィンドウが増えた)。
2140        crate::warn!("[BROWSER] built-in page host={}", host);
2141        self.current_is_https = false;
2142        self.current_host = String::from(host);
2143        self.current_path = String::new();
2144        self.current_url_with_hash = String::from(host);
2145        self.loading = false;
2146        // 前のページの読み込み要求が残っていれば捨てる。
2147        ASYNC_LOAD
2148            .lock()
2149            .requests
2150            .retain(|r| r.owner != self.engine_id);
2151        let html = if host == "about:blank" {
2152            self.title = String::from("about:blank");
2153            String::from("<html><head></head><body></body></html>")
2154        } else {
2155            self.title = String::from("Not Found");
2156            alloc::format!(
2157                "<html><head><title>Not Found</title></head><body style=\"background-color: #282a36; color: #f8f8f2;\"><h1>Not Found</h1><p>Unknown page: {}</p></body></html>",
2158                host.replace('<', "&lt;").replace('>', "&gt;")
2159            )
2160        };
2161        let top = self.top_offset;
2162        self.parse_and_layout(&html, None, top, self.win_w, self.win_h);
2163        self.dirty = true;
2164        self.dirty_reason = "mod.rs:about";
2165    }
2166
2167    // 新しいURL(ホスト&パス)のロード処理 (非同期化)
2168    pub fn load_page(
2169        &mut self,
2170        is_https: bool,
2171        host: &str,
2172        path: &str,
2173        save_history: bool,
2174        _top_offset: i32,
2175    ) {
2176        self.load_page_with_method(is_https, host, path, save_history, "GET", None);
2177    }
2178
2179    pub fn load_page_post(
2180        &mut self,
2181        is_https: bool,
2182        host: &str,
2183        path: &str,
2184        body: &str,
2185        _top_offset: i32,
2186    ) {
2187        self.load_page_with_method(is_https, host, path, true, "POST", Some(String::from(body)));
2188    }
2189
2190    fn load_page_with_method(
2191        &mut self,
2192        is_https: bool,
2193        host: &str,
2194        path: &str,
2195        save_history: bool,
2196        method: &str,
2197        body: Option<String>,
2198    ) {
2199        // 新しいナビゲーション: この文書のスクリプトはまだ実行していない。
2200        self.scripts_ran_for = None;
2201        // 参照元は `load_frame` が立てたときだけ(URL の直接入力・履歴移動には無い)。
2202        let referer = self.pending_referer.take();
2203        self.referrer = referer.clone().unwrap_or_default();
2204        // 前の文書の iframe は捨てる。
2205        self.child_frames.clear();
2206        // 【2026-08-03】URL のフラグメント(`#id`)を分離して覚えておく。
2207        //
2208        // 従来は `#` を含んだままパスとして HTTP 要求に載せており、
2209        // `https://example.com/#research` のような URL が正しく扱えなかった。
2210        // フラグメントはサーバへ送るものではなく、
2211        // **取得後にページ内でスクロールする指定**である。
2212        // レイアウト完了後に `navigate_to_fragment` で適用する。
2213        let (path, frag) = match path.split_once('#') {
2214            Some((p, f)) => (p, String::from(f)),
2215            None => (path, String::new()),
2216        };
2217        let path = if path.is_empty() { "/" } else { path };
2218        self.pending_fragment = frag;
2219
2220        self.video_playing = false;
2221        stop_video_playback();
2222        self.reset_js_for_new_document();
2223        self.dom_contents.clear();
2224        self.dom_needs_rebuild = true;
2225        // ページ遷移: 外部 CSS キャッシュを破棄し、新ページの <link> を取り直す。
2226        self.external_css_cache = None;
2227        self.pending_link_css.clear();
2228        self.external_css_counts = None;
2229        self.cached_stylesheet = None;
2230        self.cached_rule_index = None;
2231        self.cached_css_hash = None;
2232        self.inline_style_memo.clear();
2233        // ページ遷移: 旧ページの未処理画像ダウンロードを破棄する。
2234        // これをしないと、遷移後も旧ページの画像取得が延々と続き OS 全体が重くなる。
2235        IMAGE_QUEUE
2236            .lock()
2237            .pending
2238            .retain(|r| r.owner != self.engine_id);
2239        // 旧ページのフォーム入力値・name マッピングは次ページへ持ち越さない。
2240        self.form_values.clear();
2241        self.initial_form_values.clear();
2242        self.field_names.clear();
2243        if save_history {
2244            self.history.push((
2245                self.current_is_https,
2246                self.current_host.clone(),
2247                self.current_path.clone(),
2248            ));
2249            self.forward_history.clear();
2250        }
2251
2252        // 【2026-11-17】`about:` ページはネットワークへ出さず、その場で内蔵の文書を出す。
2253        if url_resolve::is_about_host(host) {
2254            self.load_about_page(host);
2255            return;
2256        }
2257        // 【2026-11-18】読み込みを始めたことを 1 行出す(撮影の手順 `scripts/screenshot_site.sh` は `host=<ホスト>` の行で
2258        // ブラウザの起動を判断する。DNS を引かない IP アドレス〔手元の試験サーバ `10.0.2.2`〕では、それまで行が出ず
2259        // 起動していないと判断されていた)。
2260        crate::warn!("[BROWSER] load host={} https={}", host, is_https);
2261
2262        if host == "localhost" {
2263            self.current_is_https = false;
2264            self.current_host = String::from("localhost");
2265            self.current_path = String::from(path);
2266            self.current_url_with_hash = alloc::format!("http://localhost{}", path);
2267
2268            let clean_path = path.strip_prefix('/').unwrap_or(path);
2269            if clean_path == "home" || clean_path.is_empty() {
2270                self.title = String::from("AtmOS Browser");
2271                let html = HOME_HTML;
2272                self.parse_and_layout(html, None, self.top_offset, self.win_w, self.win_h);
2273                self.dirty = true;
2274                self.dirty_reason = "mod.rs:1513";
2275            } else {
2276                let actual_path = if path.starts_with('/') {
2277                    String::from(path)
2278                } else {
2279                    alloc::format!("/{}", path)
2280                };
2281                // 【2026-08-25 バグ修正】以前は `FS_LOCK` を保持したまま
2282                // `parse_and_layout()` を呼んでいた。
2283                //
2284                // レイアウトは `<img>` の寸法解決(`get_replaced_element_size`)
2285                // から FS を読み、JS は `localStorage` の書き出しから FS を書く。
2286                // どちらも `FS_LOCK` を取るが、`spin::Mutex` は**再入できない**。
2287                // つまり画像 1 枚あるローカルページを開くだけで自分自身と
2288                // 取り合って固まる。ロックの保持時間が長いほど、
2289                // 「保持中に何を呼んでいるか」が見えなくなる。
2290                //
2291                // **読み込みだけを番人の下に置き、レイアウトは外へ出す**。
2292                let loaded_res = {
2293                    let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
2294                    crate::kernel::fs::get_fs().read_file_checked(&actual_path)
2295                };
2296                match loaded_res {
2297                    Ok(Some((_meta, content))) => {
2298                        if let Ok(html) = core::str::from_utf8(&content) {
2299                            self.title = alloc::format!("Local: {}", clean_path);
2300                            self.parse_and_layout(html, None, self.top_offset, self.win_w, self.win_h);
2301                            self.dirty = true;
2302                            self.dirty_reason = "mod.rs:1525";
2303                        } else {
2304                            let err_html = alloc::format!("<html><title>Load Error</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>UTF-8 Decode Failed</h1><p>File '{}' is not valid UTF-8.</p></body></html>", actual_path);
2305                            self.title = String::from("Load Error");
2306                            self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2307                            self.dirty = true;
2308                            self.dirty_reason = "mod.rs:1530";
2309                        }
2310                    }
2311                    Ok(None) => {
2312                        let err_html = alloc::format!("<html><title>Not Found</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>404 Not Found</h1><p>Local file '{}' not found in SylFS.</p></body></html>", actual_path);
2313                        self.title = String::from("404 Not Found");
2314                        self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2315                        self.dirty = true;
2316                        self.dirty_reason = "mod.rs:1536";
2317                    }
2318                    Err(e) => {
2319                        let err_html = alloc::format!("<html><title>Read Error</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>Failed to read file</h1><p>Local file '{}' could not be read: {}</p></body></html>", actual_path, e);
2320                        self.title = String::from("Read Error");
2321                        self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2322                        self.dirty = true;
2323                        self.dirty_reason = "mod.rs:1542";
2324                    }
2325                }
2326            }
2327            return;
2328        }
2329
2330        // 【2026-10-17】youtube.com を内蔵の生成ページ(`youtube.rs`、動画元は存在しない
2331        // `watch?v=ID.mp4`)へ差し替える分岐を外した(利用者の判断)。本物の視聴ページを取得し、
2332        // YouTube 自身の JS を実行する。
2333
2334        self.current_is_https = is_https;
2335        self.current_host = String::from(host);
2336        self.current_path = String::from(path);
2337        // 新ページ読込でフラグメントはリセット(アンカーナビの hashchange 基準を同期)。
2338        let scheme0 = if is_https { "https://" } else { "http://" };
2339        self.current_url_with_hash = alloc::format!("{}{}{}", scheme0, host, path);
2340
2341        let schema = if is_https { "https://" } else { "http://" };
2342        crate::info!(
2343            "BROWSER: Loading page {} {}{}{} (Async)",
2344            method,
2345            schema,
2346            host,
2347            path
2348        );
2349
2350        self.loading = true;
2351        self.loading_tick = 0;
2352
2353        let req = AsyncLoadRequest {
2354            owner: self.engine_id,
2355            group: crate::kernel::scheduler::current_mem_group(),
2356            is_https,
2357            host: String::from(host),
2358            path: String::from(path),
2359            method: String::from(method),
2360            body,
2361            referer,
2362            status: 1, // 処理中
2363            result_body: None,
2364            result_dom: None,
2365            error_msg: None,
2366        };
2367
2368        let need_spawn = {
2369            let mut lock = ASYNC_LOAD.lock();
2370            // 同じタブの未消費リクエストは置換(連続ナビゲーションで古い結果を捨てる)
2371            lock.requests.retain(|r| r.owner != self.engine_id);
2372            lock.requests.push(req);
2373            if !lock.thread_active {
2374                lock.thread_active = true;
2375                true
2376            } else {
2377                false
2378            }
2379        };
2380
2381        // ローダースレッドが止まっている時だけ起動(多重起動を防ぐ)
2382        if need_spawn {
2383            // 【2026-08-05 バグ修正】`spawn` はヒープ不足で **0 を返す**。
2384            // `thread_active = true` を先に立てているので、失敗したまま
2385            // 戻さないと「ローダーは居ないのに稼働中」になり、
2386            // **以後メイン HTML の読み込みが永久に始まらない**
2387            // (`need_spawn` が二度と真にならない)。
2388            // 組をまたいで使う共有のワーカーなので組 0 で起こす(TODO R2 (c)・R5 の残り (a))。
2389            let pid = crate::kernel::scheduler::spawn_shared_with_stack(
2390                async_load_thread_entry,
2391                crate::kernel::scheduler::Priority::High,
2392                "browser_loader",
2393                crate::kernel::scheduler::LARGE_STACK_SIZE,
2394            );
2395            if pid == 0 {
2396                crate::warn!("[NET] ローダースレッドを起動できません(ヒープ不足)");
2397                ASYNC_LOAD.lock().thread_active = false;
2398            }
2399        }
2400        self.dirty = true;
2401        self.dirty_reason = "mod.rs:1595";
2402    }
2403
2404    pub fn set_dom_content(&mut self, id: &str, val: &str) {
2405        self.dom_contents
2406            .insert(String::from(id), String::from(val));
2407        let html = self.last_html.clone();
2408        let top_offset = self.top_offset;
2409        let win_w = self.win_w;
2410        let win_h = self.win_h;
2411        self.parse_and_layout(&html, None, top_offset, win_w, win_h);
2412        self.dirty = true;
2413        self.dirty_reason = "mod.rs:1606";
2414    }
2415
2416    // 戻るボタンの処理
2417    pub fn go_back(&mut self, _top_offset: i32) {
2418        // SPA pushState で積んだ履歴を優先して戻る(ページリロードなし)。
2419        if self.js_runtime.has_spa_back() {
2420            if let Some(url) = self.js_runtime.spa_go_back() {
2421                // URL からホスト/パスを更新して表示を合わせる(リロードはしない)。
2422                let (is_https, host, path) = self.resolve_url_parts(&url);
2423                self.current_is_https = is_https;
2424                self.current_host = host;
2425                self.current_path = path;
2426                self.dirty = true;
2427                self.dirty_reason = "mod.rs:1619";
2428            }
2429            return;
2430        }
2431        // 実ページ遷移の履歴から戻る。
2432        if let Some((prev_is_https, prev_host, prev_path)) = self.history.pop() {
2433            self.forward_history.push((
2434                self.current_is_https,
2435                self.current_host.clone(),
2436                self.current_path.clone(),
2437            ));
2438            self.load_page_with_method(prev_is_https, &prev_host, &prev_path, false, "GET", None);
2439        }
2440    }
2441
2442    pub fn go_forward(&mut self, _top_offset: i32) {
2443        // SPA forward 履歴を優先して進む。
2444        if self.js_runtime.has_spa_forward() {
2445            if let Some(url) = self.js_runtime.spa_go_forward() {
2446                let (is_https, host, path) = self.resolve_url_parts(&url);
2447                self.current_is_https = is_https;
2448                self.current_host = host;
2449                self.current_path = path;
2450                self.dirty = true;
2451                self.dirty_reason = "mod.rs:1642";
2452            }
2453            return;
2454        }
2455        // 実ページ遷移の forward 履歴から進む。
2456        if let Some((fwd_is_https, fwd_host, fwd_path)) = self.forward_history.pop() {
2457            self.history.push((
2458                self.current_is_https,
2459                self.current_host.clone(),
2460                self.current_path.clone(),
2461            ));
2462            self.load_page_with_method(fwd_is_https, &fwd_host, &fwd_path, false, "GET", None);
2463        }
2464    }
2465
2466    /// JS の form.reset() が積んだリセット要求を処理する。JS 実行後にホストが呼ぶ。
2467    /// 戻り値: 実際にリセットしたか。
2468    pub fn process_pending_reset(&mut self) -> bool {
2469        match self.js_runtime.take_pending_reset() {
2470            Some(fi) => {
2471                self.reset_form_node(fi);
2472                true
2473            }
2474            None => false,
2475        }
2476    }
2477
2478    pub fn can_go_back(&self) -> bool {
2479        !self.history.is_empty()
2480    }
2481    pub fn can_go_forward(&self) -> bool {
2482        !self.forward_history.is_empty()
2483    }
2484
2485    /// JS の history.back/forward/go() が積んだナビゲーション要求を処理する。
2486    /// JS 実行(onclick / イベントリスナ)後にホストが呼ぶ。実ナビ後に popstate を発火。
2487    /// 戻り値: 実際にナビゲートしたか(呼び元がアドレスバー更新等に使う)。
2488    pub fn process_pending_nav(&mut self, top_offset: i32) -> bool {
2489        let delta = self.js_runtime.take_pending_nav();
2490        if delta == 0 {
2491            return false;
2492        }
2493        let mut navigated = false;
2494        if delta < 0 {
2495            for _ in 0..(-delta) {
2496                if !self.can_go_back() {
2497                    break;
2498                }
2499                self.go_back(top_offset);
2500                navigated = true;
2501            }
2502        } else {
2503            for _ in 0..delta {
2504                if !self.can_go_forward() {
2505                    break;
2506                }
2507                self.go_forward(top_offset);
2508                navigated = true;
2509            }
2510        }
2511        if navigated {
2512            // 新ページURLを JS の location に反映してから popstate を発火。
2513            let url = self.get_url();
2514            self.js_runtime.set_page_url(&url);
2515            self.js_runtime.fire_popstate();
2516        }
2517        navigated
2518    }
2519
2520    /// location への代入や assign/replace/reload が積んだナビゲーション要求を処理する。
2521    /// ホストが JS 実行後(on_mouse / on_key / タイマ後など)に呼ぶ。戻り値は遷移したか否か。
2522    pub fn process_pending_location(&mut self, top_offset: i32) -> bool {
2523        let req = self.js_runtime.take_pending_location();
2524        let (url, mode) = match req {
2525            Some(v) => v,
2526            None => return false,
2527        };
2528        match mode.as_str() {
2529            // 同一ページ内フラグメント。フルリロードせず hashchange 経路へ。
2530            "hash" => {
2531                let frag = match url.split_once('#') {
2532                    Some((_, f)) => alloc::format!("#{}", f),
2533                    None => String::from("#"),
2534                };
2535                self.navigate_to_fragment(&frag);
2536                true
2537            }
2538            // 履歴を置換して遷移(save_history=false)。
2539            "replace" => {
2540                let (is_https, host, path) = self.resolve_url_parts(&url);
2541                self.load_page(is_https, &host, &path, false, top_offset);
2542                let new_url = self.get_url();
2543                self.js_runtime.set_page_url(&new_url);
2544                true
2545            }
2546            // 現在ページの再読込。
2547            "reload" => {
2548                let is_https = self.current_is_https;
2549                let host = self.current_host.clone();
2550                let path = self.current_path.clone();
2551                self.load_page(is_https, &host, &path, false, top_offset);
2552                true
2553            }
2554            // 通常の遷移(履歴に積む)。href 代入 / assign(url)。
2555            _ => {
2556                self.navigate_to_href(&url, top_offset);
2557                let new_url = self.get_url();
2558                self.js_runtime.set_page_url(&new_url);
2559                true
2560            }
2561        }
2562    }
2563}