Skip to main content

atmos/os_lib/web_engine/
frames.rs

1//! iframe の入れ子の文書(子フレーム)。
2//!
3//! 【2026-10-17】従来の iframe はプレビュー(OGP カード)を描くだけだった。iframe ごとに
4//! 独立した `WebEngine`(文書・JS・レイアウト)を持たせ、iframe の矩形を窓として
5//! `WebEngine::draw` を呼ぶ。読み込み・スクリプト・タイマーは子の `draw` が自分で進める
6//! (最上位のタブと同じ経路)。文書の要求には埋め込み元ページの `Referer` を付ける
7//! (`referrer::referrer_for`。YouTube の埋め込みはこれが無いとエラー 153 になる)。
8
9use alloc::boxed::Box;
10use alloc::collections::BTreeMap;
11use alloc::format;
12use alloc::string::String;
13
14use super::WebEngine;
15use crate::kernel::draw;
16
17/// 入れ子の深さの上限(iframe の中の iframe の中の…)。
18pub(crate) const MAX_FRAME_DEPTH: u32 = 2;
19/// 1 つの文書が持つ子フレーム数の上限(それぞれが JS とレイアウトを持つため)。
20pub(crate) const MAX_FRAMES_PER_DOC: usize = 4;
21/// これ以下の幅・高さの iframe は読み込まない(追跡用の 1px iframe 等)。
22pub(crate) const MIN_FRAME_SIZE: i32 = 8;
23
24/// 埋め込み元ページ(子フレームを持つ側)の情報。
25pub(crate) struct FrameParent<'a> {
26    pub is_https: bool,
27    pub host: &'a str,
28    pub path: &'a str,
29    pub depth: u32,
30}
31
32/// iframe の `src` を子フレームで読み込む絶対 URL にする。読み込まないもの
33/// (空・`about:`・`javascript:`・`data:` 等)は None。
34pub(crate) fn frame_url(parent: &FrameParent<'_>, src: &str) -> Option<String> {
35    let src = src.trim();
36    if src.is_empty() {
37        return None;
38    }
39    if src.starts_with("https://") || src.starts_with("http://") {
40        return Some(String::from(src));
41    }
42    let scheme = if parent.is_https { "https:" } else { "http:" };
43    if let Some(rest) = src.strip_prefix("//") {
44        return Some(format!("{}//{}", scheme, rest));
45    }
46    if src.contains(':') && !src.starts_with('/') {
47        // about:blank / javascript: / data: など(相対パス中の ':' は '/' より後ろにしか来ない想定)。
48        let before_slash = src.split('/').next().unwrap_or("");
49        if before_slash.contains(':') {
50            return None;
51        }
52    }
53    let base = format!("{}//{}{}", scheme, parent.host, parent.path);
54    Some(super::url_resolve::resolve_url(&base, src))
55}
56
57/// 子フレームのキー(文書内で何番目の iframe か+URL。src が変われば別の文書)。
58/// 要素 id は再レイアウトで変わり得る(自動採番)ので使わない。
59pub(crate) fn frame_key(ordinal: usize, url: &str) -> String {
60    format!("{}|{}", ordinal, url)
61}
62
63/// 画面の左・上にはみ出した iframe の可視領域クリップ矩形 `(cx0, cy0, cx1, cy1)` を計算する。
64/// 完全画面外なら `None` を返す。
65pub(crate) fn compute_frame_visible_rect(
66    x: i32,
67    y: i32,
68    w: i32,
69    h: i32,
70) -> Option<(u32, u32, u32, u32)> {
71    if x + w <= 0 || y + h <= 0 || w <= 0 || h <= 0 {
72        return None;
73    }
74    let cx0 = x.max(0) as u32;
75    let cy0 = y.max(0) as u32;
76    let cx1 = (x + w).max(0) as u32;
77    let cy1 = (y + h).max(0) as u32;
78    if cx1 <= cx0 || cy1 <= cy0 {
79        return None;
80    }
81    Some((cx0, cy0, cx1, cy1))
82}
83
84/// 子フレームを(無ければ作って読み込みを始め)iframe の矩形 `(x, y, w, h)` に描く。
85/// 描けなかった(上限・小さすぎる)ときは false(呼び出し側はプレビューを描く)。
86#[allow(clippy::too_many_arguments)]
87pub(crate) fn draw_child_frame(
88    frames: &mut BTreeMap<String, Box<WebEngine>>,
89    parent: &FrameParent<'_>,
90    key: &str,
91    url: &str,
92    screen: &draw::Screen,
93    x: i32,
94    y: i32,
95    w: i32,
96    h: i32,
97) -> bool {
98    if parent.depth >= MAX_FRAME_DEPTH || w < MIN_FRAME_SIZE || h < MIN_FRAME_SIZE {
99        return false;
100    }
101    if !frames.contains_key(key) {
102        if frames.len() >= MAX_FRAMES_PER_DOC {
103            return false;
104        }
105        let mut child = Box::new(WebEngine::new());
106        child.frame_depth = parent.depth + 1;
107        child.js_runtime.set_frame_depth(child.frame_depth);
108        child.win_w = w as u32;
109        child.win_h = h as u32;
110        child.top_offset = 0;
111        let (to_https, to_host) = split_scheme_host(url);
112        let referer = super::referrer::referrer_for(parent.is_https, parent.host, parent.path, to_https, to_host);
113        child.load_frame(url, referer);
114        frames.insert(String::from(key), child);
115    }
116    let Some(child) = frames.get_mut(key) else { return false };
117    // iframe の大きさが変わったら子の文書を組み直す(最上位タブのウィンドウ変更と同じ)。
118    if child.win_w != w as u32 || child.win_h != h as u32 {
119        child.win_w = w as u32;
120        child.win_h = h as u32;
121        let html = child.last_html.clone();
122        if !html.is_empty() {
123            child.parse_and_layout(&html, None, 0, w as u32, h as u32);
124        }
125    }
126    // HTML がまだ読み込まれていない(ロード中または取得失敗)場合は false を返し、
127    // 呼び出し元の OGP プレビューカード等の代替表示にフォールバックさせる。
128    if child.last_html.is_empty() {
129        return false;
130    }
131    // 画面外(左端または上端を完全に超えて見えない)場合はスキップ
132    let Some((cx0, cy0, cx1, cy1)) = compute_frame_visible_rect(x, y, w, h) else {
133        return true;
134    };
135
136    // 画面の左・上へはみ出した iframe の描画:
137    // 可視領域を clip して、原点をそのまま (x as u32, y as u32) として子の draw に渡す。
138    // 描画エンジン内部は (win_x as i32 + el_x) で計算するため、負の原点でも
139    // 正しい画面座標に展開され、画面内領域のみがクリップを通過して正確に描画される。
140    screen.push_clip(cx0, cy0, cx1, cy1);
141    child.draw(screen, x as u32, y as u32, w as u32, h as u32, 0);
142    screen.pop_clip();
143    true
144}
145
146/// `https://host/...` → `(true, "host")`。
147fn split_scheme_host(url: &str) -> (bool, &str) {
148    let (https, rest) = if let Some(r) = url.strip_prefix("https://") {
149        (true, r)
150    } else {
151        (false, url.strip_prefix("http://").unwrap_or(url))
152    };
153    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
154    (https, rest.get(..end).unwrap_or(rest))
155}