diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml new file mode 100644 index 0000000..fd00106 --- /dev/null +++ b/.github/workflows/bench.yml @@ -0,0 +1,71 @@ +name: Bench (manual) + +# 手动触发的性能基准(nexty-chrome pipeline bench)。不挂 push/PR: +# 全页光栅的滚动风暴很重,且绝对数字依赖 runner 硬件。本作业的价值是 +# ①固定的可复现环境(同 runner 类内趋势可比)②机器无关的回归断言 +# (resize 合帧 runs、滚动 emit=0、shape≈1×chunks、metrics≤10—— +# bench 内置断言,破坏即非零退出翻红)③数字入 Job Summary 与 artifact 存档。 +# 本地完整基线仍是 docs/2026-10-25-perf-baseline.md(Windows 10 实测), +# CI runner 的绝对数字与它不可直接对比。 + +on: + workflow_dispatch: + inputs: + scroll_frames: + description: "滚动风暴帧数(全页光栅每帧 10s+,小帧数控成本;0 = 跳过滚动风暴;本地基线口径为 50)" + required: false + default: "5" + +concurrency: + group: bench-manual + cancel-in-progress: false + +env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + +jobs: + bench: + name: pipeline bench + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - name: Install system dependencies (winit / wgpu link deps + CJK fonts) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + libx11-dev libxi-dev libgl1-mesa-dev libasound2-dev libpulse-dev \ + libtss2-dev libxkbcommon-dev libwayland-dev libxcb1-dev \ + libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \ + libxrandr-dev libdbus-1-dev libdrm-dev libgbm-dev \ + libegl1-mesa-dev libgles2-mesa-dev libfontconfig1-dev \ + vulkan-tools libvulkan-dev \ + fonts-noto-cjk + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Run pipeline bench + env: + BENCH_MODE: "1" + BENCH_SCROLL_FRAMES: ${{ inputs.scroll_frames }} + run: | + set -o pipefail + cargo bench -p nexty-chrome --bench pipeline 2>&1 | tee bench-output.txt + - name: Append to job summary + if: always() + run: | + { + echo "## pipeline bench" + echo "" + echo "runner: $(uname -m), $(nproc) cores, scroll_frames=${{ inputs.scroll_frames }}" + echo "" + echo '```' + cat bench-output.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: bench-output + path: bench-output.txt + if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 6bfa2a7..57183c6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,18 +12,18 @@ MusKitty 的**不造轮子**分支。MusKitty 从零手写浏览器核心模块 已落地八层(全部骨架 crate 就位,管线端到端可跑): -- `nexty-dom`(v0.1.3)——自研 arena DOM:节点数据层、树变更算法(pre-insert/insert/remove/replace/clone/normalize)与文档模式控制。**输入边界防护**:节点携带树深度(`link_before` 单点维护、重挂重算、模板内容片段独立起算),`MAX_TREE_DEPTH = 512` 与 `Document::depth` 供下游防线使用。 +- `nexty-dom`(v0.1.4)——自研 arena DOM:节点数据层、树变更算法(pre-insert/insert/remove/replace/clone/normalize)与文档模式控制。**事件模型(K1)**:`event` 模块(feature `event`)——`Event`/`EventTarget`(监听器存 Document 侧 `ListenerRegistry`,句柄身份)、捕获/target/冒泡三阶段传播(target 上捕获与非捕获监听器按注册顺序混触发)、`stopPropagation`/`stopImmediatePropagation`/`preventDefault`(DOM §2.9 简化档:无 shadow/trusted/passive/once),数据面 UIEvent/MouseEvent/KeyboardEvent/WheelEvent/FocusEvent(FocusEvent 仅类型面,K10 补派发点),`EventLoop` FIFO 任务队列(派发中 post 不重入,由 `TaskContext` 类型结构性保证),生命周期事件类型 `DOMContentLoaded`/`load`。**输入边界防护**:节点携带树深度(`link_before` 单点维护、重挂重算、模板内容片段独立起算),`MAX_TREE_DEPTH = 512` 与 `Document::depth` 供下游防线使用。 - `nexty-html`(v0.1.5)——html5ever 的 `TreeSink` 桥接到 arena DOM,提供 `parse_document` 与 `parse_fragment`(含片段上下文命名空间);子资源清单收集(`collect_style_resources` 收集 `` 与 `\ + \ +

hi

"; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + assert_eq!(sub.stylesheets.len(), 2, "inline + 外链按源顺序"); + assert_eq!(sub.images.len(), 1, "图片已解码"); + + // 组装页面 → 布局 → Scene + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // Scene 指令序列:图片指令 + 图片池 + 文本 + let images_drawn: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::DrawImage { rect, image } => Some((*rect, *image)), + _ => None, + }) + .collect(); + assert_eq!(images_drawn.len(), 1, "一张图片一条 DrawImage"); + let (rect, index) = images_drawn[0]; + assert_eq!(scene.images.len(), 1, "图片池一份像素"); + assert_eq!(index, 0); + assert!(approx(rect.width, 10.0) && approx(rect.height, 10.0)); + // 图片落点在地址栏下方内容区(y > 0)且在文本之后 + assert!(rect.y > 0.0); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本指令仍在" + ); + + // 级联顺序:外链表的 blue 压过 inline 的 red —— 光栅化像素验证 + let rasterizer = nexty_paint::VelloCpuRasterizer::new(); + let pixmap = rasterizer + .rasterize( + &scene, + Viewport { + width: 400, + height: 300, + }, + ) + .expect("rasterize"); + let pixel = pixmap + .pixel(rect.x as u32 + 5, rect.y as u32 + 5) + .expect("像素在画布内"); + // vello_cpu 预乘/反预乘往返有 ±1 量化误差 + assert!( + pixel[0] <= 1 && pixel[1] <= 1 && pixel[2] >= 254 && pixel[3] == 255, + "1×1 PNG 的蓝色落在目标矩形内,实际 {pixel:?}" + ); +} + +/// 单个子资源失败不影响其余渲染(降级而非白屏)。 +#[test] +fn failing_subresources_degrade_without_blocking_render() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/broken.css", 500); + fetcher.fail("https://page.test/lost.png", 404); + fetcher.serve("https://page.test/junk.png", b"not an image"); + let html = "\ +

still here

"; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + assert!(sub.stylesheets.is_empty(), "失败的外链表不参与级联"); + assert!(sub.images.is_empty(), "失败图片无像素"); + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + // 文本照常渲染;无图片指令(失败图片不产生 DrawImage) + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本内容不受子资源失败影响" + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawImage { .. })), + "无像素的图片不下发指令" + ); +} + +/// 抓取不到自然尺寸的图片:布局回退默认对象尺寸,失败图片无指令。 +#[test] +fn image_natural_size_flows_from_decoding_into_layout() { + // 3×2 蓝色 PNG:无 width/height 属性时按自然尺寸 + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 3, + 2, + image::Rgba([10, 20, 30, 255]), + )) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .expect("encode"); + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/n.png", &png); + let html = ""; + + let (_, sub) = load_page_with_resources(&fetcher, "https://page.test/index.html", html); + let document = nexty_html::parse_document(html, ParseOptions::default()); + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let scene = pipeline::build_scene(&page, &root); + + let drawn: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::DrawImage { rect, .. } => Some(*rect), + _ => None, + }) + .collect(); + assert_eq!(drawn.len(), 1); + assert!( + approx(drawn[0].width, 3.0) && approx(drawn[0].height, 2.0), + "自然尺寸 3×2 从解码流入布局,实际 {:?}", + (drawn[0].width, drawn[0].height) + ); +} + +// ---- 不可信输入边界加固:全链回归(本轮验收旗舰用例) ---- + +use nexty_dom::MAX_TREE_DEPTH; +use nexty_dom::NodeKind; +use nexty_layout::Fragment; + +/// CRC-32(IEEE,PNG chunk 校验用)。 +fn crc32(data: &[u8]) -> u32 { + let mut crc: u32 = 0xFFFF_FFFF; + for &byte in data { + crc ^= u32::from(byte); + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc +} + +/// 真实 1×1 PNG,IHDR 尺寸改写为 65535×65535(重算 CRC)——头部声明巨图、 +/// 像素数据只有 1×1 的攻击样本。 +fn declared_huge_png() -> Vec { + let mut png = tiny_png(); + png[16..20].copy_from_slice(&65535u32.to_be_bytes()); + png[20..24].copy_from_slice(&65535u32.to_be_bytes()); + let crc = crc32(&png[12..29]); + png[29..33].copy_from_slice(&crc.to_be_bytes()); + png +} + +/// 片段树所有几何值必须有限(污染即在此可见)。 +fn assert_geometry_finite(fragment: &Fragment) { + let border_box = fragment.border_box; + assert!( + border_box.x.is_finite() + && border_box.y.is_finite() + && border_box.width.is_finite() + && border_box.height.is_finite(), + "片段几何有限,实际 {border_box:?}" + ); + for line in &fragment.lines { + assert!(line.baseline.is_finite() && line.height.is_finite()); + for run in &line.runs { + assert!( + run.glyphs + .iter() + .all(|glyph| glyph.x.is_finite() && glyph.advance.is_finite()) + ); + } + for image in &line.images { + assert!( + image.x.is_finite() + && image.y.is_finite() + && image.width.is_finite() + && image.height.is_finite() + ); + } + } + for child in &fragment.children { + assert_geometry_finite(child); + } +} + +/// 组合攻击面(深嵌套 + 巨数属性 + 巨图声明 + 巨数 CSS)走完整管线: +/// parse → 子资源抓取(含解码预检)→ 级联 → 布局 → TextMap → 标题/资源清单 +/// ——不崩、有限时间、几何有限。 +/// +/// 嵌套规模取上限 2 倍(1000 层):html5ever 对每个起始标签都在 open +/// elements 栈上线性扫描(O(深度²)),更大语料在测试里不可行(实测 +/// debug 1000 层 ≈ 0.8s、2000 层 ≈ 3s);截断语义已由 nexty-html 单测钉住。 +#[test] +fn hardening_full_chain_survives_adversarial_page() { + let huge = "9".repeat(45); + let mut html = String::from( + "加固回归\ + \ + ", + ); + // 深嵌套部分:超上限,解析入口截断 + html.push_str(&"
".repeat(1_000)); + html.push_str(&"
".repeat(1_000)); + // 浅层部分:巨数尺寸属性 + 指向巨图声明的 (在截断预算内存活) + html.push_str(&format!( + "

before after

" + )); + + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/huge.png", &declared_huge_png()); + + // parse → 子资源抓取(解码预检在 fetch 阶段拒绝巨图声明) + let (document, sub) = + load_page_with_resources(&fetcher, "https://page.test/index.html", &html); + assert!(sub.images.is_empty(), "巨图声明预检被拒,无像素"); + + // 深度截断:树中任意节点 ≤ MAX_TREE_DEPTH,深嵌套部分只保留预算内的层 + let mut max_depth = 0u32; + let mut div_count = 0usize; + let mut stack = vec![document.root()]; + while let Some(id) = stack.pop() { + max_depth = max_depth.max(document.depth(id)); + if let Some(NodeKind::Element(data)) = document.node(id) + && data.name == "div" + { + div_count += 1; + } + for child in document.children(id) { + stack.push(child); + } + } + assert!((max_depth as usize) <= MAX_TREE_DEPTH, "深度有界"); + assert_eq!(div_count, MAX_TREE_DEPTH - 2, "html/body 之外只保留预算内 div"); + + // 标题与资源清单在全链末端仍可用 + assert_eq!(pipeline::document_title(&document).as_deref(), Some("加固回归")); + assert_eq!(nexty_html::collect_image_resources(&document).len(), 1); + + // 级联 → 布局 → TextMap:页面可布局且几何全部有限 + let page = pipeline::build_page(document, sub.stylesheets, sub.images); + let shaper = ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); + let text_map = nexty_layout::TextMap::new(&root); + let _ = &text_map; + assert_geometry_finite(&root); + + // 显示列表可构建:文本指令在(浅层段落的 before/after) + let scene = pipeline::build_scene(&page, &root); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "文本照常下发" + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawImage { .. })), + "巨图声明无像素、无 DrawImage" + ); +} diff --git a/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source new file mode 100644 index 0000000..a5be959 --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-state/session_164476f9d97ffaabe4f6dc9715b6aad5.mvmhprgt-42404-bfa3e379d5.baseline/2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542.source @@ -0,0 +1,59 @@ +[package] +name = "nexty-chrome" +description = "Nexty 浏览器外壳:窗口、输入、导航与自绘 UI" +version = "0.1.18" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[features] +# 默认开启全部已实现能力。`window` 是二进制外壳本体(winit+wgpu), +# 关闭后本 crate 只剩可无头测试的纯逻辑模块(history/ui/scrollbar/pipeline)。 +default = [ + "pipeline", "resources", "render", "history", "ui", "scrollbar", "selection", "window", +] +# 导航管线:HTML → 级联 → 布局 → 片段树 → paint 显示列表(纯逻辑,可测试)。 +pipeline = [] +# 子资源清单解析、并发抓取与解码编排(纯逻辑,可测试)。 +resources = [] +# 渲染隔离线程:panic 兜底,线程存活可继续服务。 +render = [] +# 会话历史栈(纯逻辑,可测试)。 +history = [] +# 自绘工具带状态机(纯逻辑,可测试)。 +ui = [] +# 滚动几何与拖拽状态机(纯逻辑,可测试)。 +scrollbar = [] +# 页面文本选区状态机(纯逻辑)+ 复制到系统剪贴板。 +selection = ["pipeline", "dep:arboard"] +# 浏览器外壳本体:winit 事件循环 + wgpu 呈现(`run()` 入口)。 +# 依赖 winit / wgpu / pollster 与下层各 crate,故隐含它们。 +window = ["pipeline", "resources", "render", "history", "ui", "scrollbar", "selection", + "dep:winit", "dep:wgpu", "dep:pollster"] + +[dependencies] +nexty-dom = { path = "../nexty-dom", version = "0.1.0" } +nexty-html = { path = "../nexty-html", version = "0.1.0" } +nexty-css = { path = "../nexty-css", version = "0.1.0" } +nexty-layout = { path = "../nexty-layout", version = "0.1.0" } +nexty-text = { path = "../nexty-text", version = "0.1.0" } +nexty-paint = { path = "../nexty-paint", version = "0.1.0" } +nexty-network = { path = "../nexty-network", version = "0.1.0" } +winit = { version = "0.30.13", optional = true } +wgpu = { version = "29", optional = true } +# wgpu 的异步初始化在 winit 事件循环外的同步入口完成 +pollster = { version = "0.4", optional = true } +# 系统剪贴板(选区复制)。只要文本:关闭 default 的 image-data,避免引入 +# 图片剪贴板后端;选型与边界见 docs/decisions/2026-10-23-clipboard.md。 +arboard = { version = "3.7", default-features = false, optional = true } + +[dev-dependencies] +# 仅测试用:构造 PNG 字节喂给资源编排测试(与 nexty-paint 同一依赖) +image = { version = "0.25.10", default-features = false, features = ["png"] } + +# 浏览器可执行入口,仅在 `window` feature 下构建(关闭 window 时无窗口可启)。 +[[bin]] +name = "nexty" +path = "src/bin/nexty.rs" +required-features = ["window"] diff --git a/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json b/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json new file mode 100644 index 0000000..70a3aad --- /dev/null +++ b/crates/nexty-chrome/.mimosa/hook-status/session_164476f9d97ffaabe4f6dc9715b6aad5-5e056c09de.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-10-24T15:03:17.639Z", + "sessionId": "session_164476f9d97ffaabe4f6dc9715b6aad5", + "event": "PostToolUse", + "toolName": "Edit", + "file": "Cargo.toml", + "outcome": "inconclusive", + "coverage": "partial", + "findingCount": 0, + "durationMs": 11, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/crates/nexty-chrome/Cargo.toml b/crates/nexty-chrome/Cargo.toml index 55a91cf..f1780c7 100644 --- a/crates/nexty-chrome/Cargo.toml +++ b/crates/nexty-chrome/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nexty-chrome" description = "Nexty 浏览器外壳:窗口、输入、导航与自绘 UI" -version = "0.1.25" +version = "0.1.30" edition.workspace = true license.workspace = true repository.workspace = true diff --git a/crates/nexty-chrome/benches/pipeline.rs b/crates/nexty-chrome/benches/pipeline.rs index 3afb8b2..3fd8ca5 100644 --- a/crates/nexty-chrome/benches/pipeline.rs +++ b/crates/nexty-chrome/benches/pipeline.rs @@ -44,6 +44,15 @@ const RESIZE_COUNT: usize = 20; const RESIZE_EVENTS_PER_FRAME: usize = 4; const SCROLL_FRAMES: usize = 50; +/// CI 可用 `BENCH_SCROLL_FRAMES` 覆盖滚动风暴帧数(全页光栅每帧 10s+, +/// CI 用小帧数控成本;0 = 跳过滚动风暴)。缺省 50(本地基线口径)。 +fn scroll_frames() -> usize { + std::env::var("BENCH_SCROLL_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(SCROLL_FRAMES) +} + /// 首屏各阶段耗时(ms)。 #[derive(Debug, Default, Clone, Copy)] struct StageMs { @@ -196,11 +205,11 @@ impl Corpus { ) } - /// 滚动风暴(M6 场景缓存后语义):同一布局下 `SCROLL_FRAMES` 个滚动 + /// 滚动风暴(M6 场景缓存后语义):同一布局下 `frames` 个滚动 /// 偏移经 [`pipeline::SceneCache`] 取页面坐标系场景(首帧后零 emit), /// emit 阶段 = 缓存命中 + [`nexty_paint::Scene::translated`] origin /// 平移。返回(平移中位数 ms,rasterize 中位数 ms,emit 次数)。 - fn scroll_storm(&self, shaper: &CountingShaper) -> (f64, f64, usize) { + fn scroll_storm(&self, shaper: &CountingShaper, frames: usize) -> (f64, f64, usize) { let document = nexty_html::parse_document(&self.html, ParseOptions::default()); let sheet = Stylesheet::parse(&self.css); let mut page = pipeline::build_page(document, vec![sheet], self.images.clone()); @@ -217,7 +226,7 @@ impl Corpus { let rasterizer = VelloCpuRasterizer::new(); let mut emit_samples = Vec::new(); let mut raster_samples = Vec::new(); - for frame in 0..SCROLL_FRAMES { + for frame in 0..frames { // 确定性偏移:137 步长在典型页高上打满全程 let scroll = if max_scroll > 0.0 { ((frame as u64) * 137) % (max_scroll as u64) + 1 @@ -259,6 +268,7 @@ fn run() { Corpus::new("image-heavy", image_heavy_html(), ""), ]; + let frames = scroll_frames(); for corpus in &corpora { // 首屏:阶段计时 + 单次布局的整形调用数(独立计数窗口) let stages = corpus.first_load(&shaper); @@ -274,12 +284,26 @@ fn run() { pipeline::recascade(&mut page, VIEWPORT); shaper.reset(); let _ = pipeline::layout_page(&page, &shaper, VIEWPORT.width).expect("layout"); + let (single_shapes, single_metrics) = (shaper.shape_calls(), shaper.metrics_calls()); println!( "[{}] single layout shaping: shape {} calls / {chunks} chunks = {:.2}x, metrics {} calls", corpus.name, - shaper.shape_calls(), - shaper.shape_calls() as f64 / chunks.max(1) as f64, - shaper.metrics_calls(), + single_shapes, + single_shapes as f64 / chunks.max(1) as f64, + single_metrics, + ); + // 机器无关断言(回归陷阱,破坏即 bench 非零退出——CI 据此翻红): + // 单次布局整形 ≈1×chunks(H4 逐 chunk 缓存)、metrics 探针 ≤10 + // (布局级 MetricsCache——基线 text-heavy 10 / rules 1 / image 1)。 + assert!( + single_shapes <= chunks + 1, + "[{}] shaping cache regression: {single_shapes} shape calls for {chunks} chunks (expect ≈1.0x)", + corpus.name + ); + assert!( + single_metrics <= 10, + "[{}] metrics cache regression: {single_metrics} probe calls (expect ≤10)", + corpus.name ); let (per_frame, runs, _events, shapes, metricses, total_events) = @@ -290,12 +314,32 @@ fn run() { RESIZE_EVENTS_PER_FRAME, shapes as f64 / chunks.max(1) as f64, ); - - let (emit, raster, emits) = corpus.scroll_storm(&shaper); - println!( - "[{}] scroll storm: {SCROLL_FRAMES} frames, emit count {emits} (must be 0 after initial build), translate median {emit:.3} ms, rasterize median {raster:.1} ms", - corpus.name, + // resize 合帧断言(M6):管线执行数 = 事件数 / 每帧事件比。 + assert_eq!( + runs, + RESIZE_COUNT / RESIZE_EVENTS_PER_FRAME, + "[{}] resize coalescing regression: {runs} pipeline runs for {total_events} events", + corpus.name ); + + if frames == 0 { + println!( + "[{}] scroll storm: skipped (BENCH_SCROLL_FRAMES=0)", + corpus.name + ); + } else { + let (emit, raster, emits) = corpus.scroll_storm(&shaper, frames); + println!( + "[{}] scroll storm: {frames} frames, emit count {emits} (must be 0 after initial build), translate median {emit:.3} ms, rasterize median {raster:.1} ms", + corpus.name, + ); + // 场景缓存断言(M6):首帧构建后统计窗口内 emit 必须为 0。 + assert_eq!( + emits, 0, + "[{}] scene cache regression: {emits} emits after initial build", + corpus.name + ); + } } } diff --git a/crates/nexty-chrome/src/app.rs b/crates/nexty-chrome/src/app.rs index ec2b9ef..f46afe4 100644 --- a/crates/nexty-chrome/src/app.rs +++ b/crates/nexty-chrome/src/app.rs @@ -1,8 +1,9 @@ //! winit + wgpu 呈现:窗口、输入转译与 Pixmap 上屏。 //! -//! 本模块是无法在无头环境自动化测试的薄胶水层:窗口创建、surface 配置、 -//! 纹理上传与 blit 呈现。所有可测试逻辑(管线、渲染线程、UI 状态机) -//! 都在其余模块并有单测覆盖。 +//! 本模块的 winit/GPU 胶水是无法在无头环境自动化测试的薄层:窗口创建、 +//! surface 配置、纹理上传与 blit 呈现。所有可测试逻辑(管线、渲染线程、 +//! UI 状态机)都在其余模块并有单测覆盖;交互事件接线与生命周期派发集中在 +//! 子模块 [`events`](纯函数部分有无头单测,K1 T3)。 //! //! 呈现路径:页面 + 地址栏 → Scene → [`RenderThread`](隔离线程 + //! `catch_unwind`)→ Pixmap → `wgpu` 纹理 → 全屏 `textureLoad` blit → @@ -11,8 +12,9 @@ use std::sync::Arc; use std::time::{Duration, Instant}; +use nexty_dom::{DeltaMode, NodeId}; use nexty_layout::{Fragment, TextMap}; -use nexty_network::{Method, NetworkError, NetworkFetcher, ReqwestFetcher}; +use nexty_network::{CachedFetcher, NetworkFetcher, ReqwestFetcher}; use nexty_paint::{Pixmap, Scene, Size}; use winit::application::ApplicationHandler; use winit::event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent}; @@ -27,6 +29,8 @@ use crate::scrollbar::{self, ScrollGeometry, Scrollbar, ScrollbarHit}; use crate::selection::{self, Selection}; use crate::ui::{self, AddressBar, BAR_HEIGHT, BarCommand, CaretDirection, UiEvent}; +mod events; + /// 滚轮一格(LineDelta 1.0)对应的滚动距离,px。 const WHEEL_LINE_PX: f32 = 40.0; @@ -55,20 +59,39 @@ impl std::error::Error for AppError {} /// 后台抓取完成后经事件代理送回的载荷。 enum BackgroundEvent { - /// 页面(含子资源:外链 CSS + 解码图片)就绪。载荷装箱(Page 较大, - /// 与单元变体并列时避免枚举整体膨胀)。 + /// 抓取数据面(HTML + 子资源字节/像素)就绪。载荷装箱(与单元变体 + /// 并列时避免枚举整体膨胀)。 PageLoaded(Box), + /// 字体字节就绪(K4 T3):注册进会话注册表,有新注册触发恰好一轮 + /// 重排 + 重绘。 + FontsReady(Box), /// 渲染线程完成一份光栅作业(异步呈现:主线程发请求即返回,不阻塞 /// 等待——巨页帧可达数十秒,阻塞会让窗口进入系统「无响应」状态并 /// 触发 WM_PAINT/WM_SIZE 重绘风暴)。 FrameReady, } +/// [`BackgroundEvent::FontsReady`] 的载荷(K4 T3):抓取成功的字体字节 + +/// 描述符。`url` 是发起抓取的导航 URL(跨页保护:页面已离开时只入库, +/// 不重排当前页)。 +struct FontsReadyPayload { + url: String, + fonts: Vec, +} + /// [`BackgroundEvent::PageLoaded`] 的载荷。 +/// +/// K1 起载荷只携带全 `Send` 数据面([`crate::resources::FetchedPageData`]): +/// `Document` 含监听器注册表(!Send)只能在主线程构建——后台线程只投 +/// 信号与字节,不触碰 Document。K3 T5 起后台编排同步完成(解析 + settle) +/// 后事件才到达,生命周期门控在到达点即满足,不再携带中途信号字段。 struct PageLoadedPayload { url: String, - /// 页面构建结果;错误携带用户可读信息。 - result: Result, + /// 文档 base:响应最终 URL(重定向落点);错误路径与请求 URL 同值 + /// (错误页无子资源,不参与查表)。 + base_url: String, + /// 抓取产物;错误携带用户可读信息。 + result: Result, } /// 启动浏览器窗口。阻塞直至窗口关闭。 @@ -102,11 +125,14 @@ struct Gpu { staging_cache: Option<((u32, u32, u32), Vec)>, } -/// 页面左键按下手势(链接目标在按下时解析,释放且未拖动才导航)。 +/// 页面左键按下手势(链接目标在按下时解析,释放且未拖动才导航; +/// 命中节点存入 `Press`,供 mousedown/mouseup/click 派发作目标)。 struct Press { x: f32, y: f32, link: Option, + /// mousedown 时命中测试的节点(无命中为 None,事件退回文档根)。 + node: Option, } /// 浏览器应用状态。 @@ -117,9 +143,14 @@ struct BrowserApp { renderer: Option, /// 网络接驳缝:后端可整体替换(reqwest 实现或其他 `NetworkFetcher`)。 fetcher: Option>, + /// @font-face 字体编排会话(K4 T3):会话级注册表 + 已注册 URL 集。 + fonts: crate::resources::FontOrchestrator, shaper: nexty_text::ParleyTextShaper, bar: AddressBar, history: History, + /// DOM 宏任务队列(K1):生命周期事件经 post_task 派发、 + /// `run_pending_tasks` 排空(FIFO,派发中 post 不重入)。 + dom_loop: nexty_dom::EventLoop, /// 滚动条交互状态(悬停 / 拖拽)。 scrollbar: Scrollbar, /// Alt 修饰键按住状态(后退/前进快捷键)。 @@ -168,15 +199,21 @@ struct BrowserApp { impl BrowserApp { fn new(proxy: EventLoopProxy) -> Self { + // 字体注册表先于整形器创建:整形器经 with_registry 接线(K4 T3), + // 此后 register 即生效、无需重建(nexty-text T2 语义)。 + let fonts = crate::resources::FontOrchestrator::new(); + let shaper = nexty_text::ParleyTextShaper::with_registry(fonts.registry()); Self { proxy, window: None, gpu: None, renderer: None, fetcher: None, - shaper: nexty_text::ParleyTextShaper::new(), + fonts, + shaper, bar: AddressBar::new("about:blank"), history: History::new("about:blank"), + dom_loop: nexty_dom::EventLoop::new(), scrollbar: Scrollbar::new(), alt_down: false, ctrl_down: false, @@ -230,9 +267,11 @@ impl BrowserApp { // 启动路径用 fail-fast:TLS 后端不可用时浏览器本就无法工作, // 带着半初始化的状态继续跑不如立刻退出(渲染路径才需要降级)。 // 整请求超时 30s:真实站点挂起时不无限占住加载状态。 - self.fetcher = Some(Arc::new( + // 抓取栈接 HTTP 内存缓存(K3 T4/T5):主文档与子资源共用同一实例, + // 同 URL 二次导航 / 重复子资源直接命中缓存,不再打网络。 + self.fetcher = Some(Arc::new(CachedFetcher::new( ReqwestFetcher::with_timeout(Duration::from_secs(30)).expect("network fetcher"), - )); + ))); self.show_blank(); window.request_redraw(); } @@ -241,6 +280,11 @@ impl BrowserApp { fn show_blank(&mut self) { self.bar.set_url("about:blank"); self.set_page(pipeline::load_page("", ""), true); + // 内部页生命周期:主线程本地解析完成、零子资源编排 = 立即 settle + self.dispatch_page_lifecycle(pipeline::PendingLifecycle { + dom_content_loaded: true, + load: true, + }); } /// 当前视口与内容对应的滚动几何;窗口未创建时为 `None`。 @@ -395,10 +439,27 @@ impl BrowserApp { /// 开始一次页面点击/选择手势。 fn begin_page_gesture(&mut self, x: f32, y: f32) { + let page_y = y - BAR_HEIGHT + self.scroll_y; + // 单次命中测试同时供事件目标与链接解析(hit_test_ex 结果 → 事件节点) + let hit = self + .root + .as_ref() + .and_then(|root| pipeline::hit_test_ex(root, x, page_y)); + let node = hit.map(|hit| hit.node); + let link = hit + .and_then(|hit| { + self.page + .as_ref() + .and_then(|page| pipeline::link_target(page, hit.node)) + }) + .and_then(|href| nexty_network::resolve(self.history.current(), &href).ok()); + // mousedown 先派发后默认:默认动作 = 开始选择手势(含地址栏失焦, + // 同浏览器 preventDefault mousedown 阻止焦点转移)。取消则手势不开始。 + if !self.dispatch_page_mouse(node, "mousedown", x, y, 1) { + return; + } // 页面点击让地址栏失焦:之后 Ctrl+A / Ctrl+C 作用于页面。 self.bar.blur(); - let page_y = y - BAR_HEIGHT + self.scroll_y; - let link = self.link_at(x, page_y); let position = self.text_map.as_ref().and_then(|map| map.hit(x, page_y)); let now = Instant::now(); let double_click = self.last_click.is_some_and(|(time, last_x, last_y)| { @@ -422,30 +483,25 @@ impl BrowserApp { } None => self.selection.clear(), } - self.press = Some(Press { x, y, link }); + self.press = Some(Press { x, y, link, node }); if let Some(window) = &self.window { window.request_redraw(); } } - /// 页面点命中的链接绝对地址(无链接或解析失败返回 `None`)。 - fn link_at(&self, x: f32, page_y: f32) -> Option { - self.root - .as_ref() - .and_then(|root| pipeline::hit_test(root, x, page_y)) - .and_then(|node| { - self.page - .as_ref() - .and_then(|page| pipeline::link_target(page, node)) - }) - .and_then(|href| nexty_network::resolve(self.history.current(), &href).ok()) - } - /// 导航:入历史栈并加载。 + /// + /// 地址栏输入与页面链接共用入口。地址栏输入在这里做 URL 规范化:无 + /// scheme 补 `http://`(HTTP-first,决策见 + /// `docs/decisions/2026-10-31-addressbar-url.md` 与 + /// [`crate::resources::normalize_address_bar_input`]);链接 href 已由 + /// `resolve` 按文档 base 绝对化,规范化对其无操作。历史栈存规范化后 + /// 的 URL:后退/前进重放的即实际导航目标。 fn navigate(&mut self, url: &str) { - self.history.push(url.to_owned()); + let url = crate::resources::normalize_address_bar_input(url); + self.history.push(url.clone()); self.sync_history_flags(); - self.load(url); + self.load(&url); } /// 后退/前进(历史栈搬运后按目标 URL 加载,不再入栈)。 @@ -485,9 +541,10 @@ impl BrowserApp { self.bar.set_url(url.to_owned()); self.bar.set_loading(true); - // 内部 scheme(about:blank 等)不由网络抓取,直接生成本地空白页。 - // 交给 NetworkFetcher 会被协议白名单判为 InvalidUrl,白屏。 - if !url.starts_with("http://") && !url.starts_with("https://") { + // 内部 scheme(about:blank 等)不经网络,直接生成本地空白页。 + // 其余 URL(含补全 scheme 后仍非法的输入)交给抓取路径:协议白名单 + // 判 InvalidUrl → 错误页给出反馈,不再静默白屏。 + if url.starts_with("about:") { self.bar.set_loading(false); self.show_blank(); if let Some(window) = &self.window { @@ -503,70 +560,62 @@ impl BrowserApp { let Some(proxy) = Some(self.proxy.clone()) else { return; }; - let url = url.to_owned(); - let target = url.clone(); + let target = url.to_owned(); std::thread::Builder::new() .name("nexty-fetch".to_owned()) .spawn(move || { - let request = nexty_network::Request { - url: target.clone(), - method: Method::Get, - // 不少真实站点对无 UA 请求直接 403/429 - headers: vec![( - "User-Agent".to_owned(), - format!("Nexty/{}", env!("CARGO_PKG_VERSION")), - )], - }; - // 全部加载在后台线程完成:文档抓取 → 解析 → 子资源并发抓取 - // → 级联 → 页面就绪。主线程只做布局与呈现。 - // 错误串收敛为「错误类别 + 状态码」:不回显上游原始错误 - //(reqwest 的错误文本内含目标 URL),错误页只显示类别。 - let result = match fetcher.fetch(&request) { - Ok(response) if (200..300).contains(&response.status) => { - if response.body.len() > crate::resources::MAX_DOCUMENT_BODY_BYTES { - Err("响应体超出预算".to_owned()) - } else { - match String::from_utf8(response.body) { - Ok(html) => { - let document = nexty_html::parse_document( - &html, - nexty_html::ParseOptions::default(), - ); - let resources = crate::resources::fetch_subresources( - fetcher.as_ref(), - &url, - &document, - ); - Ok(pipeline::build_page( - document, - resources.stylesheets, - resources.images, - )) - } - Err(_) => Err("响应不是有效的文本".to_owned()), - } - } - } - Ok(response) => Err(format!("HTTP {}", response.status)), - Err(error) => Err(load_error_text(&error).to_owned()), + // 全部抓取在后台线程完成:文档抓取 → 解码 → 规划解析 → + // 子资源并发抓取与解码(resources::fetch_document 同步编排), + // 产出全 Send 数据面(K1 起 Document 含监听器注册表 !Send, + // 只能在主线程构建——主线程按同一 HTML 重建正式文档)。 + // 错误串收敛为「错误类别 + 状态码」(见 fetch_document)。 + let result = crate::resources::fetch_document(fetcher.as_ref(), &target); + let base_url = match &result { + Ok(fetched) => fetched.base_url.clone(), + Err(_) => target.clone(), }; let _ = proxy.send_event(BackgroundEvent::PageLoaded(Box::new(PageLoadedPayload { - url, + url: target, + base_url, result, }))); }) .expect("spawn fetch thread"); } - /// 抓取完成:重建页面与显示列表。 - fn page_loaded(&mut self, url: String, result: Result) { + /// 抓取完成:重建页面与显示列表,并派发生命周期事件。 + fn page_loaded(&mut self, payload: PageLoadedPayload) { self.bar.set_loading(false); - match result { - Ok(page) => { + // 生命周期门控:后台编排同步完成(解析 + settle)后事件才到达; + // 错误页在主线程本地合成解析——两条路径的 DOMContentLoaded 与 load + // 门控均已满足,经 EventLoop post_task 按 FIFO 顺序派发。 + let pending = pipeline::PendingLifecycle { + dom_content_loaded: true, + load: true, + }; + match payload.result { + Ok(fetched) => { + // 正式文档在主线程构建(Document 含监听器注册表 !Send): + // 按同一 HTML 重建,并装配后台线程抓取的子资源数据面。 + // 查表 base 与后台抓取一致:响应最终 URL(重定向落点)。 + let document = nexty_html::parse_document( + &fetched.data.html, + nexty_html::ParseOptions::default(), + ); + let resources = crate::resources::assemble_page_data( + &document, + &payload.base_url, + &fetched.data, + ); + // @font-face 字体源收集与后台抓取(K4 T3):不在 load 门控 + // 内,首帧先用系统字体渲染;字节就绪注册后经 FontsReady + // 触发恰好一轮重排(font-display swap 简化)。 + self.spawn_font_fetch(&resources.stylesheets, &payload.base_url, &payload.url); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); let title = pipeline::document_title(&page.document); self.set_page(page, true); - self.bar.set_url(url); + self.bar.set_url(payload.url); if let Some(window) = &self.window { match title { Some(title) => window.set_title(&format!("{title} - Nexty")), @@ -575,16 +624,75 @@ impl BrowserApp { } } Err(error) => { - eprintln!("load {url} failed: {error}"); + eprintln!("load {} failed: {error}", payload.url); // 失败也要出错误页:只打日志会让画面停在上一帧或空白, // 用户看不到任何反馈。 - let html = error_page_html(&url, &error); + let html = error_page_html(&payload.url, &error); self.set_page(pipeline::load_page(&html, ""), true); if let Some(window) = &self.window { window.set_title("加载失败 - Nexty"); } } } + // 生命周期派发经 EventLoop post_task(DOMContentLoaded → load,FIFO) + self.dispatch_page_lifecycle(pending); + } + + /// 收集 @font-face 源并在后台线程抓取字体字节(K4 T3)。 + /// + /// 无待抓取源(无 @font-face / 全部会话已注册 / woff2 提示跳过)时 + /// 不起线程:已注册字体的重复导航零抓取、零重排。 + fn spawn_font_fetch( + &mut self, + stylesheets: &[nexty_css::Stylesheet], + base_url: &str, + url: &str, + ) { + let requests = self.fonts.collect(stylesheets, base_url); + if requests.is_empty() { + return; + } + let Some(fetcher) = self.fetcher.clone() else { + return; + }; + let proxy = self.proxy.clone(); + let url = url.to_owned(); + std::thread::Builder::new() + .name("nexty-fonts".to_owned()) + .spawn(move || { + // 抓取降级语义与主文档子资源一致(404 / 超预算 / 传输错误 + // 缺席);全空则无事可做,不回送事件。 + let fonts = crate::resources::fetch_fonts(fetcher.as_ref(), &requests); + if fonts.is_empty() { + return; + } + let _ = + proxy.send_event(BackgroundEvent::FontsReady(Box::new(FontsReadyPayload { + url, + fonts, + }))); + }) + .expect("spawn font fetch thread"); + } + + /// 字体字节就绪:注册进会话注册表;有新注册时重级联 + 重排 + 重绘 + /// **恰好一轮**(K4 T3)。已接线的整形器自动命中注册字体(nexty-text + /// T2);chunk 分析缓存随新片段树重建,场景缓存随代次推进失效。载荷 + /// 属于已离开的页面时只入库(会话缓存跨页有效),不重排。 + fn fonts_ready(&mut self, payload: FontsReadyPayload) { + let registration = self.fonts.register(payload.fonts); + if registration.rejected > 0 { + eprintln!( + "font registration rejected {} source(s); fallback to system fonts", + registration.rejected + ); + } + if registration.registered > 0 && payload.url == self.history.current() { + self.relayout(); + if let Some(window) = &self.window { + window.request_redraw(); + } + } } /// 一帧:合成显示列表并发给渲染线程(异步,不等待)。 @@ -636,17 +744,10 @@ impl BrowserApp { Some(map) if !self.selection.is_empty() => self.selection.rects(map), _ => Vec::new(), }; - // 画布底色:pipeline 的画布保持透明,直接 blit 会把透明像素交给 - // surface(alpha_mode Auto),在部分后端表现为黑屏/花屏。先铺不透明白底。 - let white_background = nexty_paint::Command::FillRect { - rect: nexty_paint::Rect { - x: 0.0, - y: 0.0, - width, - height, - }, - color: nexty_paint::Color::opaque(0xff, 0xff, 0xff), - }; + // 画布底色:CSS 2.2 §14.2 html/body 背景传播到画布——html 携带背景 + // 用 html,否则 body,都无回落白;视口坐标系,不随滚动平移。画布 + // 必须不透明:透明像素直接 blit 给 surface(alpha_mode Auto)在部分 + // 后端表现为黑屏/花屏。被传播元素的自身背景由 emit 抑制(搬移语义)。 let mut scene = match (&self.page, &self.root) { (Some(page), Some(root)) => { let page_scene = self.scene_cache.scene_for( @@ -657,12 +758,26 @@ impl BrowserApp { &highlights, ); let mut scene = page_scene.translated(0.0, BAR_HEIGHT - self.scroll_y); - scene.commands.insert(0, white_background); + for (index, command) in pipeline::canvas_background_commands(page, width, height) + .into_iter() + .enumerate() + { + scene.commands.insert(index, command); + } scene } _ => { + // 无页面(启动空窗):无从传播,固定白底。 let mut scene = Scene::default(); - scene.commands.push(white_background); + scene.commands.push(nexty_paint::Command::FillRect { + rect: nexty_paint::Rect { + x: 0.0, + y: 0.0, + width, + height, + }, + color: nexty_paint::Color::opaque(0xff, 0xff, 0xff), + }); scene } }; @@ -763,7 +878,9 @@ impl ApplicationHandler for BrowserApp { fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: BackgroundEvent) { match event { - BackgroundEvent::PageLoaded(payload) => self.page_loaded(payload.url, payload.result), + BackgroundEvent::PageLoaded(payload) => self.page_loaded(*payload), + // 字体字节就绪:注册 + 恰一轮重排(K4 T3) + BackgroundEvent::FontsReady(payload) => self.fonts_ready(*payload), // 渲染线程完成:上屏最新一帧,按需补排帧 BackgroundEvent::FrameReady => self.present_finished_frames(), } @@ -838,12 +955,23 @@ impl ApplicationHandler for BrowserApp { self.update_cursor_icon(); } WindowEvent::MouseWheel { delta, .. } => { - // 滚轮向上(y > 0)→ 减小滚动量 - let amount = match delta { - MouseScrollDelta::LineDelta(_, y) => y * WHEEL_LINE_PX, - MouseScrollDelta::PixelDelta(position) => position.y as f32, + // 滚轮先派发后默认:WheelEvent(正值 deltaY = 页面向下滚, + // 与 winit 相反号)未取消才滚动,滚动量换算沿用现语义。 + let (mode, amount, wheel_delta) = match delta { + MouseScrollDelta::LineDelta(x, y) => ( + DeltaMode::Line, + y * WHEEL_LINE_PX, + (-f64::from(x), -f64::from(y)), + ), + MouseScrollDelta::PixelDelta(position) => ( + DeltaMode::Pixel, + position.y as f32, + (-position.x, -position.y), + ), }; - self.scroll_by(-amount); + if self.dispatch_page_wheel(wheel_delta, mode) { + self.scroll_by(-amount); + } } WindowEvent::MouseInput { state: ElementState::Pressed, @@ -875,10 +1003,18 @@ impl ApplicationHandler for BrowserApp { } => { self.scrollbar.on_release(); if let Some(press) = self.press.take() { - self.selection.finish(); let dragged = !selection::is_click((press.x, press.y), self.cursor); - // 释放且未拖动才算点击:链接此时导航,拖过链接文字只选择。 - if !dragged && let Some(url) = press.link { + // mouseup 先派发后默认;selection.finish 与滚动条 + // on_release 一样是 chrome 侧手势状态卫生(无论取消都 + // 执行,避免状态机卡在拖拽态)。 + let _ = self.dispatch_page_mouse(press.node, "mouseup", press.x, press.y, 0); + self.selection.finish(); + // 释放且未拖动才算点击:click 仅此时派发(现语义), + // 默认动作 = 链接导航,被取消则跳过(先派发后默认)。 + if !dragged + && self.dispatch_page_mouse(press.node, "click", press.x, press.y, 0) + && let Some(url) = press.link + { self.navigate(&url); } } @@ -893,21 +1029,28 @@ impl ApplicationHandler for BrowserApp { self.shift_down = state.shift_key(); } WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => { - let modifiers = ui::Modifiers { - ctrl: self.ctrl_down, - shift: self.shift_down, - alt: self.alt_down, - }; + let modifiers = self.modifiers(); let key = ui_key(&event.logical_key); - // 浏览器级快捷键优先于一切(Alt+方向键、Ctrl+L/R/A、F5、Esc) + // 浏览器级快捷键优先于一切(Alt+方向键、Ctrl+L/R/A、F5、Esc)。 + // 「先派发后默认」:地址栏聚焦时键属 chrome UI(不进页面), + // 直接执行;未聚焦时先派发可取消 keydown,未取消才执行。 if let Some(key) = key && let Some(shortcut) = ui::shortcut(key, modifiers) { - self.apply_shortcut(shortcut); + let allowed = if self.bar.is_focused() { + true + } else { + let (key_name, code) = events::dom_key_names(key); + self.dispatch_page_key(&key_name, &code, event.repeat) + }; + if allowed { + self.apply_shortcut(shortcut); + } return; } if self.bar.is_focused() { // 地址栏聚焦:方向键/Home/End 作用于光标(Shift 扩选) + // —— chrome UI 键,不派发到页面 if let Some(direction) = key.and_then(caret_direction) { let _ = self.bar.handle(UiEvent::MoveCaret { direction, @@ -915,29 +1058,31 @@ impl ApplicationHandler for BrowserApp { }); } } else { - // 未聚焦:翻页/滚动键作用于页面 + // 未聚焦:翻页/滚动键作用于页面——先派发后默认 let page_step = self .geometry() .map_or(0.0, |geometry| geometry.page_step() * 0.9); match event.logical_key { Key::Named(NamedKey::PageDown) => { - self.scroll_by(page_step); + self.dispatch_key_scroll("PageDown", page_step); } Key::Named(NamedKey::PageUp) => { - self.scroll_by(-page_step); + self.dispatch_key_scroll("PageUp", -page_step); } Key::Named(NamedKey::ArrowDown) => { - self.scroll_by(WHEEL_LINE_PX); + self.dispatch_key_scroll("ArrowDown", WHEEL_LINE_PX); } Key::Named(NamedKey::ArrowUp) => { - self.scroll_by(-WHEEL_LINE_PX); + self.dispatch_key_scroll("ArrowUp", -WHEEL_LINE_PX); } Key::Named(NamedKey::Home) => { - self.scroll_by(-self.scroll_y); + let delta = -self.scroll_y; + self.dispatch_key_scroll("Home", delta); } Key::Named(NamedKey::End) => { if let Some(geometry) = self.geometry() { - self.scroll_by(geometry.max_scroll() - self.scroll_y); + let delta = geometry.max_scroll() - self.scroll_y; + self.dispatch_key_scroll("End", delta); } } _ => {} @@ -1395,18 +1540,6 @@ fn pad_rows_into(out: &mut Vec, data: &[u8], width: u32, height: u32, padded } } -/// 传输失败 → 错误类别文本。 -/// -/// 不回显上游原始错误串:reqwest 的错误文本内含目标 URL,而错误页是按 -/// 页面语义渲染的 HTML——错误信息只保留「类别」这一用户需要知道的内容。 -fn load_error_text(error: &NetworkError) -> &'static str { - match error { - NetworkError::InvalidUrl => "无效的地址", - NetworkError::Timeout => "请求超时", - NetworkError::Transport => "网络错误", - } -} - /// HTML 实体转义(`&` `<` `>` `"` `'`)。 /// /// 错误页把不可信文本(URL、错误类别)拼进 HTML:不转义的话,形如 diff --git a/crates/nexty-chrome/src/app/events.rs b/crates/nexty-chrome/src/app/events.rs new file mode 100644 index 0000000..9e3065d --- /dev/null +++ b/crates/nexty-chrome/src/app/events.rs @@ -0,0 +1,469 @@ +//! 交互事件接线与生命周期派发(K1 T3)——chrome 侧事件接线的集中点。 +//! +//! 从 `app` 的输入路由迁出的事件派发部分全在本模块: +//! +//! - **交互事件**:`hit_test_ex` 命中节点(无命中退回文档根)上构造数据面 +//! 事件(`MouseEvent` / `WheelEvent` / `KeyboardEvent`,bubbles=true、 +//! cancelable=true,字段由派发方填)并派发;`Document::dispatch` 返回 +//! 「未取消」(true)→ 调用方执行默认动作。链接导航、滚轮滚动、键盘 +//! 滚动与快捷键全部走「先派发后默认」——无监听器时行为与接线前一致。 +//! - **生命周期**:页面安装点按跨线程信号(HTML 解析完成 / 首轮子资源 +//! 编排 settle,见 [`PendingLifecycle`])经 pipeline 的单处钩子 +//! `Page::post_lifecycle_tasks` post 进 [`EventLoop`],`run_pending_tasks` +//! 排空派发(FIFO:DOMContentLoaded 先于 load;派发中 post 不重入)。 +//! +//! 数据面构造与派发是纯函数(可无头单测);winit → chrome UI 的路由 +//! (地址栏、滚动条、悬停)仍在 `app.rs`,不属于页面 DOM 事件。 +//! +//! 偏差(K1 简化档):监听器回调只见核心 [`Event`] 面,读不到类型化数据 +//! 字段(K5 扩回调签名);`screenX/Y` 未跟踪(置 0);无 mousemove/悬停 +//! 派发(悬停只更新光标);地址栏聚焦时按键属 chrome UI,不派发到页面。 + +use nexty_dom::{DeltaMode, KeyboardEvent, MouseEvent, NodeId, WheelEvent}; + +use super::BrowserApp; +use crate::pipeline::{self, Page, PendingLifecycle}; +use crate::ui::{self, BAR_HEIGHT, Modifiers}; + +/// 派发鼠标事件(mousedown / mouseup / click)到 `target`。 +/// +/// `client` 为页面视口坐标(UI Events clientX/Y:相对视口,不含滚动偏移); +/// button 固定主键 0,`buttons` 为按住位掩码(UI Events §5.2.2:按下主键 +/// 为 1,释放后为 0)。bubbles=true、cancelable=true。返回「未取消」: +/// false = 已被 [`prevent_default`](nexty_dom::Event::prevent_default), +/// 默认动作必须跳过。 +pub(super) fn dispatch_mouse( + page: &mut Page, + target: NodeId, + type_: &'static str, + client: (f32, f32), + buttons: u16, + modifiers: Modifiers, +) -> bool { + let mut event = MouseEvent::new(type_, true, true); + event.detail = 1; + event.client_x = client.0 as i32; + event.client_y = client.1 as i32; + event.button = 0; + event.buttons = buttons; + event.ctrl_key = modifiers.ctrl; + event.shift_key = modifiers.shift; + event.alt_key = modifiers.alt; + page.document.dispatch(target, &mut event.event) +} + +/// 派发滚轮事件(wheel)到 `target`。 +/// +/// `delta` 为 UI Events 语义(正值 deltaY = 页面向下滚),单位由 `mode` +/// 标注;简化档的 `WheelEvent` 数据面无坐标与修饰键字段。bubbles=true、 +/// cancelable=true。返回「未取消」。 +pub(super) fn dispatch_wheel( + page: &mut Page, + target: NodeId, + delta: (f64, f64), + mode: DeltaMode, +) -> bool { + let mut event = WheelEvent::new("wheel", true, true); + event.delta_x = delta.0; + event.delta_y = delta.1; + event.delta_mode = mode; + page.document.dispatch(target, &mut event.event) +} + +/// 派发键盘事件(keydown)到 `target`。 +/// +/// `key` / `code` 为 UI Events 键值与物理键位字符串;bubbles=true、 +/// cancelable=true。返回「未取消」。 +pub(super) fn dispatch_key( + page: &mut Page, + target: NodeId, + key: &str, + code: &str, + modifiers: Modifiers, + repeat: bool, +) -> bool { + let mut event = KeyboardEvent::new("keydown", true, true); + event.key = key.to_owned(); + event.code = code.to_owned(); + event.ctrl_key = modifiers.ctrl; + event.shift_key = modifiers.shift; + event.alt_key = modifiers.alt; + event.repeat = repeat; + page.document.dispatch(target, &mut event.event) +} + +/// chrome 抽象键 → DOM `key`/`code` 字符串(KeyboardEvent 数据面填充用)。 +/// +/// 字符键 `key` 取原文、`code` 按 `Key<大写>`;命名键两处同名——物理键位 +/// 的精确 `code` 面记入偏差清单(简化档不读 winit physical_key)。 +pub(super) fn dom_key_names(key: ui::Key) -> (String, String) { + match key { + ui::Key::Character(character) => { + let key = character.to_string(); + let code = format!("Key{}", character.to_ascii_uppercase()); + (key, code) + } + ui::Key::Left => ("ArrowLeft".to_owned(), "ArrowLeft".to_owned()), + ui::Key::Right => ("ArrowRight".to_owned(), "ArrowRight".to_owned()), + ui::Key::Home => ("Home".to_owned(), "Home".to_owned()), + ui::Key::End => ("End".to_owned(), "End".to_owned()), + ui::Key::F5 => ("F5".to_owned(), "F5".to_owned()), + ui::Key::Escape => ("Escape".to_owned(), "Escape".to_owned()), + } +} + +impl BrowserApp { + /// 当前修饰键快照(winit ModifiersChanged 维护的三个布尔)。 + pub(super) fn modifiers(&self) -> Modifiers { + Modifiers { + ctrl: self.ctrl_down, + shift: self.shift_down, + alt: self.alt_down, + } + } + + /// 窗口点 `(x, y)` 在页面里的命中节点(工具带高度已扣除并叠加滚动)。 + pub(super) fn hit_node_at(&self, x: f32, y: f32) -> Option { + let page_y = y - BAR_HEIGHT + self.scroll_y; + self.root + .as_ref() + .and_then(|root| pipeline::hit_test_ex(root, x, page_y)) + .map(|hit| hit.node) + } + + /// 在命中节点(`node` 为 None 时退回文档根)派发页面鼠标事件。 + /// + /// `x`/`y` 为窗口坐标;client 取页面视口坐标(扣工具带高度,不含滚动 + /// 偏移)。无页面时视为未取消(默认动作照常——与无监听器时一致)。 + pub(super) fn dispatch_page_mouse( + &mut self, + node: Option, + type_: &'static str, + x: f32, + y: f32, + buttons: u16, + ) -> bool { + let modifiers = self.modifiers(); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = match node { + Some(node) => node, + None => page.document.root(), + }; + dispatch_mouse(page, target, type_, (x, y - BAR_HEIGHT), buttons, modifiers) + } + + /// 派发滚轮事件(光标命中节点或文档根)。返回「未取消」。 + pub(super) fn dispatch_page_wheel(&mut self, delta: (f64, f64), mode: DeltaMode) -> bool { + let (x, y) = self.cursor; + let node = self.hit_node_at(x, y); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = match node { + Some(node) => node, + None => page.document.root(), + }; + dispatch_wheel(page, target, delta, mode) + } + + /// 派发页面键盘事件(keydown,文档根上)。返回「未取消」。 + /// + /// 调用边界:地址栏聚焦时键属 chrome UI,不派发到页面(调用方保证); + /// 无页面时视为未取消。 + pub(super) fn dispatch_page_key(&mut self, key: &str, code: &str, repeat: bool) -> bool { + let modifiers = self.modifiers(); + let Some(page) = self.page.as_mut() else { + return true; + }; + let target = page.document.root(); + dispatch_key(page, target, key, code, modifiers, repeat) + } + + /// 滚动键的「先派发后默认」:keydown 未取消才执行滚动。 + pub(super) fn dispatch_key_scroll(&mut self, key: &'static str, delta: f32) { + if self.dispatch_page_key(key, key, false) { + self.scroll_by(delta); + } + } + + /// 页面安装点的生命周期派发:按跨线程信号 post DOMContentLoaded / load + /// 任务(pipeline 单处钩子构造,FIFO 保序),随即排空——事件在当前 + /// 页面文档根上派发。信号未到的事件不 post(K3/K4 异步 settle 的接缝)。 + pub(super) fn dispatch_page_lifecycle(&mut self, pending: PendingLifecycle) { + if pending.is_empty() { + return; + } + if let Some(page) = self.page.as_mut() { + page.post_lifecycle_tasks(&mut self.dom_loop, pending); + } + self.run_dom_tasks(); + } + + /// 排空 DOM 宏任务队列(任务在当前页面文档上执行)。 + pub(super) fn run_dom_tasks(&mut self) { + if let Some(page) = self.page.as_mut() { + self.dom_loop.run_pending_tasks(&mut page.document); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pipeline; + use nexty_dom::{Event, EventListener}; + use std::cell::RefCell; + use std::rc::Rc; + + type Log = Rc>>; + + /// 鼠标事件记录器:按事件类型记入日志;`prevent_click` 为真时对 click + /// 调 [`Event::prevent_default`](模拟页面监听器取消默认动作)。 + struct ClickLogger { + log: Log, + prevent_click: bool, + } + + impl EventListener for ClickLogger { + fn handle_event(&mut self, event: &mut Event) { + let label = match event.type_() { + "mousedown" => "mousedown", + "mouseup" => "mouseup", + "click" => "click", + _ => "other", + }; + self.log.borrow_mut().push(label); + if self.prevent_click && event.type_() == "click" { + event.prevent_default(); + } + } + } + + /// 块级链接页 + 命中节点(布局 200px 视口,点 (10, 5) 命中 `` 盒)。 + fn link_page(log: &Log, prevent_click: bool) -> (Page, NodeId) { + let mut page = pipeline::load_page( + "block link", + "body { margin: 0 }", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = pipeline::layout_page(&page, &shaper, 200.0).expect("root"); + let node = pipeline::hit_test(&root, 10.0, 5.0).expect("命中链接"); + page.document.add_listener( + node, + "mousedown", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click: false, + }), + ); + page.document.add_listener( + node, + "mouseup", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click: false, + }), + ); + page.document.add_listener( + node, + "click", + false, + Box::new(ClickLogger { + log: Rc::clone(log), + prevent_click, + }), + ); + (page, node) + } + + /// ① click 派发且默认导航仍发生:三事件按序派发、click 未取消—— + /// app 侧据此执行链接导航(默认动作)。 + #[test] + fn click_sequence_dispatches_and_default_navigation_runs() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let (mut page, target) = link_page(&log, false); + let modifiers = Modifiers::default(); + + // app.rs 的点击序列:mousedown(主键按住 buttons=1)→ mouseup → + // click(释放且未拖动才派发,现语义)。 + assert!(dispatch_mouse( + &mut page, + target, + "mousedown", + (10.0, 5.0), + 1, + modifiers + )); + assert!(dispatch_mouse( + &mut page, + target, + "mouseup", + (10.0, 5.0), + 0, + modifiers + )); + assert!( + dispatch_mouse(&mut page, target, "click", (10.0, 5.0), 0, modifiers), + "无取消监听器:click 未取消 → 默认导航执行" + ); + assert_eq!( + *log.borrow(), + ["mousedown", "mouseup", "click"], + "点击序列 mousedown → mouseup → click 完整派发" + ); + } + + /// ② 注入测试监听器 preventDefault 后默认导航被跳过——「先派发后默认」 + /// 顺序的证据:监听器在 click 派发中置 defaultPrevented,导航判定 + /// (dispatch 返回值)在其后读到 false。mousedown/mouseup 不受影响。 + #[test] + fn prevent_default_click_skips_default_navigation() { + let log: Log = Rc::new(RefCell::new(Vec::new())); + let (mut page, target) = link_page(&log, true); + let modifiers = Modifiers::default(); + + assert!(dispatch_mouse( + &mut page, + target, + "mousedown", + (10.0, 5.0), + 1, + modifiers + )); + assert!(dispatch_mouse( + &mut page, + target, + "mouseup", + (10.0, 5.0), + 0, + modifiers + )); + assert!( + !dispatch_mouse(&mut page, target, "click", (10.0, 5.0), 0, modifiers), + "preventDefault 后 dispatch 返回已取消 → 默认导航被跳过" + ); + assert_eq!( + *log.borrow(), + ["mousedown", "mouseup", "click"], + "事件照常派发,被取消的只是默认动作" + ); + } + + /// ③ 生命周期(pipeline 单处钩子):按信号 post、排空派发—— + /// DOMContentLoaded 在解析后、load 在子资源 settle 后,各恰一次、FIFO + /// 保序。与 tests/chrome.rs 的集成测试互补(那里走完整抓取编排)。 + #[test] + fn lifecycle_posts_dispatch_exactly_once_per_signal_in_fifo_order() { + let mut page = pipeline::load_page("hi", ""); + let log: Log = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + let recorder = |log: &Log, label: &'static str| { + let log = Rc::clone(log); + Box::new(move |_event: &mut Event| log.borrow_mut().push(label)) + as Box + }; + page.document.add_listener( + root, + nexty_dom::DOM_CONTENT_LOADED, + false, + recorder(&log, "dcl"), + ); + page.document + .add_listener(root, nexty_dom::LOAD, false, recorder(&log, "load")); + + // 无信号:不 post、不派发 + let mut event_loop = nexty_dom::EventLoop::new(); + page.post_lifecycle_tasks(&mut event_loop, PendingLifecycle::default()); + event_loop.run_pending_tasks(&mut page.document); + assert!(log.borrow().is_empty(), "信号未到不派发"); + + // 只到解析信号:仅 DOMContentLoaded + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: false, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["dcl"], "仅 DOMContentLoaded 派发"); + + // settle 信号到:load 恰一次 + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: false, + load: true, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!( + *log.borrow(), + ["dcl", "load"], + "DOMContentLoaded 先于 load,各恰一次" + ); + + // 队列已空:重复排空不重复派发 + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(log.borrow().len(), 2, "排空后无重复派发"); + } + + /// 滚轮/键盘事件在命中节点与文档根上的派发与取消语义(字段填充对 + /// 监听器不可见是 K1 登记偏差,字段面由检视覆盖)。 + #[test] + fn wheel_and_key_dispatch_gating() { + let mut page = pipeline::load_page("x", ""); + let root_node = page.document.root(); + let hits = Rc::new(RefCell::new(Vec::new())); + let wheel_hits = Rc::clone(&hits); + page.document.add_listener( + root_node, + "wheel", + false, + Box::new(move |event: &mut Event| { + wheel_hits.borrow_mut().push(event.type_().to_owned()); + event.prevent_default(); + }), + ); + assert!( + !dispatch_wheel(&mut page, root_node, (0.0, -40.0), DeltaMode::Line), + "wheel 被 preventDefault → 默认滚动跳过" + ); + assert_eq!(*hits.borrow(), ["wheel"]); + + let key_hits = Rc::new(RefCell::new(Vec::new())); + page.document.add_listener( + root_node, + "keydown", + false, + Box::new(move |_event: &mut Event| key_hits.borrow_mut().push("keydown")), + ); + assert!( + dispatch_key( + &mut page, + root_node, + "PageDown", + "PageDown", + Modifiers::default(), + false + ), + "keydown 未取消 → 默认滚动执行" + ); + assert_eq!(*hits.borrow(), ["wheel"], "wheel 监听器不收 keydown"); + } + + /// chrome 抽象键 → DOM key/code 映射(字符键大写进 code)。 + #[test] + fn dom_key_names_map_characters_and_named_keys() { + let (key, code) = dom_key_names(ui::Key::Character('a')); + assert_eq!((key.as_str(), code.as_str()), ("a", "KeyA")); + let (key, code) = dom_key_names(ui::Key::F5); + assert_eq!((key.as_str(), code.as_str()), ("F5", "F5")); + let (key, _) = dom_key_names(ui::Key::Left); + assert_eq!(key.as_str(), "ArrowLeft"); + } +} diff --git a/crates/nexty-chrome/src/lib.rs b/crates/nexty-chrome/src/lib.rs index bc36425..aba6886 100644 --- a/crates/nexty-chrome/src/lib.rs +++ b/crates/nexty-chrome/src/lib.rs @@ -8,14 +8,16 @@ //! (见 AGENTS.md 硬规则「渲染隔离」)。模块分工: //! //! - [`pipeline`]:HTML 字符串 → 级联 → 布局 → 片段树 → paint 显示列表; -//! - [`resources`]:子资源(外链 CSS + 图片)清单解析、并发抓取与解码编排; +//! - [`resources`]:子资源(外链 CSS + 图片 + @font-face 字体)清单解析、并发抓取与解码编排; //! - [`render`]:渲染隔离线程(panic 兜底,线程存活可继续服务); //! - [`ui`]:自绘工具带状态机(纯逻辑,可测试); //! - [`scrollbar`]:滚动几何与拖拽状态机(纯逻辑,可测试); //! - [`selection`]:页面文本选区状态机(纯逻辑,可测试); //! - [`history`]:会话历史栈(纯逻辑,可测试); -//! - `app`(私有):winit 事件循环 + wgpu 呈现胶水——**无法在无头环境 -//! 自动化测试**,实机运行验证(`cargo run -p nexty-chrome --bin nexty`)。 +//! - `app`(私有):winit 事件循环 + wgpu 呈现胶水——winit/GPU 部分无法 +//! 在无头环境自动化测试,实机运行验证(`cargo run -p nexty-chrome --bin +//! nexty`);交互事件接线与生命周期派发在 `app::events` 子模块(纯函数 +//! 部分有单测,K1 T3)。 //! //! 上游类型一律不得出现在本 crate 的 pub 导出中(AGENTS.md 硬规则)。 //! diff --git a/crates/nexty-chrome/src/pipeline.rs b/crates/nexty-chrome/src/pipeline.rs index 122ba05..35049a3 100644 --- a/crates/nexty-chrome/src/pipeline.rs +++ b/crates/nexty-chrome/src/pipeline.rs @@ -2,21 +2,38 @@ //! //! 行为分工:解析归 nexty-html,级联归 nexty-css(UA + author 双 origin), //! 布局归 nexty-layout,本模块负责把片段树转译为 [`nexty_paint::Scene`]: -//! 背景与 CSS 边框(四条填充带,宽 0 的边跳过)、行内文本 run +//! 背景与渐变(css-images-3 渐变线端点在 emit 前换算)、CSS 边框(四边等宽 +//! 有圆角时一条圆角描边,否则四条填充带)、行内文本 run 与装饰带 //! (坐标换算到绝对坐标系)、行内/块级图片(`DrawImage`,像素从页面图片池 -//! 按节点索引)。匿名片段不产生背景与边框。 +//! 按节点索引)。匿名片段不产生背景与边框;背景绘制次序遵循 +//! z-index 基础定序(普通流先、定位元素后,定位兄弟按整数排序)。 //! -//! 已知偏差:``/`` 背景不向画布传播(画布保持透明,由呈现层 -//! 决定底色);片段树不做滚动裁剪。 +//! 画布底色(CSS 2.2 §14.2):html/body 背景传播到画布——html 携带背景 +//! 用 html,否则用 body,都无回落白([`canvas_background_commands`]); +//! 传播是搬移语义,被传播的元素不再自绘背景。 +//! +//! 已知偏差:z-index 为基础定序档,不做完整 stacking context——定位元素 +//! 统一画在普通流之上(负 z-index 不回落普通流之下),命中测试也不镜像 +//! 定位层序(K7 补);border-radius 百分比按边框盒对应轴折算后取两轴 +//! 较小分量(paint 只有圆形角,椭圆 `/` 语法 css 层已整条拒收);四边 +//! border-width 不等时圆角边框降级直角填充带;text-decoration 按文本 run +//! 自身元素的 computed style 绘制(规范的祖先「传播」未实现,css 层偏差; +//! 跨行内元素边界按 run 分段断线)、非 solid 不画、度量用经验值 +//! (0.06em 厚 / underline 基线下 0.08em,无字体 underline 数据); +//! 片段树不做滚动裁剪。 use std::collections::HashMap; use std::sync::Arc; -use nexty_css::{ComputedStyle, MediaViewport, Rgba, Stylesheet, html_ua_stylesheet}; -use nexty_dom::{Document, NodeId}; +use nexty_css::{ + BackgroundImageValue, BorderRadiusValue, ComputedStyle, GradientColorStop, MediaViewport, + PositionValue, Rgba, Stylesheet, TextDecorationLineValue, TextDecorationStyleValue, + ZIndexValue, html_ua_stylesheet, +}; +use nexty_dom::{Document, Event, EventLoop, NodeId, Task, TaskContext}; use nexty_html::ParseOptions; -use nexty_layout::{Fragment, Rect as LayoutRect}; -use nexty_paint::{Color, Command, Image, Rect as PaintRect, Scene, Size, TextGlyph}; +use nexty_layout::{Fragment, Rect as LayoutRect, TextRun}; +use nexty_paint::{Color, Command, GradientStop, Image, Rect as PaintRect, Scene, Size, TextGlyph}; use nexty_text::TextShaper; /// 一个已解析、已级联的页面。 @@ -87,6 +104,57 @@ pub fn load_page(html: &str, author_css: &str) -> Page { build_page(document, vec![sheet], HashMap::new()) } +/// 页面待派发的生命周期事件信号集(K1 T3)。 +/// +/// 信号在后台线程于真实完成点捕获(HTML 解析返回 / 首轮子资源编排 +/// settle——含失败/超时/预算降级路径),随页面载荷送回主线程;主线程经 +/// [`Page::post_lifecycle_tasks`] post 进 EventLoop 再排空派发。后台线程 +/// 只投信号,不得跨线程触碰 [`Document`]。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PendingLifecycle { + /// HTML 解析完成 → `DOMContentLoaded`(bubbles=true、cancelable=false, + /// 文档根上派发)。 + pub dom_content_loaded: bool, + /// 首轮子资源编排 settle(含失败/超时/预算降级)→ `load`(bubbles=false)。 + pub load: bool, +} + +impl PendingLifecycle { + /// 两个信号都未到。 + #[must_use] + pub fn is_empty(&self) -> bool { + !self.dom_content_loaded && !self.load + } +} + +impl Page { + /// 导航/解析完成点的**单处** EventLoop 钩子(K1 T3):把信号了的生命 + /// 周期事件按 `DOMContentLoaded` → `load` 顺序 post 进 EventLoop + /// (FIFO 保序);任务执行时在文档根上派发(根无祖先链 → 仅 target + /// 阶段,恰好一次)。 + /// + /// 本方法不存状态:同一信号重复 post 会重复派发——每页只 post 一次 + /// 由调用方(页面安装点)保证。 + pub fn post_lifecycle_tasks(&mut self, event_loop: &mut EventLoop, pending: PendingLifecycle) { + if pending.dom_content_loaded { + event_loop.post_task(Task::new(|ctx: &mut TaskContext| { + let document = ctx.document(); + let root = document.root(); + let mut event = Event::dom_content_loaded(); + document.dispatch(root, &mut event); + })); + } + if pending.load { + event_loop.post_task(Task::new(|ctx: &mut TaskContext| { + let document = ctx.document(); + let root = document.root(); + let mut event = Event::load(); + document.dispatch(root, &mut event); + })); + } + } +} + /// 对页面做布局,返回根元素片段。 #[must_use] pub fn layout_page(page: &Page, shaper: &dyn TextShaper, viewport_width: f32) -> Option { @@ -143,6 +211,9 @@ pub fn build_scene_at_with_highlights( ) -> Scene { let mut scene = Scene::default(); let mut pool: HashMap = HashMap::new(); + // §14.2 传播源(html 优先、body 回落):emit 内被传播的元素不再自绘 + // 背景(搬移语义);全树只查一次,递归透传。 + let canvas_source = canvas_background_source(page); // 高亮矩形相对根片段;先平移到场景坐标,递归 emit 里不再叠加 origin //(emit 的 origin 是父链累积位置,不是场景原点)。 let highlights: Vec = highlights @@ -161,10 +232,22 @@ pub fn build_scene_at_with_highlights( &mut scene, &mut pool, &highlights, + canvas_source, ); scene } +/// 文本装饰带的经验度量(em 单位;无字体 underline 度量可用——T0 报告 +/// F11,记偏差):厚度一律 `0.06em`;underline 带顶在基线下 `0.08em`; +/// overline 近似 em 盒顶(基线上方 `0.88em` ≈ 0.8em ascent + 0.08em); +/// line-through 穿过 x 高中部近似(基线上方 `0.30em`)。 +const DECORATION_THICKNESS_EM: f32 = 0.06; +const UNDERLINE_OFFSET_EM: f32 = 0.08; +const OVERLINE_OFFSET_EM: f32 = 0.88; +const LINE_THROUGH_OFFSET_EM: f32 = 0.30; + +/// 递归 emit 的固定形态参数较多;八参均在用,重签名不值当(针对性抑制)。 +#[allow(clippy::too_many_arguments)] fn emit( page: &Page, fragment: &Fragment, @@ -173,61 +256,114 @@ fn emit( scene: &mut Scene, pool: &mut HashMap, highlights: &[LayoutRect], + canvas_source: Option, ) { let x = origin_x + fragment.border_box.x; let y = origin_y + fragment.border_box.y; let width = fragment.border_box.width; let height = fragment.border_box.height; let style = &fragment.style; + // 四角圆角解析为 px(CSS Backgrounds §5.5;全 0 保持直角旧路径) + let radii = resolve_corner_radii(style, width, height); + let rounded = radii != [0.0; 4]; + // §14.2 传播是搬移:被传播的元素不再自绘背景(颜色与渐变) + let background_propagated = !fragment.anonymous && Some(fragment.node) == canvas_source; if !fragment.anonymous { - // 背景(透明跳过) - if style.background_color.a > 0 { - scene.commands.push(Command::FillRect { + // 背景色(透明跳过;有圆角走 FillRoundedRect,全 0 保持 FillRect) + if style.background_color.a > 0 && !background_propagated { + let rect = PaintRect { + x, + y, + width, + height, + }; + let color = to_color(style.background_color); + if rounded { + scene + .commands + .push(Command::FillRoundedRect { rect, radii, color }); + } else { + scene.commands.push(Command::FillRect { rect, color }); + } + } + // 渐变背景(CSS Images §3.4,画在背景色之上):渐变线端点按 + // css-images-3 公式在 emit 前换算,radii 随 border_radius——单条 + // 指令完成渐变 × 圆角。 + if !background_propagated + && let BackgroundImageValue::LinearGradient(gradient) = &style.background_image + { + let (start, end) = linear_gradient_endpoints(gradient.angle, x, y, width, height); + let stops = gradient_stops(&gradient.stops); + if !stops.is_empty() { + scene.commands.push(Command::FillGradient { + rect: PaintRect { + x, + y, + width, + height, + }, + radii, + start, + end, + stops, + }); + } + } + // CSS 边框:画在边框盒内侧。四边宽度相等且有圆角 → 一条圆角描边 + //(facade 内缩 `width/2`,带恰落在 [0, width],颜色取 top——四边 + // 异色记偏差);否则四条填充带精确表达(宽 0 跳过;宽不等时圆角 + // 降级直角——偏差)。 + let border = fragment.border; + let colors = &style.border_color; + let uniform_border = + border.top == border.bottom && border.left == border.right && border.top == border.left; + if border.top > 0.0 && rounded && uniform_border { + scene.commands.push(Command::StrokeRoundedRect { rect: PaintRect { x, y, width, height, }, - color: to_color(style.background_color), + radii, + color: to_color(colors.top), + width: border.top, }); - } - // CSS 边框:画在边框盒内侧,用四条填充带精确表达(宽 0 跳过) - let border = fragment.border; - let colors = &style.border_color; - if border.top > 0.0 { - push_strip(scene, x, y, width, border.top, colors.top); - } - if border.bottom > 0.0 { - push_strip( - scene, - x, - y + height - border.bottom, - width, - border.bottom, - colors.bottom, - ); - } - if border.left > 0.0 { - push_strip( - scene, - x, - y + border.top, - border.left, - height - border.top - border.bottom, - colors.left, - ); - } - if border.right > 0.0 { - push_strip( - scene, - x + width - border.right, - y + border.top, - border.right, - height - border.top - border.bottom, - colors.right, - ); + } else { + if border.top > 0.0 { + push_strip(scene, x, y, width, border.top, colors.top); + } + if border.bottom > 0.0 { + push_strip( + scene, + x, + y + height - border.bottom, + width, + border.bottom, + colors.bottom, + ); + } + if border.left > 0.0 { + push_strip( + scene, + x, + y + border.top, + border.left, + height - border.top - border.bottom, + colors.left, + ); + } + if border.right > 0.0 { + push_strip( + scene, + x + width - border.right, + y + border.top, + border.right, + height - border.top - border.bottom, + colors.right, + ); + } } } @@ -293,6 +429,10 @@ fn emit( if run.glyphs.is_empty() { continue; } + // 文本装饰带(CSS Text Decor 3):按 run 自身元素的 computed + // style(装饰不继承、规范的祖先「传播」未实现——css 层偏差; + // 跨行内元素边界按 run 分段断线),垫在本 run 文字之下。 + push_text_decoration(page, run, content_x, baseline, scene); scene.commands.push(Command::DrawText { glyphs: run .glyphs @@ -326,16 +466,321 @@ fn emit( ); } // 行内原子盒(inline-block 等):完整子片段树,x/y 已相对行顶定位, - // 按子片段递归(原点 = 本行顶) - for atomic in &line.boxes { - emit(page, atomic, content_x, line_y, scene, pool, highlights); + // 按子片段递归(原点 = 本行顶);定位原子盒后画并按 z-index 排序 + //(基础定序,同块级子盒)。 + let (normal_atomic, positioned_atomic) = split_positioned(&line.boxes); + for atomic in normal_atomic { + emit( + page, + atomic, + content_x, + line_y, + scene, + pool, + highlights, + canvas_source, + ); + } + for atomic in positioned_atomic { + emit( + page, + atomic, + content_x, + line_y, + scene, + pool, + highlights, + canvas_source, + ); } line_offset += line.height; } - for child in &fragment.children { - emit(page, child, content_x, content_y, scene, pool, highlights); + // z-index 基础定序(CSS Position 3 §5 简化档):普通流子片段先按文档 + // 序 emit,定位子片段(position ≠ static)后按 z-index 整数升序 emit + //(auto 视作 0、相等保持文档序;完整 stacking context 留 K7)。 + let (normal, positioned) = split_positioned(&fragment.children); + for child in normal { + emit( + page, + child, + content_x, + content_y, + scene, + pool, + highlights, + canvas_source, + ); } + for child in positioned { + emit( + page, + child, + content_x, + content_y, + scene, + pool, + highlights, + canvas_source, + ); + } +} + +/// 把子片段分拣为(普通流,定位):普通流保持文档序;定位元素(position +/// ≠ static)按 `z-index` 整数升序**稳定**排序(auto 视作 0,相等保持 +/// 文档序)。 +fn split_positioned(children: &[Fragment]) -> (Vec<&Fragment>, Vec<&Fragment>) { + let mut normal = Vec::new(); + let mut positioned: Vec<(&Fragment, i32)> = Vec::new(); + for child in children { + if child.style.position == PositionValue::Static { + normal.push(child); + } else { + positioned.push((child, z_index_key(&child.style))); + } + } + positioned.sort_by_key(|&(_, z)| z); + let positioned = positioned + .into_iter() + .map(|(fragment, _)| fragment) + .collect(); + (normal, positioned) +} + +/// `z-index` 的定序键:`auto` 与 `0` 同序(基础定序档,无 stacking context)。 +fn z_index_key(style: &ComputedStyle) -> i32 { + match style.z_index { + ZIndexValue::Auto => 0, + ZIndexValue::Integer(z) => z, + } +} + +/// 为一个文本 run 下发装饰带(`FillRect`,垫在文字下)。 +/// +/// 装饰属性取 run 自身元素的 computed style:非 solid 不画(偏差);颜色 +/// 透明不画;带顶相对基线按 [`UNDERLINE_OFFSET_EM`] 等经验度量;带 x 范围 +/// 为该 run 字形的实际横向覆盖(与命中测试同一口径)。度量为经验值、无 +/// 字体 underline 数据(T0 报告 F11,记偏差)。 +fn push_text_decoration( + page: &Page, + run: &TextRun, + content_x: f32, + baseline: f32, + scene: &mut Scene, +) { + let Some(style) = page.styles.get(&run.node) else { + return; + }; + if style.text_decoration_style != TextDecorationStyleValue::Solid { + return; + } + let offset_em = match style.text_decoration_line { + TextDecorationLineValue::None => return, + TextDecorationLineValue::Underline => UNDERLINE_OFFSET_EM, + TextDecorationLineValue::Overline => -OVERLINE_OFFSET_EM, + TextDecorationLineValue::LineThrough => -LINE_THROUGH_OFFSET_EM, + }; + if style.text_decoration_color.a == 0 { + return; + } + let size = run.style.size; + let thickness = size * DECORATION_THICKNESS_EM; + if !(thickness.is_finite() && thickness > 0.0) { + return; + } + let Some(first) = run.glyphs.first() else { + return; + }; + let Some(last) = run.glyphs.last() else { + return; + }; + let start = content_x + first.x; + let width = (last.x + last.advance) - first.x; + if !(width.is_finite() && width > 0.0) { + return; + } + scene.commands.push(Command::FillRect { + rect: PaintRect { + x: start, + y: baseline + size * offset_em, + width, + height: thickness, + }, + color: to_color(style.text_decoration_color), + }); +} + +/// 把 computed 的四角圆角解析为 px 半径 `[左上, 右上, 右下, 左下]`。 +/// +/// - `Length(px)` 直取;`Percent` 按边框盒对应轴折算(水平÷宽、垂直÷高)后 +/// 取两轴**较小**分量——paint 只有圆形角,取较小分量保证角不出盒 +/// (50% 在任意盒上退化为药丸半高;椭圆角记偏差); +/// - `Viewport` 仅在调用方未以视口 recascade 时残留,按 0 降级(直角); +/// - 负值与非有限按 0 处理(渲染为直角,与 paint 层防御一致)。 +fn resolve_corner_radii(style: &ComputedStyle, width: f32, height: f32) -> [f32; 4] { + fn one(value: BorderRadiusValue, width: f32, height: f32) -> f32 { + let radius = match value { + BorderRadiusValue::Length(px) => px, + BorderRadiusValue::Percent(p) => (p * width).min(p * height), + BorderRadiusValue::Viewport(..) => 0.0, + }; + if radius.is_finite() && radius > 0.0 { + radius + } else { + 0.0 + } + } + let corners = &style.border_radius; + [ + one(corners.top_left, width, height), + one(corners.top_right, width, height), + one(corners.bottom_right, width, height), + one(corners.bottom_left, width, height), + ] +} + +/// css-images-3 线性渐变线端点:角度自北顺时针(0 = to top),渐变线过盒 +/// 中心、长度 `|W·sinα| + |H·cosα|`(CSS Images 3 §3.3.4 图式),两端关于 +/// 中心对称。返回 `(start, end)` 场景坐标;`angle_deg` 非有限按 180 +///(to bottom)降级。 +fn linear_gradient_endpoints( + angle_deg: f32, + x: f32, + y: f32, + width: f32, + height: f32, +) -> ([f32; 2], [f32; 2]) { + let angle = if angle_deg.is_finite() { + angle_deg + } else { + 180.0 + }; + let center_x = x + width / 2.0; + let center_y = y + height / 2.0; + // 渐变方向单位向量:0° 向上(y 轴向下为正的屏幕坐标系)。四正向 + // (rem_euclid 后恰为 0/90/180/270)走精确轴向量与精确线长——f32 + // 三角函数在 90° 带 ~4e-6 噪声,最常用方向的渐变线必须严格水平 + // /垂直,端点才确定。 + let (dx, dy, length) = match angle.rem_euclid(360.0) { + 0.0 => (0.0, -1.0, height.abs()), + 90.0 => (1.0, 0.0, width.abs()), + 180.0 => (0.0, 1.0, height.abs()), + 270.0 => (-1.0, 0.0, width.abs()), + _ => { + let alpha = angle.to_radians(); + let (sin, cos) = alpha.sin_cos(); + (sin, -cos, (width * sin).abs() + (height * cos).abs()) + } + }; + ( + [center_x - dx * length / 2.0, center_y - dy * length / 2.0], + [center_x + dx * length / 2.0, center_y + dy * length / 2.0], + ) +} + +/// css 色标 → paint 色标(offset 透传,颜色经非预乘 RGBA 转换)。 +fn gradient_stops(stops: &[GradientColorStop]) -> Vec { + stops + .iter() + .map(|stop| GradientStop { + offset: stop.position, + color: to_color(stop.color), + }) + .collect() +} + +/// 元素是否携带可见背景(颜色不透明度 > 0 或渐变)——§14.2 传播判定用。 +fn has_background(style: &ComputedStyle) -> bool { + style.background_color.a > 0 + || matches!( + style.background_image, + BackgroundImageValue::LinearGradient(_) + ) +} + +/// 按 HTML 命名空间的标签名找文档中首个元素(html5ever 强制存在 html/body)。 +fn find_html_element(page: &Page, name: &str) -> Option { + use nexty_dom::{Namespace, NodeKind}; + fn walk(page: &Page, node: NodeId, name: &str) -> Option { + if let Some(NodeKind::Element(data)) = page.document.node(node) + && data.namespace == Namespace::Html + && data.name == name + { + return Some(node); + } + page.document + .children(node) + .find_map(|child| walk(page, child, name)) + } + walk(page, page.document.root(), name) +} + +/// CSS 2.2 §14.2 的画布背景传播源:html 携带背景用 html,否则 body, +/// 都无返回 `None`(画布回落白)。 +#[must_use] +pub fn canvas_background_source(page: &Page) -> Option { + if let Some(html) = find_html_element(page, "html") + && page.styles.get(&html).is_some_and(has_background) + { + return Some(html); + } + if let Some(body) = find_html_element(page, "body") + && page.styles.get(&body).is_some_and(has_background) + { + return Some(body); + } + None +} + +/// 画布底色指令(CSS 2.2 §14.2 背景传播),供呈现层插到场景**底部**。 +/// +/// - html/body 均无背景 → 一条白色 `FillRect`(画布必须不透明:透明像素 +/// 直接 blit 给 surface 在部分后端表现为黑屏/花屏); +/// - 传播源只有纯色 → 一条该色 `FillRect`; +/// - 传播源带渐变 → 先垫一条底色(传播色不透明时用它,否则白——保证 +/// 渐变透明色标不露出未初始化画布),再一条铺满视口的 `FillGradient` +/// (渐变线按**视口矩形**解析:传播到画布的背景按画布尺寸取值)。 +/// +/// 被传播元素的自身背景由 emit 抑制(搬移语义,见 [`emit`])。 +#[must_use] +pub fn canvas_background_commands( + page: &Page, + viewport_width: f32, + viewport_height: f32, +) -> Vec { + let rect = PaintRect { + x: 0.0, + y: 0.0, + width: viewport_width, + height: viewport_height, + }; + let white = Color::opaque(0xff, 0xff, 0xff); + let Some(source) = canvas_background_source(page) else { + return vec![Command::FillRect { rect, color: white }]; + }; + // 传播源必有 computed style(级联覆盖全部元素) + let style = &page.styles[&source]; + let base = if style.background_color.a > 0 { + to_color(style.background_color) + } else { + white + }; + let mut commands = vec![Command::FillRect { rect, color: base }]; + if let BackgroundImageValue::LinearGradient(gradient) = &style.background_image { + let (start, end) = + linear_gradient_endpoints(gradient.angle, 0.0, 0.0, viewport_width, viewport_height); + let stops = gradient_stops(&gradient.stops); + if !stops.is_empty() { + commands.push(Command::FillGradient { + rect, + radii: [0.0; 4], + start, + end, + stops, + }); + } + } + commands } /// `node` 是否为 HTML 命名空间的 ``(块级替换路径的判定)。 @@ -797,4 +1242,455 @@ mod tests { coalescer.on_resized(); assert!(coalescer.take()); } + + // ---- K2 T3:圆角 / 渐变 / 装饰带 / z-index / 背景传播 ---- + + use nexty_css::{Corners, ViewportUnit}; + + /// 渐变线端点:css-images-3 公式 `|W·sinα| + |H·cosα|`,四正向端点 + /// 方向、对角 45° 线长与非有限角度降级。 + #[test] + fn linear_gradient_endpoints_follow_css_images_formula() { + // 0°(to top):线长 = H,起点在下、终点在上 + let (start, end) = linear_gradient_endpoints(0.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [60.0, 70.0]); + assert_eq!(end, [60.0, 20.0]); + // 90°(to right):线长 = W,起点在左、终点在右 + let (start, end) = linear_gradient_endpoints(90.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [10.0, 45.0]); + assert_eq!(end, [110.0, 45.0]); + // 180°(to bottom,缺省角):起点在上、终点在下 + let (start, end) = linear_gradient_endpoints(180.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [60.0, 20.0]); + assert_eq!(end, [60.0, 70.0]); + // 270°(to left):起点在右、终点在左 + let (start, end) = linear_gradient_endpoints(270.0, 10.0, 20.0, 100.0, 50.0); + assert_eq!(start, [110.0, 45.0]); + assert_eq!(end, [10.0, 45.0]); + // 45°:L = W·sin45 + H·cos45;方形盒端点落在对角上 + let (start, end) = linear_gradient_endpoints(45.0, 0.0, 0.0, 100.0, 100.0); + assert!((start[0] - 0.0).abs() < 1e-4 && (start[1] - 100.0).abs() < 1e-4); + assert!((end[0] - 100.0).abs() < 1e-4 && (end[1] - 0.0).abs() < 1e-4); + // 非有限角度降级 180(to bottom) + let (start, end) = linear_gradient_endpoints(f32::NAN, 0.0, 0.0, 100.0, 50.0); + assert_eq!(start, [50.0, 0.0]); + assert_eq!(end, [50.0, 50.0]); + } + + /// 圆角解析:Length 直取、Percent 两轴取小、Viewport 残留降级 0、 + /// 负值与非有限钳 0。 + #[test] + fn corner_radii_resolve_length_percent_and_viewport_fallback() { + let mut style = ComputedStyle::initial(); + style.border_radius = Corners::splat(BorderRadiusValue::Length(10.0)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [10.0; 4]); + + // 50% @800×200:水平 400、垂直 100 → 取较小分量(药丸半高) + style.border_radius = Corners::splat(BorderRadiusValue::Percent(0.5)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [100.0; 4]); + + // 视口单位残留(未 recascade)→ 0 降级直角 + style.border_radius = Corners::splat(BorderRadiusValue::Viewport(2.0, ViewportUnit::Vw)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + + style.border_radius = Corners::splat(BorderRadiusValue::Length(f32::NAN)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + style.border_radius = Corners::splat(BorderRadiusValue::Length(-5.0)); + assert_eq!(resolve_corner_radii(&style, 800.0, 200.0), [0.0; 4]); + } + + /// 布局一页并构建场景的测试辅助。 + fn scene_of(html: &str) -> Scene { + let page = load_page(html, ""); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + build_scene(&page, &root) + } + + /// 渐变背景发 FillGradient:to right 端点从左到右、色标映射正确、 + /// 渐变线过盒中心。 + #[test] + fn gradient_background_emits_fill_gradient_with_stops() { + let scene = scene_of( + "
", + ); + let gradients: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillGradient { + rect, + start, + end, + stops, + .. + } => Some((*rect, *start, *end, stops.clone())), + _ => None, + }) + .collect(); + assert_eq!(gradients.len(), 1, "恰一条 FillGradient"); + let (rect, start, end, stops) = &gradients[0]; + assert!(start[0] < end[0], "to right 起点在左终点在右"); + assert_eq!(start[1], end[1], "to right 渐变线水平"); + assert_eq!(stops.len(), 2); + assert_eq!(stops[0].offset, 0.0); + assert_eq!(stops[0].color, Color::opaque(255, 0, 0)); + assert_eq!(stops[1].offset, 1.0); + assert_eq!(stops[1].color, Color::opaque(0, 0, 255)); + let center_x = rect.x + rect.width / 2.0; + assert_eq!((start[0] + end[0]) / 2.0, center_x, "渐变线过盒中心"); + } + + /// 渐变 × 圆角单指令:radii 随 border_radius,不另发圆角纯色背景。 + #[test] + fn gradient_with_radius_is_single_command() { + let scene = scene_of( + "
", + ); + assert!( + !scene + .commands + .iter() + .any(|command| matches!(command, Command::FillRoundedRect { .. })), + "背景色透明时不发纯色圆角指令" + ); + let gradients: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillGradient { radii, .. } => Some(*radii), + _ => None, + }) + .collect(); + assert_eq!(gradients, vec![[12.0; 4]], "渐变 radii 随 border_radius"); + } + + /// 有圆角背景走 FillRoundedRect;全 0 半径保持 FillRect 旧路径。 + #[test] + fn rounded_background_uses_fill_rounded_rect_zero_radius_keeps_fill_rect() { + let scene = scene_of( + "\ +
\ +
\ + ", + ); + let rounded: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::FillRoundedRect { radii, color, .. } => Some((*radii, *color)), + _ => None, + }) + .collect(); + assert_eq!(rounded, vec![([10.0; 4], Color::opaque(255, 0, 0))]); + assert!( + scene.commands.iter().any(|command| matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 255) + )), + "无圆角 div 保持 FillRect 旧路径" + ); + } + + /// 四边等宽 + 圆角 → 一条圆角描边;宽不等维持四条填充带(直角降级)。 + #[test] + fn uniform_borders_use_stroke_rounded_rect_unequal_keep_strips() { + let scene = scene_of( + "\ +
\ +
\ + ", + ); + let strokes: Vec<_> = scene + .commands + .iter() + .filter_map(|command| match command { + Command::StrokeRoundedRect { radii, width, .. } => Some((*radii, *width)), + _ => None, + }) + .collect(); + assert_eq!(strokes, vec![([8.0; 4], 4.0)], "等宽圆角边框一条描边"); + let black_strips = scene + .commands + .iter() + .filter(|command| { + matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 0) + ) + }) + .count(); + assert_eq!(black_strips, 4, "宽不等时四条直角填充带"); + } + + /// 场景中某色首个 `FillRect` 的下标。 + fn fill_index(scene: &Scene, color: Color) -> Option { + scene.commands.iter().position( + |command| matches!(command, Command::FillRect { color: c, .. } if *c == color), + ) + } + + /// z-index 基础定序:定位元素画在普通流之后、定位兄弟按整数升序。 + #[test] + fn z_index_orders_positioned_after_static_sorted_by_integer() { + let scene = scene_of( + "\ +
\ +
\ +
\ +
\ +
\ + ", + ); + let red = fill_index(&scene, Color::opaque(255, 0, 0)).expect("普通流红"); + let white = fill_index(&scene, Color::opaque(255, 255, 255)).expect("普通流白"); + let green = fill_index(&scene, Color::opaque(0, 128, 0)).expect("z=2 绿"); + let blue = fill_index(&scene, Color::opaque(0, 0, 255)).expect("z=1 蓝"); + let yellow = fill_index(&scene, Color::opaque(255, 255, 0)).expect("z=-1 黄"); + assert!(red < yellow && white < yellow, "定位元素画在普通流之后"); + assert!(yellow < blue && blue < green, "定位兄弟按 z-index 升序"); + } + + /// 选区高亮插入次序回归:高亮在背景之上、文字之下。 + #[test] + fn selection_highlight_stays_between_background_and_text() { + let page = load_page( + "

hello

", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let highlights = [LayoutRect { + x: 0.0, + y: 0.0, + width: 400.0, + height: 300.0, + }]; + let scene = build_scene_at_with_highlights(&page, &root, 0.0, 0.0, &highlights); + let background = fill_index(&scene, Color::opaque(0, 0, 255)).expect("div 背景"); + let highlight = scene + .commands + .iter() + .position(|command| matches!(command, Command::FillRect { color, .. } if *color == SELECTION_COLOR)) + .expect("选区高亮"); + let text = scene + .commands + .iter() + .position(|command| matches!(command, Command::DrawText { .. })) + .expect("文本命令"); + assert!(background < highlight, "高亮在背景之上"); + assert!(highlight < text, "高亮在文字之下"); + } + + /// 画布背景传播源:html 优先、body 回落、都无回落白。 + #[test] + fn canvas_background_prefers_html_then_body_falls_back_to_white() { + let page = load_page( + "", + "", + ); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(0, 0, 255) + ), + "html 背景优先传播" + ); + + let page = load_page("", ""); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(0, 128, 0) + ), + "html 无背景时 body 回落" + ); + + let page = load_page("", ""); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(255, 255, 255) + ), + "都无背景回落白" + ); + } + + /// 渐变背景传播:垫底色 + 铺满视口的 FillGradient(渐变线按视口矩形)。 + #[test] + fn canvas_gradient_propagates_as_viewport_fill_gradient() { + let page = load_page( + "", + "", + ); + let canvas = canvas_background_commands(&page, 400.0, 300.0); + assert_eq!(canvas.len(), 2, "垫底色 + 渐变两条指令"); + assert!( + matches!( + &canvas[0], + Command::FillRect { color, .. } if *color == Color::opaque(255, 255, 255) + ), + "传播色透明时垫白" + ); + let Command::FillGradient { + rect, + start, + end, + stops, + .. + } = &canvas[1] + else { + panic!("第二条应是渐变"); + }; + assert_eq!(rect.width, 400.0); + assert_eq!(rect.height, 300.0); + assert!(start[0] < end[0]); + assert_eq!(stops.len(), 2); + } + + /// 传播是搬移:body 背景被传播后场景中不再自绘;html 携带背景时 + /// body 背景不被传播、仍自绘。 + #[test] + fn propagated_background_is_suppressed_on_fragment() { + let page = load_page( + "

x

", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let scene = build_scene(&page, &root); + assert!( + scene.commands.iter().all(|command| !matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 128, 0) + )), + "被传播的 body 背景不再自绘" + ); + + let page = load_page( + "

x

", + "", + ); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let scene = build_scene(&page, &root); + assert!( + scene.commands.iter().any(|command| matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 128, 0) + )), + "body 背景未被传播时仍自绘" + ); + assert!( + scene.commands.iter().all(|command| !matches!( + command, + Command::FillRect { color, .. } if *color == Color::opaque(0, 0, 255) + )), + "html 背景被传播后不再自绘" + ); + } + + /// 场景中某色首个非黑装饰带(带高 = 0.06em)的下标与几何。 + fn decoration_band(scene: &Scene) -> Option { + scene.commands.iter().find_map(|command| match command { + Command::FillRect { rect, color } + if *color == Color::opaque(0, 0, 0) && (rect.height - 0.96).abs() < 1e-3 => + { + Some(*rect) + } + _ => None, + }) + } + + /// 装饰带几何:厚度 0.06em、underline 带顶 = 基线 + 0.08em、x 覆盖 + /// run 字形横向范围;overline / line-through 按经验偏移。 + #[test] + fn decoration_band_geometry_follows_run_baseline() { + let scene = scene_of( + "

hello

", + ); + let band = decoration_band(&scene).expect("underline 装饰带"); + assert!( + (band.height - 16.0 * 0.06).abs() < 1e-3, + "厚度 0.06em @16px" + ); + let baseline = scene + .commands + .iter() + .find_map(|command| match command { + Command::DrawText { baseline, .. } => Some(*baseline), + _ => None, + }) + .expect("文本命令"); + assert!( + (band.y - (baseline + 16.0 * 0.08)).abs() < 1e-3, + "带顶 = 基线 + 0.08em" + ); + // 装饰带垫在文字下:带下标早于本 run 的 DrawText + let band_index = scene + .commands + .iter() + .position(|command| matches!(command, Command::FillRect { rect, .. } if *rect == band)) + .expect("带下标"); + let text_index = scene + .commands + .iter() + .position(|command| matches!(command, Command::DrawText { .. })) + .expect("文本下标"); + assert!(band_index < text_index, "装饰带垫在文字下"); + + for (decoration, offset_em) in [("overline", -0.88), ("line-through", -0.30)] { + let scene = scene_of(&format!( + "

hello

" + )); + let band = decoration_band(&scene).unwrap_or_else(|| panic!("{decoration} 装饰带")); + let baseline = scene + .commands + .iter() + .find_map(|command| match command { + Command::DrawText { baseline, .. } => Some(*baseline), + _ => None, + }) + .expect("文本命令"); + assert!( + (band.y - (baseline + 16.0 * offset_em)).abs() < 1e-3, + "{decoration} 带顶 = 基线 {offset_em}em" + ); + } + } + + /// 非 solid(wavy)与透明装饰色不画(渲染仅 solid——偏差)。 + #[test] + fn decoration_skipped_for_non_solid_and_transparent() { + let scene = scene_of( + "

hello

", + ); + assert!(decoration_band(&scene).is_none(), "wavy 不按 solid 画"); + let scene = scene_of( + "

hello

", + ); + assert!(decoration_band(&scene).is_none(), "透明装饰色不画"); + } + + /// M6 回归(新指令):缓存场景经 `translated` 与直接以该 origin 构建 + /// 的场景逐字节一致(渐变端点 / 圆角 / 装饰带全部随平移)。 + #[test] + fn translated_matches_direct_build_with_new_commands() { + let page = load_page( + "\ +
\ +

hello

\ +
", + "", + ); + let shaper = nexty_text::ParleyTextShaper::new(); + let root = layout_page(&page, &shaper, 400.0).expect("root"); + let mut cache = SceneCache::new(); + let page_scene = cache.scene_for(1, &page, &root, 400.0, &[]); + let translated = page_scene.translated(0.0, 48.0); + let direct = build_scene_at_with_highlights(&page, &root, 0.0, 48.0, &[]); + assert_eq!(format!("{translated:?}"), format!("{direct:?}")); + } } diff --git a/crates/nexty-chrome/src/resources.rs b/crates/nexty-chrome/src/resources.rs index 120cb21..efce89c 100644 --- a/crates/nexty-chrome/src/resources.rs +++ b/crates/nexty-chrome/src/resources.rs @@ -1,21 +1,41 @@ -//! 子资源抓取与解码:样式表/图片清单 → URL 解析 → 并发抓取 → 级联输入。 +//! 子资源与主文档抓取编排:清单 → URL 解析 → 并发抓取 → 级联输入。 //! //! 职责边界:解析归 nexty-html(清单收集)、传输归 nexty-network(字节)、 -//! 解码归 nexty-paint(RGBA8)、级联归 nexty-css(多表合并)。本模块只做 -//! 编排:把清单里的相对 URL 解析为绝对地址,并发抓取后按清单顺序交回。 +//! 解码归 nexty-paint(RGBA8)与 nexty-network(文本编码)、级联归 nexty-css +//! (多表合并)。本模块只做编排:把清单里的相对 URL 解析为绝对地址,并发 +//! 抓取后按清单顺序交回;主文档的「抓取 → 解码 → 规划解析 → 子资源编排」 +//! 序列收口在 [`fetch_document`](K3 T5),地址栏输入的 scheme 规范化在 +//! [`normalize_address_bar_input`](决策见 +//! `docs/decisions/2026-10-31-addressbar-url.md`)。 //! //! 降级语义(T5 退出条件):单个子资源失败(URL 非法 / 传输错误 / 非 2xx / //! 解码失败)只跳过该资源,不影响其余渲染——外链 CSS 失败 = 该表不参与级联; //! 图片失败 = 该节点不产生像素(布局回退默认对象尺寸 300×150)。 +//! +//! 字体子资源(K4 T3):`@font-face` 的 `url()` 源按文档 base 解析后由 +//! [`FontOrchestrator`] 编排——收集(主线程,页面装配后)→ [`fetch_fonts`] +//! (后台线程,预算 [`MAX_FONT_BODY_BYTES`])→ 注册进会话级 +//! `nexty_text::FontRegistry`(主线程,字节到达时)。字体不在首轮 settle / +//! load 门控内(CSS Fonts font-display 的 swap 简化,偏差同 nexty-css): +//! 首帧用系统字体照常渲染,字节就绪注册后由调用方触发恰好一轮重排 + 重绘 +//! (注册表已接线的整形器自动生效,无需重建)。 +//! +//! 字体编排偏差:woff/woff2 提示的源跳过抓取(harfrust 不消费该容器格式); +//! 无提示的源乐观抓取,非字体数据由注册期拒收兜底(双重防线);`local()` +//! 源不经抓取(已安装字体的命中交给系统回退,不按 local 名单显式解析); +//! 会话去重按 URL 键控(与既有子资源同一键控语义)——同 URL 注册成功后, +//! 后续导航对同 URL 的不同描述符不再抓取(罕见边角,接受降级);负结果 +//! (404 / 非字体数据)不入会话集,再次导航时重试。 -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use nexty_css::Stylesheet; +use nexty_css::{FontFaceSource, FontFaceStyle, Stylesheet}; use nexty_dom::{Document, NodeId}; use nexty_html::StyleResource; -use nexty_network::{Method, NetworkError, NetworkFetcher, Request, resolve}; +use nexty_network::{Method, NetworkError, NetworkFetcher, Request, decode_document, resolve}; use nexty_paint::{Image, decode}; +use nexty_text::{FontFaceDescriptor, FontRegistry, FontStyle}; /// 并发抓取的线程上限:清单可能很大(真实页面几十张图),逐资源开线程 /// 会撑爆调度器;分块处理后每块内并发、块间串行。 @@ -32,6 +52,11 @@ pub const MAX_DOCUMENT_BODY_BYTES: usize = 10 * 1024 * 1024; pub const MAX_STYLESHEET_BODY_BYTES: usize = 10 * 1024 * 1024; pub const MAX_IMAGE_BODY_BYTES: usize = 50 * 1024 * 1024; +/// 字体响应体字节预算(K4 T3):单个字体文件(TTF/OTF 静态字体)远小于 +/// 图片压缩体积,20 MB 已远超真实 Web 字体;超预算按既有降级语义跳过该源 +/// (分配失败是 abort,panic 兜底兜不住)。 +pub const MAX_FONT_BODY_BYTES: usize = 20 * 1024 * 1024; + /// 抓取完成的子资源。 pub struct Subresources { /// 作者样式表,按级联优先级排列(inline 与外链按文档出现顺序交错)。 @@ -41,60 +66,242 @@ pub struct Subresources { pub images: HashMap>, } +/// 后台线程抓取产物(K1 T3:全 `Send` 数据面)。 +/// +/// K1 起 `Document` 携带监听器注册表(`Box`,!Send), +/// 只能在主线程构建——后台抓取线程不再产出 `Page`,只产出本结构(HTML + +/// 样式表字节 + 已解码图片,按绝对 URL 键控),随事件代理送回主线程后由 +/// [`assemble_page_data`] 装配。 +pub struct FetchedPageData { + /// 主文档 HTML(已 UTF-8 校验)。 + pub html: String, + /// 外链样式表字节:绝对 URL → 字节。失败/超时/超预算/URL 解析失败的 + /// URL 不在表内(降级语义:该表不参与级联)。 + pub css: HashMap>, + /// 已解码图片:绝对 URL → 像素。同上缺席 = 该图所有节点无像素;同 + /// URL 一份像素,装配期按 `Arc` 共享(M1 零拷贝)。 + pub images: HashMap>, +} + /// 抓取文档的子资源(CSS + 图片)。 /// /// `base_url` 是文档 URL(相对 URL 的解析基准);`about:blank` 等无网络 -/// 内部页直接传空文档清单即可(本函数对空清单返回空结果)。 +/// 内部页直接传空文档清单即可(本函数对空清单返回空结果)。不需 settle +/// 信号时用本便捷封装,等价于 settle 回调为空。 #[must_use] pub fn fetch_subresources( fetcher: &dyn NetworkFetcher, base_url: &str, document: &Document, ) -> Subresources { + fetch_subresources_with_settle(fetcher, base_url, document, &mut || {}) +} + +/// 抓取文档的子资源,并在**首轮编排 settle** 时触发一次 `on_settle`(K1 T3)。 +/// +/// settle = 清单里的全部抓取/解码任务都已出结果——个别资源的失败/超时/ +/// 超预算按降级语义跳过、不阻塞编排,因此无论结果如何回调恰触发一次。 +/// 回调供后台抓取线程投递「子资源就绪」信号(load 生命周期事件的派发 +/// 门控):只做信号记录,不得在回调内触碰 `Document`(跨线程约束—— +/// Document 随页面载荷回主线程后才可派发)。 +#[must_use] +pub fn fetch_subresources_with_settle( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + on_settle: &mut dyn FnMut(), +) -> Subresources { + let (css, images) = fetch_resolved(fetcher, base_url, document, on_settle); + assemble_from_maps(document, base_url, &css, &images) +} + +/// 抓取后台数据面(K1 T3):规划解析清单 → 并发抓取 → 解码,全部产出为 +/// `Send` 数据(无 `Document`/`NodeId`)。 +/// +/// `document` 是调用方在后台线程的规划解析(同一 HTML 稍后由主线程重建 +/// 正式文档);`html` 原样随产物回传。settle 回调语义同 +/// [`fetch_subresources_with_settle`]。 +#[must_use] +pub fn fetch_page_data( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + html: String, + on_settle: &mut dyn FnMut(), +) -> FetchedPageData { + let (css, images) = fetch_resolved(fetcher, base_url, document, on_settle); + FetchedPageData { html, css, images } +} + +/// 主文档抓取编排的产物(K3 T5):[`fetch_document`] 的成功输出,全部为 +/// `Send` 数据面,供后台线程随事件载荷送回主线程装配。 +pub struct FetchedDocument { + /// 页面数据面(HTML + 子资源字节/像素)。 + pub data: FetchedPageData, + /// 文档 base:响应的最终 URL(重定向落点;无重定向即请求 URL—— + /// WHATWG fetch 的 final URL 语义)。子资源相对地址的解析与装配查表 + /// 都按它进行:重定向后相对子资源随落点而非原始请求 URL。 + pub base_url: String, +} + +/// 抓取并编排主文档(导航管线的后台数据面入口,K3 T5)。 +/// +/// 编排序列与降级语义(错误串一律收敛,供错误页按页面语义渲染): +/// - 抓取失败(URL 非法 / 传输 / 超时)→ `Err`,错误串收敛为「错误类别」—— +/// 不回显上游原始错误(reqwest 的错误文本内含目标 URL,防注入); +/// - 非 2xx → `Err("HTTP <状态码>")`; +/// - 响应体超 [`MAX_DOCUMENT_BODY_BYTES`] → `Err`(巨响应的分配失败是 +/// abort,panic 兜底兜不住); +/// - 文本解码按 [`decode_document`] 的四层优先级(HTTP charset > BOM > +/// meta 预扫 > UTF-8),替换语义兜底不失败——非 UTF-8 页面不再进错误页; +/// - 解析与子资源编排见 [`fetch_page_data`](settle 恰触发一次,含失败 / +/// 超时 / 预算降级路径)。 +/// +/// `fetcher` 通常是被 `nexty_network::CachedFetcher` 装饰的共享实例(K3 +/// T4/T5):主文档与子资源同栈,同 URL 二次导航直接命中内存缓存。 +/// +/// # Errors +/// +/// 抓取失败、非 2xx、响应体超预算时返回用户可读的错误类别串。 +pub fn fetch_document(fetcher: &dyn NetworkFetcher, url: &str) -> Result { + let request = Request { + url: url.to_owned(), + method: Method::Get, + // 不少真实站点对无 UA 请求直接 403/429 + headers: vec![( + "User-Agent".to_owned(), + format!("Nexty/{}", env!("CARGO_PKG_VERSION")), + )], + }; + let response = fetcher + .fetch(&request) + .map_err(|error| load_error_text(&error).to_owned())?; + if !(200..300).contains(&response.status) { + return Err(format!("HTTP {}", response.status)); + } + if response.body.len() > MAX_DOCUMENT_BODY_BYTES { + return Err("响应体超出预算".to_owned()); + } + let content_type = content_type_header(&response.headers); + let decoded = decode_document(content_type, &response.body); + let document = nexty_html::parse_document(&decoded.text, nexty_html::ParseOptions::default()); + // 子资源 base = 最终 URL(重定向落点);mock 后端无重定向时即请求 URL + let data = fetch_page_data( + fetcher, + &response.final_url, + &document, + decoded.text, + &mut || {}, + ); + Ok(FetchedDocument { + data, + base_url: response.final_url, + }) +} + +/// 传输失败 → 错误类别文本。 +/// +/// 不回显上游原始错误串:reqwest 的错误文本内含目标 URL,而错误页是按 +/// 页面语义渲染的 HTML——错误信息只保留「类别」这一用户需要知道的内容。 +fn load_error_text(error: &NetworkError) -> &'static str { + match error { + NetworkError::InvalidUrl => "无效的地址", + NetworkError::Timeout => "请求超时", + NetworkError::Transport => "网络错误", + } +} + +/// 取响应头里的 Content-Type 值(头名不区分大小写;reqwest 的头表不保序, +/// 条目完整但顺序与源报文无关)。 +fn content_type_header(headers: &[(String, String)]) -> Option<&str> { + headers + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("content-type")) + .map(|(_, value)| value.as_str()) +} + +/// 地址栏输入的 URL 规范化(K3 T5 决策,完整记录见 +/// `docs/decisions/2026-10-31-addressbar-url.md`)。 +/// +/// 输入缺 scheme 时补 `http://`(HTTP-first,与主流浏览器地址栏默认一致; +/// 不猜测 `www.` 前缀、不在 http/https 间猜测升级)。scheme 判定按 WHATWG +/// URL 的 scheme 语法前缀匹配(`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) +/// ":"`)——带合法 scheme 的输入(`https://…`、`about:blank`、`mailto:…`) +/// 原样返回,各自走到其语义终点。合法性不在这里前置校验:非法输入交给 +/// 抓取路径,由协议白名单判 `InvalidUrl` 进既有错误页(单点错误路径)。 +#[must_use] +pub fn normalize_address_bar_input(input: &str) -> String { + if has_url_scheme(input) { + input.to_owned() + } else { + format!("http://{input}") + } +} + +/// 输入是否以 WHATWG URL 的 scheme 前缀开头 +/// (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`)。 +fn has_url_scheme(input: &str) -> bool { + let mut chars = input.chars(); + match chars.next() { + Some(first) if first.is_ascii_alphabetic() => {} + _ => return false, + } + for char in chars { + if char == ':' { + return true; + } + if !(char.is_ascii_alphanumeric() || char == '+' || char == '-' || char == '.') { + return false; + } + } + false +} + +/// 把后台数据面装配为子资源(主线程调用):按**本线程文档**的清单顺序 +/// 组装——inline 用原文、外链按绝对 URL 查表,失败/缺席的槽位跳过(降级 +/// 语义与 [`fetch_subresources`] 一致);图片按绝对 URL 查表映射到节点, +/// 同 URL 共享一份像素(M1)。 +#[must_use] +pub fn assemble_page_data( + document: &Document, + base_url: &str, + fetched: &FetchedPageData, +) -> Subresources { + assemble_from_maps(document, base_url, &fetched.css, &fetched.images) +} + +/// 共享抓取核心:收集清单 → URL 解析/去重 → 并发抓取(按类别带预算)→ +/// 解码,成功者按绝对 URL 打包。settle(含失败/超时/预算降级路径)在 +/// 返回前恰触发一次回调。 +fn fetch_resolved( + fetcher: &dyn NetworkFetcher, + base_url: &str, + document: &Document, + on_settle: &mut dyn FnMut(), +) -> (HashMap>, HashMap>) { let style_resources = nexty_html::collect_style_resources(document); let image_resources = nexty_html::collect_image_resources(document); - // ---- 阶段一:解析 URL,编出抓取任务 ---- - /// 清单顺序的样式表槽位:inline 有文本,外链等抓取,解析失败的丢弃。 - enum SheetSlot { - Inline(String), - External { url: String }, - Unresolved, - } - let mut css_urls: HashMap = HashMap::new(); // 绝对 URL → 任务序号 + // ---- 阶段一:解析 URL,编出抓取任务(同 URL 只抓一次)---- + let mut css_seen: HashSet = HashSet::new(); let mut css_tasks: Vec = Vec::new(); - let mut sheet_slots: Vec = Vec::new(); - let mut image_urls: HashMap> = HashMap::new(); // 绝对 URL → 节点 + let mut image_seen: HashSet = HashSet::new(); let mut image_tasks: Vec = Vec::new(); for resource in &style_resources { - match resource { - StyleResource::Inline { css } => { - sheet_slots.push(SheetSlot::Inline(css.clone())); - } - StyleResource::External { href } => match resolve(base_url, href) { - Ok(url) => { - // 同一 URL 只抓一次,级联里按首现位置参与 - if css_urls.insert(url.clone(), css_tasks.len()).is_none() { - css_tasks.push(url.clone()); - } - sheet_slots.push(SheetSlot::External { url }); - } - // URL 解析失败 = 该表不参与级联(降级) - Err(_) => sheet_slots.push(SheetSlot::Unresolved), - }, + if let StyleResource::External { href } = resource + && let Ok(url) = resolve(base_url, href) + && css_seen.insert(url.clone()) + { + css_tasks.push(url); } } for resource in &image_resources { - if let Ok(url) = resolve(base_url, &resource.src) { - image_urls - .entry(url.clone()) - .or_insert_with(|| { - image_tasks.push(url.clone()); - Vec::new() - }) - .push(resource.node); + if let Ok(url) = resolve(base_url, &resource.src) + && image_seen.insert(url.clone()) + { + image_tasks.push(url); } } @@ -102,49 +309,253 @@ pub fn fetch_subresources( let css_bytes = fetch_many(fetcher, &css_tasks, MAX_STYLESHEET_BODY_BYTES); let image_bytes = fetch_many(fetcher, &image_tasks, MAX_IMAGE_BODY_BYTES); - // ---- 阶段三:按清单顺序重组 ---- - // inline 与抓到的外链按文档出现顺序交错产出(顺序即级联优先级); - // 抓取失败的外链槽位跳过 + // ---- 阶段三:成功者按绝对 URL 打包(图片解码在本线程完成)---- + let mut css = HashMap::new(); + for (task, url) in css_tasks.iter().enumerate() { + if let Some(bytes) = &css_bytes[task] { + css.insert(url.clone(), bytes.clone()); + } + } + let mut images: HashMap> = HashMap::new(); + for (task, url) in image_tasks.iter().enumerate() { + let Some(bytes) = &image_bytes[task] else { + continue; // 抓取失败:该图所有节点都无像素(降级) + }; + if let Ok(image) = decode(bytes) { + images.insert(url.clone(), Arc::new(image)); + } // 解码失败:同样降级 + } + + // ---- 首轮编排 settle:全部抓取/解码任务已出结果(含降级路径), + // 恰触发一次回调 ---- + on_settle(); + + (css, images) +} + +/// 按**本线程文档**的清单顺序装配(inline 用原文、外链按绝对 URL 查表、 +/// 图片按 URL 映射到节点):顺序即级联优先级,失败/缺席槽位跳过。 +fn assemble_from_maps( + document: &Document, + base_url: &str, + css: &HashMap>, + images: &HashMap>, +) -> Subresources { let mut stylesheets = Vec::new(); - for slot in &sheet_slots { - match slot { - SheetSlot::Inline(css) => stylesheets.push(Stylesheet::parse(css)), - SheetSlot::External { url } => { - let task = css_urls[url]; - if let Some(bytes) = &css_bytes[task] { + for resource in nexty_html::collect_style_resources(document) { + match resource { + StyleResource::Inline { css } => stylesheets.push(Stylesheet::parse(&css)), + StyleResource::External { href } => { + if let Ok(url) = resolve(base_url, &href) + && let Some(bytes) = css.get(&url) + { let css = String::from_utf8_lossy(bytes); stylesheets.push(Stylesheet::parse(&css)); } } - SheetSlot::Unresolved => {} } } - let mut images: HashMap> = HashMap::new(); - for (task, url) in image_tasks.iter().enumerate() { - let Some(bytes) = &image_bytes[task] else { - continue; // 抓取失败:该图所有节点都无像素(降级) - }; - match decode(bytes) { - Ok(image) => { - if let Some(nodes) = image_urls.get(url) { - // 一份像素按 Arc 共享给该 URL 的全部节点(M1 零拷贝) - let shared = Arc::new(image); - for node in nodes { - images.insert(*node, Arc::clone(&shared)); + let mut images_by_node: HashMap> = HashMap::new(); + for resource in nexty_html::collect_image_resources(document) { + if let Ok(url) = resolve(base_url, &resource.src) + && let Some(image) = images.get(&url) + { + // 一份像素按 Arc 共享给该 URL 的全部节点(M1 零拷贝) + images_by_node.insert(resource.node, Arc::clone(image)); + } + } + + Subresources { + stylesheets, + images: images_by_node, + } +} + +/// @font-face 待抓取源(K4 T3):绝对 URL + 注册用描述符。 +/// +/// 同一 URL 可携带不同描述符出现多次(同一文件按多条 `@font-face` 声明为 +/// 不同 weight/style face);抓取按 URL 去重,注册按描述符逐条进行。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FontRequest { + /// 字体文件的绝对地址(已按文档 base 解析,`FetchedDocument.base_url` + /// 语义——重定向落点)。 + pub url: String, + /// 注册描述符:css `FontFaceRule` → text `FontFaceDescriptor` 映射 + /// (weight 缺省 400、style 缺省 normal——CSS Fonts 描述符 initial)。 + pub descriptor: FontFaceDescriptor, +} + +/// 抓取成功的字体字节(后台线程 → 主线程注册,全 `Send` 数据面)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FetchedFont { + /// 来源绝对 URL(会话去重键)。 + pub url: String, + /// 注册描述符(与请求一致)。 + pub descriptor: FontFaceDescriptor, + /// 字体文件字节。 + pub bytes: Vec, +} + +/// 一批字体字节的注册结果(K4 T3)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct FontRegistration { + /// 新注册成功的 face 数:> 0 时调用方触发恰好一轮重排 + 重绘。 + pub registered: usize, + /// 注册失败(非字体数据 / 空族名)跳过的源数:页面回退系统字体照常 + /// 渲染(降级语义)。 + pub rejected: usize, +} + +/// 字体子资源编排会话(K4 T3):会话级注册表 + 已注册 URL 集。 +/// +/// 会话级 = 浏览器生命周期内持续有效:跨导航共享已注册字体(同 URL 重复 +/// 导航不再抓取)。三段编排与主文档抓取同构,全部为纯逻辑、可无头测试: +/// ① [`FontOrchestrator::collect`](主线程,页面装配后)收集待抓取源; +/// ② [`fetch_fonts`](后台线程)并发抓取; +/// ③ [`FontOrchestrator::register`](主线程,字节到达)注册进注册表。 +/// +/// 注册表经 [`FontOrchestrator::registry`] 交给 `ParleyTextShaper::with_registry` +/// 接线(构造点一次完成);此后每次 `register` 即生效,无需重建整形器 +/// (nexty-text T2 语义)。本类型不持 `Document`,跨线程边界只传 +/// [`FontRequest`] / [`FetchedFont`] 数据面。 +#[derive(Default)] +pub struct FontOrchestrator { + /// 会话级 @font-face 注册表(`Clone` = 廉价共享句柄)。 + registry: FontRegistry, + /// 已成功注册的字体 URL 集(会话去重;只记成功——负结果允许重试)。 + fetched: HashSet, +} + +impl FontOrchestrator { + /// 空会话(空注册表)。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 会话级注册表句柄(供 `ParleyTextShaper::with_registry` 接线)。 + #[must_use] + pub fn registry(&self) -> &FontRegistry { + &self.registry + } + + /// 收集阶段(主线程,页面装配后):从解析后的作者样式表收集 `@font-face` + /// 的 `url()` 源([CSS Fonts 4 §4](https://drafts.csswg.org/css-fonts-4/#font-face-rule) + /// 简化档)。 + /// + /// 过滤规则:`local()` 源不抓取;format 提示含 woff/woff2 的源跳过 + /// (harfrust 不消费,偏差);URL 非法跳过;会话内已注册 URL 跳过; + /// 同页内同(URL, 描述符)去重。描述符映射按 css 层映射表:weight + /// `unwrap_or(400)`、style `None→Normal` / `Italic→Italic`。 + #[must_use] + pub fn collect(&self, stylesheets: &[Stylesheet], base_url: &str) -> Vec { + let mut requests: Vec = Vec::new(); + // 页内去重键(URL, family, weight, style):同 URL 同描述符只出一项 + let mut seen: HashSet<(String, String, u16, FontStyle)> = HashSet::new(); + for sheet in stylesheets { + for face in sheet.font_faces() { + let descriptor = FontFaceDescriptor { + family: face.family.clone(), + weight: face.weight.unwrap_or(400), + style: match face.style { + Some(FontFaceStyle::Italic) => FontStyle::Italic, + Some(FontFaceStyle::Normal) | None => FontStyle::Normal, + }, + }; + for source in &face.sources { + let FontFaceSource::Url { url, format_hints } = source else { + continue; // local():已安装字体,不经网络 + }; + if format_hints.iter().any(|hint| is_skipped_font_format(hint)) { + continue; // woff/woff2:harfrust 不消费(偏差),跳过 + } + let Ok(absolute) = resolve(base_url, url) else { + continue; // URL 非法:降级跳过(回退系统字体) + }; + if self.fetched.contains(&absolute) { + continue; // 会话去重:同 URL 已注册,不重复抓取 + } + let key = ( + absolute.clone(), + descriptor.family.clone(), + descriptor.weight, + descriptor.style, + ); + if seen.insert(key) { + requests.push(FontRequest { + url: absolute, + descriptor: descriptor.clone(), + }); } } } - Err(_) => continue, // 解码失败:同样降级 } + requests } - Subresources { - stylesheets, - images, + /// 注册阶段(主线程,字节到达):逐条注册进注册表。 + /// + /// `InvalidFontData` / `EmptyFamily` 跳过并记入 [`FontRegistration::rejected`], + /// 页面回退系统字体照常渲染(降级语义);注册成功的 URL 记入会话集 + /// (跨导航去重)。调用方按 [`FontRegistration::registered`] > 0 触发 + /// **恰好一轮**重排 + 重绘——重复/迟到载荷注册数为 0,不产生额外重排。 + pub fn register(&mut self, fonts: Vec) -> FontRegistration { + let mut result = FontRegistration::default(); + for font in fonts { + // 会话去重:同 URL 已注册的载荷(迟到 / 竞态重复抓取)跳过—— + // 这是「registered > 0 恰好出现一次 → 重排恰一轮」的保证。 + if self.fetched.contains(&font.url) { + continue; + } + match self.registry.register(font.bytes, font.descriptor) { + Ok(()) => { + // 只记成功:失败的源(404 / 非字体数据)再次导航时重试 + self.fetched.insert(font.url); + result.registered += 1; + } + Err(_) => result.rejected += 1, + } + } + result } } +/// 抓取阶段(后台线程):并发抓取一批字体源,成功者逐请求打包。 +/// +/// 同 URL 只抓一次(复用既有子资源 URL 键控语义,多个描述符共享一份字节); +/// 预算 [`MAX_FONT_BODY_BYTES`],超预算 / 非 2xx / 传输错误按降级语义缺席 +/// (该源回退系统字体)。空请求列表返回空结果,不起任何抓取。 +#[must_use] +pub fn fetch_fonts(fetcher: &dyn NetworkFetcher, requests: &[FontRequest]) -> Vec { + // URL 去重(保序):同 URL 只抓一次 + let mut urls: Vec = Vec::new(); + for request in requests { + if !urls.contains(&request.url) { + urls.push(request.url.clone()); + } + } + let bodies = fetch_many(fetcher, &urls, MAX_FONT_BODY_BYTES); + requests + .iter() + .filter_map(|request| { + let index = urls.iter().position(|url| *url == request.url)?; + let bytes = bodies[index].clone()?; + Some(FetchedFont { + url: request.url.clone(), + descriptor: request.descriptor.clone(), + bytes, + }) + }) + .collect() +} + +/// harfrust 不消费的容器格式提示(woff / woff2,K4 记偏差):带这些提示的 +/// 源跳过抓取。比较不区分 ASCII 大小写(format 串规范未约束大小写)。 +fn is_skipped_font_format(hint: &str) -> bool { + hint.eq_ignore_ascii_case("woff") || hint.eq_ignore_ascii_case("woff2") +} + /// 并发抓取一组 URL,返回与 `urls` 等长的结果槽(失败或超预算为 `None`)。 fn fetch_many( fetcher: &dyn NetworkFetcher, @@ -240,16 +651,19 @@ mod tests { status: 200, headers: Vec::new(), body: body.clone(), + final_url: request.url.clone(), }), Some(Err(status)) => Ok(nexty_network::Response { status: *status, headers: Vec::new(), body: Vec::new(), + final_url: request.url.clone(), }), None => Ok(nexty_network::Response { status: 404, headers: Vec::new(), body: Vec::new(), + final_url: request.url.clone(), }), } } @@ -403,4 +817,237 @@ mod tests { ); assert_eq!(resources.images.len(), 1, "超预算图片跳过,预算内的保留"); } + + // ---- 地址栏输入规范化(K3 T5)---- + + #[test] + fn address_bar_input_without_scheme_gets_http_prefix() { + assert_eq!( + normalize_address_bar_input("example.com"), + "http://example.com" + ); + assert_eq!( + normalize_address_bar_input("example.com/path?q=1"), + "http://example.com/path?q=1" + ); + // 空输入同样补全:交给抓取路径进错误页(不白屏、不 panic) + assert_eq!(normalize_address_bar_input(""), "http://"); + } + + #[test] + fn address_bar_input_with_scheme_is_untouched() { + assert_eq!( + normalize_address_bar_input("https://example.com"), + "https://example.com" + ); + assert_eq!( + normalize_address_bar_input("http://example.com"), + "http://example.com" + ); + // 内部 scheme 与非网络 scheme 原样返回,各自走到其语义终点 + assert_eq!(normalize_address_bar_input("about:blank"), "about:blank"); + assert_eq!( + normalize_address_bar_input("mailto:a@b.test"), + "mailto:a@b.test" + ); + } + + #[test] + fn address_bar_scheme_prefix_follows_whatwg_syntax() { + // scheme 首字符必须是字母,否则视为无 scheme + assert_eq!(normalize_address_bar_input("1http://x"), "http://1http://x"); + // scheme 字符集外(空格)截断判定 → 无 scheme + assert_eq!(normalize_address_bar_input("ht tp://x"), "http://ht tp://x"); + // scheme 允许字母/数字/+-. + assert_eq!(normalize_address_bar_input("a-b.c+x:rest"), "a-b.c+x:rest"); + } + + // ---- @font-face 字体子资源编排(K4 T3)---- + + /// 测试字体字节:nexty-text T2 入库的 OFL 字体资产(工作区内复用同一 + /// 份,不另入库副本)。 + fn test_font_bytes() -> Vec { + std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../nexty-text/tests/data/SpaceMono-Regular.ttf" + )) + .expect("test font asset (nexty-text tests/data)") + } + + /// 构造一个字体抓取请求。 + fn font_request(url: &str, family: &str, weight: u16, style: FontStyle) -> FontRequest { + FontRequest { + url: url.to_owned(), + descriptor: FontFaceDescriptor { + family: family.to_owned(), + weight, + style, + }, + } + } + + /// 描述符映射(weight 缺省 400、style 缺省 normal/italic)+ 过滤 + /// (woff/woff2 提示、local())+ 页内去重。 + #[test] + fn font_requests_map_descriptors_and_filter_sources() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; src: url(a.ttf); } \ + @font-face { font-family: W; src: url(w.woff2) format(\"woff2\"); } \ + @font-face { font-family: W2; src: url(w2.woff) format(\"woff\"); } \ + @font-face { font-family: L; src: local(\"Sys X\"), url(l.ttf); font-weight: 700; font-style: italic; } \ + @font-face { font-family: OnlyLocal; src: local(\"Sys Y\"); } \ + @font-face { font-family: A; src: url(a.ttf); }", + ); + let fonts = FontOrchestrator::new(); + let requests = fonts.collect(std::slice::from_ref(&sheet), BASE); + assert_eq!( + requests, + vec![ + font_request("https://page.test/a.ttf", "A", 400, FontStyle::Normal), + font_request("https://page.test/l.ttf", "L", 700, FontStyle::Italic), + ], + "woff/woff2 提示与 local() 跳过;描述符按映射表(缺省 400/normal,italic 映射);页内同 URL 同描述符去重" + ); + } + + /// 相对 URL 按文档 base 解析、非法 URL 跳过、会话去重(注册成功后 + /// 同 URL 再收集为空——同 URL 重复导航不重复抓取的收集侧语义)。 + #[test] + fn font_requests_resolve_base_skip_invalid_and_dedupe_by_session() { + let sheet = Stylesheet::parse( + "@font-face { font-family: A; src: url(../fonts/a.ttf); } \ + @font-face { font-family: Bad; src: url(\"http://bad host/x.ttf\"); }", + ); + let fonts = FontOrchestrator::new(); + let requests = fonts.collect( + std::slice::from_ref(&sheet), + "https://page.test/dir/page.html", + ); + assert_eq!( + requests, + vec![font_request( + "https://page.test/fonts/a.ttf", + "A", + 400, + FontStyle::Normal + )], + "相对 URL 按 base 解析,非法 URL 跳过" + ); + + let mut fonts = FontOrchestrator::new(); + let sheet = Stylesheet::parse("@font-face { font-family: A; src: url(a.ttf) }"); + assert_eq!(fonts.collect(std::slice::from_ref(&sheet), BASE).len(), 1); + let registered = fonts.register(vec![FetchedFont { + url: "https://page.test/a.ttf".to_owned(), + descriptor: font_request("x", "A", 400, FontStyle::Normal).descriptor, + bytes: test_font_bytes(), + }]); + assert_eq!(registered.registered, 1); + assert!( + fonts.collect(std::slice::from_ref(&sheet), BASE).is_empty(), + "注册成功后同 URL 不再收集(跨导航会话去重)" + ); + } + + /// 抓取:同 URL 只抓一次(多描述符共享一份字节);404 / 超预算按 + /// 降级语义缺席。 + #[test] + fn fetch_fonts_dedupes_urls_and_degrades_failures_and_budget() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/a.ttf", b"font-a"); + fetcher.fail("https://page.test/lost.ttf", 404); + fetcher.serve( + "https://page.test/huge.ttf", + &vec![0u8; MAX_FONT_BODY_BYTES + 1], + ); + let requests = vec![ + font_request("https://page.test/a.ttf", "A", 400, FontStyle::Normal), + font_request("https://page.test/a.ttf", "A", 700, FontStyle::Normal), + font_request("https://page.test/lost.ttf", "B", 400, FontStyle::Normal), + font_request("https://page.test/huge.ttf", "C", 400, FontStyle::Normal), + ]; + + let fonts = fetch_fonts(&fetcher, &requests); + assert_eq!( + fetcher + .hits + .lock() + .unwrap() + .iter() + .filter(|url| **url == "https://page.test/a.ttf") + .count(), + 1, + "同 URL 只抓一次" + ); + assert_eq!( + fonts.len(), + 2, + "404 与超预算缺席,成功 URL 的两个描述符都在" + ); + assert_eq!(fonts[0].bytes, b"font-a"); + assert_eq!(fonts[0].descriptor.weight, 400); + assert_eq!( + fonts[1].descriptor.weight, 700, + "同 URL 不同描述符共享一次抓取" + ); + } + + /// 注册:非字体数据拒收记数且不入会话集(可重试);成功注册记入 + /// 会话集;重复/迟到载荷(同 URL 已注册)跳过——恰一轮重排的保证。 + #[test] + fn register_rejects_invalid_data_marks_success_and_skips_duplicates() { + let mut fonts = FontOrchestrator::new(); + let junk_sheet = Stylesheet::parse("@font-face { font-family: Junk; src: url(junk.ttf) }"); + let a_sheet = Stylesheet::parse("@font-face { font-family: A; src: url(a.ttf) }"); + + let rejected = fonts.register(vec![FetchedFont { + url: "https://page.test/junk.ttf".to_owned(), + descriptor: font_request("x", "Junk", 400, FontStyle::Normal).descriptor, + bytes: b"not a font".to_vec(), + }]); + assert_eq!( + rejected, + FontRegistration { + registered: 0, + rejected: 1 + }, + "非字体数据拒收记数" + ); + assert_eq!( + fonts.collect(std::slice::from_ref(&junk_sheet), BASE).len(), + 1, + "负结果不入会话集,再次导航可重试" + ); + + let font_bytes = test_font_bytes(); + let payload = FetchedFont { + url: "https://page.test/a.ttf".to_owned(), + descriptor: font_request("x", "A", 400, FontStyle::Normal).descriptor, + bytes: font_bytes.clone(), + }; + let ok = fonts.register(vec![payload.clone()]); + assert_eq!( + ok, + FontRegistration { + registered: 1, + rejected: 0 + } + ); + assert!( + fonts + .collect(std::slice::from_ref(&a_sheet), BASE) + .is_empty(), + "成功注册后同 URL 不再收集" + ); + // 重复/迟到载荷:同 URL 已注册 → 跳过(registered == 0 → 不重排) + let duplicate = fonts.register(vec![payload]); + assert_eq!( + duplicate, + FontRegistration { + registered: 0, + rejected: 0 + }, + "同 URL 重复载荷不重复注册" + ); + } } diff --git a/crates/nexty-chrome/tests/chrome.rs b/crates/nexty-chrome/tests/chrome.rs index f06e3e1..2d17b9e 100644 --- a/crates/nexty-chrome/tests/chrome.rs +++ b/crates/nexty-chrome/tests/chrome.rs @@ -10,6 +10,8 @@ use nexty_text::ParleyTextShaper; use nexty_chrome::pipeline::{self, Viewport}; use nexty_chrome::render::{RenderError, RenderThread}; +use nexty_chrome::resources::{fetch_document, normalize_address_bar_input}; +use nexty_network::CachedFetcher; fn approx(a: f32, b: f32) -> bool { (a - b).abs() < 0.01 @@ -25,7 +27,18 @@ fn end_to_end_page_renders_background_and_border() { let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); let scene = pipeline::build_scene(&page, &root); - // 显示列表应包含:body 白底、box 蓝底、四条红边、一条文本 + // body 白底按 CSS 2.2 §14.2 传播到画布(搬移语义:场景中不再发 body + // 白底,由呈现层把 canvas_background_commands 插到场景底部) + let canvas = pipeline::canvas_background_commands(&page, 400.0, 300.0); + assert!( + matches!( + &canvas[..], + [Command::FillRect { color, .. }] if *color == Color::opaque(255, 255, 255) + ), + "body 白底传播为画布白色底指令" + ); + + // 显示列表应包含:box 蓝底、四条红边、一条文本 let fills: Vec<_> = scene .commands .iter() @@ -40,9 +53,6 @@ fn end_to_end_page_renders_background_and_border() { .filter(|command| matches!(command, Command::DrawText { .. })) .collect(); - let has_white = fills.iter().any(|(rect, color)| { - color.r == 255 && color.g == 255 && color.b == 255 && rect.width > 300.0 - }); let has_blue = fills .iter() .any(|(_, color)| *color == Color::opaque(0, 128, 255)); @@ -50,7 +60,6 @@ fn end_to_end_page_renders_background_and_border() { .iter() .filter(|(_, color)| *color == Color::opaque(255, 0, 0)) .count(); - assert!(has_white, "body 白底"); assert!(has_blue, "box 蓝底"); assert_eq!(red_strips, 4, "四条红边"); assert_eq!(texts.len(), 1, "hello 一个文本 run"); @@ -503,17 +512,33 @@ use std::collections::BTreeMap; use std::sync::Mutex; /// 内存 mock fetcher:URL → body / 状态码;未登记的 URL 返回 404。 +/// K3 T5 起支持按 URL 的响应头与 final_url 覆盖(charset / 缓存头 / +/// 重定向落点模拟),并记录抓取计数供缓存命中断言。 struct MockFetcher { routes: Mutex, u16>>>, + /// 按 URL 的响应头(未登记 = 空头表)。 + headers: Mutex>>, + /// 按 URL 的 final_url 覆盖(重定向落点;未登记 = 请求 URL)。 + final_urls: Mutex>, + /// 抓取计数(共享句柄:CachedFetcher 包住 mock 后仍可读内部计数)。 + hits: Arc>>, } impl MockFetcher { fn new() -> Self { Self { routes: Mutex::new(BTreeMap::new()), + headers: Mutex::new(BTreeMap::new()), + final_urls: Mutex::new(BTreeMap::new()), + hits: Arc::new(Mutex::new(Vec::new())), } } + /// 抓取计数句柄:mock 被搬进 CachedFetcher 后从外部读计数用。 + fn hits(&self) -> Arc>> { + self.hits.clone() + } + fn serve(&self, url: &str, body: &[u8]) { self.routes .lock() @@ -527,26 +552,58 @@ impl MockFetcher { .unwrap() .insert(url.to_owned(), Err(status)); } + + /// 带响应头的登记(charset / cache-control 等用例)。 + fn serve_with_headers(&self, url: &str, headers: Vec<(String, String)>, body: &[u8]) { + self.serve(url, body); + self.headers.lock().unwrap().insert(url.to_owned(), headers); + } + + /// 模拟重定向落点:响应的 final_url 与请求 URL 不同。 + fn serve_final_url(&self, url: &str, final_url: &str, body: &[u8]) { + self.serve(url, body); + self.final_urls + .lock() + .unwrap() + .insert(url.to_owned(), final_url.to_owned()); + } } impl NetworkFetcher for MockFetcher { fn fetch(&self, request: &Request) -> Result { + self.hits.lock().unwrap().push(request.url.clone()); let routes = self.routes.lock().unwrap(); + let final_url = self + .final_urls + .lock() + .unwrap() + .get(&request.url) + .cloned() + .unwrap_or_else(|| request.url.clone()); match routes.get(&request.url) { Some(Ok(body)) => Ok(Response { status: 200, - headers: Vec::new(), + headers: self + .headers + .lock() + .unwrap() + .get(&request.url) + .cloned() + .unwrap_or_default(), body: body.clone(), + final_url, }), Some(Err(status)) => Ok(Response { status: *status, headers: Vec::new(), body: Vec::new(), + final_url, }), None => Ok(Response { status: 404, headers: Vec::new(), body: Vec::new(), + final_url, }), } } @@ -915,3 +972,464 @@ fn hardening_full_chain_body() { "巨图声明无像素、无 DrawImage" ); } + +// ---- K1 T3:事件模型接线——生命周期派发(先派发后默认、各恰一次) ---- + +use nexty_chrome::pipeline::PendingLifecycle; +use nexty_dom::{DOM_CONTENT_LOADED, Event, EventListener, EventLoop, LOAD}; +use std::cell::RefCell; +use std::rc::Rc; + +type LifecycleLog = Rc>>; + +/// 生命周期计数钩子:把派发的事件类型记入日志。 +fn lifecycle_recorder(log: &LifecycleLog, label: &'static str) -> Box { + let log = Rc::clone(log); + Box::new(move |_event: &mut Event| log.borrow_mut().push(label)) +} + +/// ③ DOMContentLoaded 在解析后、load 在子资源 settle 后各恰一次:走与 +/// app.rs 后台线程相同的编排序列(真实 parse → settle 回调信号 → +/// build_page → 信号 post → 排空),计数钩子挂在文档根上。 +#[test] +fn lifecycle_events_fire_once_each_in_order_after_signals() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/ext.css", b"p { color: blue }"); + let html = "

hi

"; + + // 信号捕获点与 app.rs load 的后台线程一致 + let document = nexty_html::parse_document(html, ParseOptions::default()); + let parsed = true; // parse_document 返回 + let mut settled = false; + let sub = resources::fetch_subresources_with_settle( + &fetcher, + "https://page.test/index.html", + &document, + &mut || settled = true, + ); + assert!(settled, "首轮编排 settle(成功路径)恰触发一次回调"); + + let mut page = pipeline::build_page(document, sub.stylesheets, sub.images); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document.add_listener( + root, + DOM_CONTENT_LOADED, + false, + lifecycle_recorder(&log, "dcl"), + ); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + // 信号齐 → pipeline 单处钩子 post → EventLoop 排空派发 + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: parsed, + load: settled, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!( + *log.borrow(), + ["dcl", "load"], + "DOMContentLoaded 先于 load,各恰一次" + ); + + // 队列已空:重复排空不重复派发(每页各恰一次) + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(log.borrow().len(), 2, "排空后无重复派发"); +} + +/// ③(降级路径):子资源全部失败/超时/超预算时 settle 回调仍恰触发一次, +/// load 照常派发(含失败/超时/预算降级的语义)。 +#[test] +fn lifecycle_load_fires_after_settled_degraded_subresources() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/broken.css", 500); + fetcher.fail("https://page.test/lost.png", 404); + let html = "\ +

hi

"; + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let mut settled = false; + let sub = resources::fetch_subresources_with_settle( + &fetcher, + "https://page.test/index.html", + &document, + &mut || settled = true, + ); + assert!(settled, "全失败路径 settle 回调仍触发"); + assert!(sub.stylesheets.is_empty() && sub.images.is_empty()); + + let mut page = pipeline::build_page(document, sub.stylesheets, sub.images); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: settled, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["load"], "降级 settle 后 load 恰一次"); +} + +/// ③(门控):信号未到不派发;只到解析信号只派发 DOMContentLoaded—— +/// K3/K4 异步 settle 的接缝。 +#[test] +fn lifecycle_events_wait_for_their_signals() { + let mut page = pipeline::load_page("hi", ""); + let log: LifecycleLog = Rc::new(RefCell::new(Vec::new())); + let root = page.document.root(); + page.document.add_listener( + root, + DOM_CONTENT_LOADED, + false, + lifecycle_recorder(&log, "dcl"), + ); + page.document + .add_listener(root, LOAD, false, lifecycle_recorder(&log, "load")); + + let mut event_loop = EventLoop::new(); + page.post_lifecycle_tasks(&mut event_loop, PendingLifecycle::default()); + event_loop.run_pending_tasks(&mut page.document); + assert!(log.borrow().is_empty(), "无信号不派发"); + + page.post_lifecycle_tasks( + &mut event_loop, + PendingLifecycle { + dom_content_loaded: true, + load: false, + }, + ); + event_loop.run_pending_tasks(&mut page.document); + assert_eq!(*log.borrow(), ["dcl"], "只到解析信号 → 仅 DOMContentLoaded"); +} + +// ---- K3 T5:导航编排接线(主文档解码 / 缓存接入 / 重定向落点) ---- + +/// 主文档解码:Content-Type charset=gbk → 按 GBK 解码,标题正确—— +/// 非 UTF-8 页面不再进错误页(错误页 = fetch_document 返回 Err)。 +#[test] +fn gbk_document_with_content_type_charset_decodes_title() { + let fetcher = MockFetcher::new(); + // 「中文」的 GBK 编码字节(0xD6 0xD0 0xCE 0xC4) + let mut body = b"".to_vec(); + body.extend_from_slice(&[0xD6, 0xD0, 0xCE, 0xC4]); + body.extend_from_slice(b""); + fetcher.serve_with_headers( + "https://page.test/gbk.html", + vec![( + "content-type".to_owned(), + "text/html; charset=gbk".to_owned(), + )], + &body, + ); + + let fetched = fetch_document(&fetcher, "https://page.test/gbk.html") + .expect("GBK 页面应成功返回而非错误页"); + let document = nexty_html::parse_document(&fetched.data.html, ParseOptions::default()); + assert_eq!( + pipeline::document_title(&document).as_deref(), + Some("中文"), + "GBK 字节按 charset 解码为可读标题" + ); +} + +/// 无 charset 提示的 GBK 字节:按默认 UTF-8 替换语义兑底,不 panic、 +/// 不进错误页(Err)。非法序列退化为 U+FFFD 可见。 +#[test] +fn gbk_bytes_without_charset_hint_degrade_without_panic() { + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/raw.html", &[0xD6, 0xD0, 0xCE, 0xC4]); + + let fetched = + fetch_document(&fetcher, "https://page.test/raw.html").expect("解码兑底路径不失败"); + assert!( + fetched.data.html.contains('\u{FFFD}'), + "无提示的非法 UTF-8 序列替换为 U+FFFD" + ); +} + +/// 缓存接入:CachedFetcher 包裹后同 URL 二次导航命中内存缓存—— +/// mock 计数恰 1 次,两次产物一致。 +#[test] +fn cached_fetcher_serves_second_navigation_from_cache() { + let fetcher = MockFetcher::new(); + fetcher.serve_with_headers( + "https://page.test/doc.html", + vec![("cache-control".to_owned(), "max-age=60".to_owned())], + b"cachedx", + ); + let hits = fetcher.hits(); + let cached = CachedFetcher::new(fetcher); + + let first = fetch_document(&cached, "https://page.test/doc.html").expect("first"); + let second = fetch_document(&cached, "https://page.test/doc.html").expect("second"); + assert_eq!(first.data.html, second.data.html, "缓存体与首抓一致"); + assert_eq!( + hits.lock().unwrap().len(), + 1, + "同 URL 二次导航命中缓存,网络只打一次" + ); +} + +/// 重定向落点:响应 final_url 与请求 URL 不同时,子资源相对地址按落点 +/// (base_url)解析,不按原始请求 URL(WHATWG fetch final URL 语义)。 +#[test] +fn subresources_resolve_against_final_url_after_redirect() { + let fetcher = MockFetcher::new(); + fetcher.serve_final_url( + "https://page.test/r", + "https://page.test/final/page.html", + b"x", + ); + fetcher.serve("https://page.test/final/style.css", b"p { color: red }"); + let hits = fetcher.hits(); + + let fetched = fetch_document(&fetcher, "https://page.test/r").expect("ok"); + assert_eq!( + fetched.base_url, "https://page.test/final/page.html", + "文档 base = 重定向落点" + ); + assert!( + hits.lock() + .unwrap() + .contains(&"https://page.test/final/style.css".to_owned()), + "相对子资源按落点解析" + ); +} + +/// 地址栏输入规范化接进导航:无 scheme 补 http:// 后可达;非法输入走 +/// 抓取路径返回收敛错误串(错误页兑底),全程不 panic。 +#[test] +fn address_bar_navigation_normalizes_and_fails_safe() { + let fetcher = MockFetcher::new(); + fetcher.serve("http://plain.test/x", b"ok"); + + // 无 scheme 输入补全 http:// 后命中 + let normalized = normalize_address_bar_input("plain.test/x"); + assert_eq!(normalized, "http://plain.test/x"); + let fetched = fetch_document(&fetcher, &normalized).expect("补全后可导航"); + assert!(fetched.data.html.contains("ok")); + + // 非法输入(含空格)补全后仍非法:mock 按未登记 → 404 → 错误串收敛, + // 不 panic(真实后端 reqwest 同路径判 InvalidUrl →「无效的地址」) + let invalid = normalize_address_bar_input("hello world"); + assert_eq!( + fetch_document(&fetcher, &invalid).err().as_deref(), + Some("HTTP 404") + ); +} + +// ---- K4 T3:@font-face 字体子资源编排(无头 MockFetcher,与 app.rs 同序) ---- + +use nexty_chrome::resources::{ + FetchedFont, FontOrchestrator, FontRegistration, MAX_FONT_BODY_BYTES, fetch_fonts, +}; +use nexty_layout::TextRun; + +/// 独特测试族名:避开系统字体碰撞(nexty-text T2 偏差——同名系统字体合并 +/// 不保证 @font-face 优先)。 +const TEST_FAMILY: &str = "NextyChromeTestMono"; + +/// 测试字体字节:nexty-text T2 入库的 OFL 字体资产,复用同一份不另入库副本。 +fn test_font_bytes() -> Vec { + std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../nexty-text/tests/data/SpaceMono-Regular.ttf" + )) + .expect("test font asset (nexty-text tests/data)") +} + +/// 树中首个非空文本 run(字体归属断言用);找不到时 panic(测试页必有文本)。 +fn first_run(fragment: &Fragment) -> &TextRun { + fn find(fragment: &Fragment) -> Option<&TextRun> { + for line in &fragment.lines { + for run in &line.runs { + if !run.glyphs.is_empty() { + return Some(run); + } + } + } + for child in &fragment.children { + if let Some(run) = find(child) { + return Some(run); + } + } + None + } + find(fragment).expect("no text run in fragment tree") +} + +/// ①③④:@font-face 页字体字节被抓取且注册(shape 归属);就绪后恰一轮 +/// 重排;同 URL 重复导航不重复抓取。编排序列与 app.rs 的 page_loaded / +/// spawn_font_fetch / fonts_ready 一致(无头模拟,整形器接线同构造点)。 +#[test] +fn font_face_page_fetches_registers_and_relayouts_exactly_once() { + let font_bytes = test_font_bytes(); + let fetcher = MockFetcher::new(); + fetcher.serve("https://page.test/mono.ttf", &font_bytes); + let html = format!( + "\ +

Hello

" + ); + let base = "https://page.test/index.html"; + + // 会话与整形器接线:与 app.rs 构造点同序(registry 先于 shaper) + let mut fonts = FontOrchestrator::new(); + let shaper = ParleyTextShaper::with_registry(fonts.registry()); + let mut layouts = 0usize; + + // 第一轮导航:抓取 → 装配 → 收集(build_page 之前,同 page_loaded) + let document = nexty_html::parse_document(&html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + let requests = fonts.collect(&resources.stylesheets, base); + assert_eq!(requests.len(), 1, "收集到 @font-face 的 url() 源"); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); + + // 首帧布局:注册表为空 → 系统回退字体(不 panic;字节不是注册字体) + let root1 = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + assert_eq!(layouts, 1); + assert!( + first_run(&root1) + .fonts + .iter() + .all(|font| font.data().as_ref() != font_bytes.as_slice()), + "字体未就绪首帧用系统字体渲染" + ); + + // SceneCache 缓存键(页面代次):基线一次 emit + let mut cache = pipeline::SceneCache::new(); + let _ = cache.scene_for(1, &page, &root1, 400.0, &[]); + assert_eq!(cache.emits(), 1); + + // 字节就绪(后台 fetch_fonts)→ 注册 → registered > 0 → 恰一轮重排 + let fetched = fetch_fonts(&fetcher, &requests); + assert_eq!(fetched.len(), 1); + let registration = fonts.register(fetched); + assert_eq!( + registration, + FontRegistration { + registered: 1, + rejected: 0 + } + ); + let root2 = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + assert_eq!(layouts, 2, "就绪后恰一轮重排(布局调用恰 +1)"); + + // shape 归属:run 字体表含注册字节(同一 shaper 实例自动生效,未重建) + assert!( + first_run(&root2) + .fonts + .iter() + .any(|font| font.data().as_ref() == font_bytes.as_slice()), + "注册字体进入 shape 归属" + ); + + // 代次推进 → 场景缓存失效重建(重排接既有缓存失效机制) + let _ = cache.scene_for(2, &page, &root2, 400.0, &[]); + assert_eq!(cache.emits(), 2, "重排推进代次使 SceneCache 重建"); + + // 重复/迟到载荷:registered == 0 → 不再重排(layouts 保持 2) + let duplicate = fonts.register(vec![FetchedFont { + url: "https://page.test/mono.ttf".to_owned(), + descriptor: requests[0].descriptor.clone(), + bytes: font_bytes.clone(), + }]); + assert_eq!(duplicate.registered, 0, "重复载荷不重复注册"); + + // 第二轮导航(同 URL):会话去重 → 不再收集、不再抓取、不再重排 + let document = nexty_html::parse_document(&html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + assert!( + fonts.collect(&resources.stylesheets, base).is_empty(), + "会话去重:二次导航不再收集" + ); + assert_eq!(layouts, 2, "二次导航零重排"); + assert_eq!( + fetcher + .hits() + .lock() + .unwrap() + .iter() + .filter(|url| **url == "https://page.test/mono.ttf") + .count(), + 1, + "mock 计数恰 1" + ); +} + +/// ②:404 / 非字体数据 / 超预算字体 → 不 panic,页面回退系统字体照常 +/// 渲染;注册失败不触发重排。 +#[test] +fn font_failures_degrade_to_system_fonts_without_panicking() { + let fetcher = MockFetcher::new(); + fetcher.fail("https://page.test/lost.ttf", 404); + fetcher.serve("https://page.test/junk.ttf", b"not a font"); + fetcher.serve( + "https://page.test/huge.ttf", + &vec![0u8; MAX_FONT_BODY_BYTES + 1], + ); + let html = "

Hello

"; + let base = "https://page.test/index.html"; + + let mut fonts = FontOrchestrator::new(); + let shaper = ParleyTextShaper::with_registry(fonts.registry()); + let mut layouts = 0usize; + + let document = nexty_html::parse_document(html, ParseOptions::default()); + let resources = resources::fetch_subresources(&fetcher, base, &document); + let requests = fonts.collect(&resources.stylesheets, base); + assert_eq!( + requests.len(), + 3, + "url() 源全部收集(格式/预算过滤发生在抓取、注册层)" + ); + let page = pipeline::build_page(document, resources.stylesheets, resources.images); + let root = { + layouts += 1; + pipeline::layout_page(&page, &shaper, 400.0).expect("root") + }; + + // 抓取:404 / 超预算缺席;junk 字节到达但注册期拒收(记报告) + let fetched = fetch_fonts(&fetcher, &requests); + assert_eq!(fetched.len(), 1, "404 与超预算缺席"); + let registration = fonts.register(fetched); + assert_eq!( + registration, + FontRegistration { + registered: 0, + rejected: 1 + }, + "非字体数据拒收记数" + ); + assert_eq!(layouts, 1, "注册失败不触发重排"); + + // 页面照常渲染:系统回退文本进显示列表(不 panic、不空白) + let scene = pipeline::build_scene(&page, &root); + assert!( + scene + .commands + .iter() + .any(|command| matches!(command, Command::DrawText { .. })), + "回退路径照常渲染文本" + ); +} diff --git a/crates/nexty-chrome/tests/selection.rs b/crates/nexty-chrome/tests/selection.rs index c4ce707..72a5201 100644 --- a/crates/nexty-chrome/tests/selection.rs +++ b/crates/nexty-chrome/tests/selection.rs @@ -116,8 +116,8 @@ fn click_and_drag_are_distinguished_for_link_navigation() { #[test] fn highlight_is_emitted_between_background_and_text() { let page = pipeline::load_page( - "

abc

", - "body { background-color: #ffffff; margin: 0 }", + "

abc

", + "body { margin: 0 }", ); let shaper = ParleyTextShaper::new(); let root = pipeline::layout_page(&page, &shaper, 400.0).expect("root"); diff --git a/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json new file mode 100644 index 0000000..b542b9a --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.json @@ -0,0 +1 @@ +{"touched":["D:\\Nexty\\crates\\nexty-css\\src\\value.rs","D:\\Nexty\\crates\\nexty-css\\src\\cascade.rs"],"bashMutation":true,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mvw2dq8j-91568-cc032940c8","createdAt":"2026-10-31T07:12:59.923Z","files":{"src/value.rs":{"existed":true,"snapshot":"be1c878c753064b7eaddf4a10ba4215a93dd1817d31e6788691cdb29752fd612.source"},"src/cascade.rs":{"existed":true,"snapshot":"01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":2,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-10-31T07:14:15.698Z"} \ No newline at end of file diff --git a/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source new file mode 100644 index 0000000..0460168 --- /dev/null +++ b/crates/nexty-css/.mimosa/hook-state/sess_593b0e04-d177-44d2-b3cc-247d233520f7.mvw2dq8j-91568-cc032940c8.baseline/01bd7f2baaf2335e56694f02b60c806c80651a6e5acc29a13d3c84bf63ac1cdd.source @@ -0,0 +1,2367 @@ +//! 自研 cascade 与 computed style。 +//! +//! 行为 ground truth: +//! - 级联排序:[CSS Cascading and Inheritance Level 5 §6](https://drafts.csswg.org/css-cascade-5/#cascading) +//! - 继承 / 初始值:[CSS Cascade 5 §7](https://drafts.csswg.org/css-cascade-5/#defaulting) +//! - 字号计算:[CSS Fonts 4 §2.5](https://drafts.csswg.org/css-fonts-4/#font-size-prop) +//! - 相对字重:[CSS Fonts 4 §2.2.1](https://drafts.csswg.org/css-fonts-4/#relative-weights) +//! +//! 本轮只有 author origin(UA 样式表未引入),故排序桶为: +//! importance → 内联样式 → 特异度 → 源顺序。`revert` 回退到 UA origin, +//! 而 UA 无声明,等价于 initial。 + +use std::collections::HashMap; + +use nexty_dom::{Document, NodeId, NodeKind}; + +use crate::parser::{Declaration, MediaViewport, StyleRule, Stylesheet, parse_inline_style}; +use crate::selector::{NextySelector, atom_str, match_element_selectors}; +use crate::value::{ + AbsoluteSize, AlignItemsValue, AlignSelfValue, BorderColorValue, BorderStyle, BorderWidthValue, + BoxSizingValue, ClearValue, CssWideKeyword, DeclaredValue, DisplayValue, FlexDirectionValue, + FloatValue, FlexWrapValue, + FontFamilyValue, FontSizeValue, FontStyleValue, FontWeightValue, GapValue, GridAutoFlowValue, + GridTrackList, InsetValue, JustifyContentValue, LineHeightValue, MAX_CSS_LENGTH, MarginValue, + OverflowValue, OverflowWrapValue, PaddingValue, PositionValue, PropertyId, PropertyValue, Rgba, + SizeValue, SpacingValue, TabSizeValue, TextAlignValue, TextIndentValue, ViewportUnit, + WhiteSpaceValue, WordBreakValue, +}; + +/// 本层 UA 的 medium 字号基准(CSS Fonts 4 §2.5:initial 值由 UA 决定, +/// 对齐浏览器默认 16px;绝对尺寸关键字按 §2.5.1 缩放系数相对它计算)。 +pub(crate) const MEDIUM_FONT_SIZE: f32 = 16.0; + +/// 一个元素的 computed style(属性集随管线逐轮扩展)。 +#[derive(Debug, Clone, PartialEq)] +pub struct ComputedStyle { + /// `display`。 + pub display: DisplayValue, + /// `color`。 + pub color: Rgba, + /// `background-color`。 + pub background_color: Rgba, + /// 计算字号(CSS px)。 + pub font_size: f32, + /// 计算字重(1–1000)。 + pub font_weight: f32, + /// `font-style`。 + pub font_style: FontStyleValue, + /// `font-family` 列表。 + pub font_family: Vec, + /// `text-align`。 + pub text_align: TextAlignValue, + /// `line-height`(数值/normal 保持原样;长度为绝对 px; + /// 百分比与 em 已按本元素 font-size 折算)。 + pub line_height: LineHeightValue, + /// `white-space`(CSS Text 3 §3.1)。 + pub white_space: WhiteSpaceValue, + /// `overflow-wrap`(CSS Text 3 §5.4)。 + pub overflow_wrap: OverflowWrapValue, + /// `word-break`(CSS Text 3 §5.1)。 + pub word_break: WordBreakValue, + /// `letter-spacing` 的附加字距(CSS px;`normal` 与 0 同义,CSS Text 3 §8.1)。 + pub letter_spacing: f32, + /// `word-spacing`(CSS Text 3 §8.2;`normal` 语义保留给 layout,em 已折算)。 + pub word_spacing: SpacingValue, + /// `text-indent`(CSS Text 3 §4;em 已折算,百分比由 layout 按包含块解析)。 + pub text_indent: TextIndentValue, + /// `tab-size`(CSS Text 3 §5;整数形态由 layout 按空格 advance 解析)。 + pub tab_size: TabSizeValue, + /// `width`(百分比由 layout 解析)。 + pub width: SizeValue, + /// `height`(百分比由 layout 解析)。 + pub height: SizeValue, + /// `min-width`(CSS 2.1 §10.4)。 + pub min_width: SizeValue, + /// `max-width`(CSS 2.1 §10.4)。 + pub max_width: SizeValue, + /// `min-height`(CSS 2.1 §10.7)。 + pub min_height: SizeValue, + /// `max-height`(CSS 2.1 §10.7)。 + pub max_height: SizeValue, + /// `box-sizing`(CSS Sizing 4 §5.3)。 + pub box_sizing: BoxSizingValue, + /// `overflow`(CSS Overflow 3 §3;仅裁剪标记,裁剪未实现)。 + pub overflow: OverflowValue, + /// `flex-grow`(CSS Flexbox §7.1,initial 0)。 + pub flex_grow: f32, + /// `flex-basis`(CSS Flexbox §7.2,initial auto)。 + pub flex_basis: SizeValue, + /// `position`(CSS Position 3 §2,initial static)。 + pub position: PositionValue, + /// `float`(CSS 2.1 §9.5.1,initial none;不继承)。 + pub float: FloatValue, + /// `clear`(CSS 2.1 §9.5.2,initial none;不继承)。 + pub clear: ClearValue, + /// 四边 inset(top / right / bottom / left;百分比与 auto 由 layout 解析)。 + pub inset: Edges, + /// `flex-direction`(CSS Flexbox §8.3.1,initial row)。 + pub flex_direction: FlexDirectionValue, + /// `flex-wrap`(CSS Flexbox §8.4.1,initial nowrap)。 + pub flex_wrap: FlexWrapValue, + /// `flex-shrink`(CSS Flexbox §7.2,initial 1)。 + pub flex_shrink: f32, + /// `align-items`(CSS Box Alignment §7,initial stretch)。 + pub align_items: AlignItemsValue, + /// `justify-content`(CSS Box Alignment §8,initial flex-start)。 + pub justify_content: JustifyContentValue, + /// `align-self`(CSS Box Alignment §7,initial auto)。 + pub align_self: AlignSelfValue, + /// `grid-template-columns`(CSS Grid §7.2,initial 空)。 + pub grid_template_columns: GridTrackList, + /// `grid-template-rows`(CSS Grid §7.3,initial 空)。 + pub grid_template_rows: GridTrackList, + /// `row-gap`(CSS Box Alignment §6,initial normal)。 + pub row_gap: GapValue, + /// `column-gap`(CSS Box Alignment §6,initial normal)。 + pub column_gap: GapValue, + /// `grid-auto-flow`(CSS Grid §7.7,initial row)。 + pub grid_auto_flow: GridAutoFlowValue, + /// 四边 margin(百分比与 auto 由 layout 解析)。 + pub margin: Edges, + /// 四边 padding(百分比由 layout 解析)。 + pub padding: Edges, + /// 四边 border 宽度(computed 值:style 为 none/hidden 时为 0)。 + pub border_width: Edges, + /// 四边 border 样式。 + pub border_style: Edges, + /// 四边 border 颜色(currentcolor 已按本元素 color 解析)。 + pub border_color: Edges, +} + +/// 四边值(top / right / bottom / left)。 +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Edges { + /// 上边。 + pub top: T, + /// 右边。 + pub right: T, + /// 下边。 + pub bottom: T, + /// 左边。 + pub left: T, +} + +impl Edges { + /// 用同一值填充四边。 + #[must_use] + pub const fn splat(value: T) -> Self { + Self { + top: value, + right: value, + bottom: value, + left: value, + } + } +} + +impl ComputedStyle { + /// 全部属性取 initial 值。 + /// + /// initial 值逐条对应各属性规范;UA 相关的(`color` 的 `CanvasText`、 + /// `font-family` 的 UA 默认、`font-size` 的 medium、`line-height` 的 + /// normal)取本层固定选择:黑色、serif、16px。 + #[must_use] + pub fn initial() -> Self { + Self { + display: DisplayValue::Inline, + color: Rgba::opaque(0, 0, 0), + background_color: Rgba::transparent(), + font_size: MEDIUM_FONT_SIZE, + font_weight: 400.0, + font_style: FontStyleValue::Normal, + font_family: vec![FontFamilyValue::Generic("serif")], + text_align: TextAlignValue::Start, + line_height: LineHeightValue::Normal, + white_space: WhiteSpaceValue::Normal, + overflow_wrap: OverflowWrapValue::Normal, + word_break: WordBreakValue::Normal, + letter_spacing: 0.0, + word_spacing: SpacingValue::Normal, + text_indent: TextIndentValue::Length(0.0), + tab_size: TabSizeValue::Integer(8), + width: SizeValue::Auto, + height: SizeValue::Auto, + min_width: SizeValue::Auto, + max_width: SizeValue::Auto, + min_height: SizeValue::Auto, + max_height: SizeValue::Auto, + box_sizing: BoxSizingValue::ContentBox, + overflow: OverflowValue::Visible, + flex_grow: 0.0, + flex_basis: SizeValue::Auto, + position: PositionValue::Static, + float: FloatValue::None, + clear: ClearValue::None, + inset: Edges::splat(InsetValue::Auto), + flex_direction: FlexDirectionValue::Row, + flex_wrap: FlexWrapValue::NoWrap, + flex_shrink: 1.0, + align_items: AlignItemsValue::Stretch, + justify_content: JustifyContentValue::FlexStart, + align_self: AlignSelfValue::Auto, + grid_template_columns: GridTrackList::default(), + grid_template_rows: GridTrackList::default(), + row_gap: GapValue::Normal, + column_gap: GapValue::Normal, + grid_auto_flow: GridAutoFlowValue::Row, + margin: Edges::splat(MarginValue::Length(0.0)), + padding: Edges::splat(PaddingValue::Length(0.0)), + border_width: Edges::splat(0.0), + border_style: Edges::splat(BorderStyle::None), + border_color: Edges::splat(Rgba::opaque(0, 0, 0)), + } + } +} + +impl PropertyId { + /// 属性是否继承(各属性规范 "Inherited" 行)。 + #[must_use] + pub fn inherited(self) -> bool { + matches!( + self, + Self::Color + | Self::FontSize + | Self::FontWeight + | Self::FontStyle + | Self::FontFamily + | Self::TextAlign + | Self::LineHeight + | Self::WhiteSpace + | Self::OverflowWrap + | Self::WordBreak + | Self::LetterSpacing + | Self::WordSpacing + | Self::TextIndent + | Self::TabSize + ) + } +} + +/// 全部属性的固定枚举顺序。 +/// +/// 顺序承载计算依赖:`FontSize` 先于 `LineHeight`(百分比按自身字号折算)、 +/// `Color` 先于 border 颜色(currentcolor)、border style 先于 width +/// (none/hidden 时宽度归零)。 +const PROPERTY_ORDER: [PropertyId; 64] = [ + PropertyId::Display, + PropertyId::Color, + PropertyId::BackgroundColor, + PropertyId::FontSize, + PropertyId::FontWeight, + PropertyId::FontStyle, + PropertyId::FontFamily, + PropertyId::TextAlign, + PropertyId::LineHeight, + PropertyId::WhiteSpace, + PropertyId::OverflowWrap, + PropertyId::WordBreak, + PropertyId::LetterSpacing, + PropertyId::WordSpacing, + PropertyId::TextIndent, + PropertyId::TabSize, + PropertyId::Width, + PropertyId::Height, + PropertyId::MinWidth, + PropertyId::MaxWidth, + PropertyId::MinHeight, + PropertyId::MaxHeight, + PropertyId::BoxSizing, + PropertyId::Overflow, + PropertyId::FlexGrow, + PropertyId::FlexBasis, + PropertyId::Position, + PropertyId::Float, + PropertyId::Clear, + PropertyId::Top, + PropertyId::Right, + PropertyId::Bottom, + PropertyId::Left, + PropertyId::FlexDirection, + PropertyId::FlexWrap, + PropertyId::FlexShrink, + PropertyId::AlignItems, + PropertyId::JustifyContent, + PropertyId::AlignSelf, + PropertyId::GridTemplateColumns, + PropertyId::GridTemplateRows, + PropertyId::RowGap, + PropertyId::ColumnGap, + PropertyId::GridAutoFlow, + PropertyId::MarginTop, + PropertyId::MarginRight, + PropertyId::MarginBottom, + PropertyId::MarginLeft, + PropertyId::PaddingTop, + PropertyId::PaddingRight, + PropertyId::PaddingBottom, + PropertyId::PaddingLeft, + PropertyId::BorderTopStyle, + PropertyId::BorderRightStyle, + PropertyId::BorderBottomStyle, + PropertyId::BorderLeftStyle, + PropertyId::BorderTopWidth, + PropertyId::BorderRightWidth, + PropertyId::BorderBottomWidth, + PropertyId::BorderLeftWidth, + PropertyId::BorderTopColor, + PropertyId::BorderRightColor, + PropertyId::BorderBottomColor, + PropertyId::BorderLeftColor, +]; + +/// 级联 origin 桶(CSS Cascade 5 §6.4,仅 UA 与 author 两个 origin; +/// user origin 尚未引入)。 +/// +/// 值越大优先级越高:UA 普通 < author 普通 < author `!important` < +/// UA `!important`。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum OriginBucket { + UaNormal = 0, + AuthorNormal = 1, + AuthorImportant = 2, + UaImportant = 3, +} + +/// 级联排序键(CSS Cascade 5 §6.4)。 +/// +/// 字典序即优先级:先 origin/importance 桶;author 声明中内联样式排在 +/// 样式表声明之后(§6.4 style attribute);然后按特异度、规则顺序、声明顺序。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct CascadeKey { + bucket: OriginBucket, + inline: bool, + specificity: u32, + rule_order: usize, + declaration_order: usize, +} + +/// 级联 origin(CSS Cascade 5 §6.4;user origin 尚未引入)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Origin { + Ua, + Author, +} + +/// origin + importance → 排序桶:UA 普通 < author 普通 < author `!important` +/// < UA `!important`。 +fn bucket_of(origin: Origin, important: bool) -> OriginBucket { + match (origin, important) { + (Origin::Ua, false) => OriginBucket::UaNormal, + (Origin::Author, false) => OriginBucket::AuthorNormal, + (Origin::Author, true) => OriginBucket::AuthorImportant, + (Origin::Ua, true) => OriginBucket::UaImportant, + } +} + +/// 选择器的必要条件(M5 分桶):匹配该选择器的元素**必然**满足的条件。 +/// +/// 只取顶层 compound 里的直接简单选择器(`Class` / `ID` / `LocalName`)—— +/// `:is()` / `:where()` / `:has()` 内部是备选分支而非必要条件,含组合器的 +/// 选择器其条件分布在多个 compound 上,一概保守回落 +/// [`Requirement::Always`]。键统一 ASCII 小写:quirks 模式的 +/// case-insensitive 与严格模式都只会「多测不会漏」(大小写不同的名字折到 +/// 同一键,仍然进入匹配)。 +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Requirement { + /// 元素必须带有该 class。 + Class(String), + /// 元素必须是该标签名。 + Tag(String), + /// 元素必须带有该 id。 + Id(String), + /// 无可提取的必要条件:每元素必测。 + Always, +} + +/// 从一条已解析选择器提取必要条件(优先 id > class > tag,其余 Always)。 +fn requirement_of(selector: &NextySelector) -> Requirement { + use selectors::parser::Component; + use std::borrow::Borrow; + let mut class: Option<&str> = None; + let mut tag: Option<&str> = None; + for component in selector.selector.iter_raw_match_order() { + match component { + // 组合器连接多个 compound:条件不再唯一,保守全测 + Component::Combinator(_) => return Requirement::Always, + Component::ID(atom) => { + return Requirement::Id(atom_str(atom).to_ascii_lowercase()); + } + Component::Class(atom) if class.is_none() => class = Some(atom_str(atom)), + Component::LocalName(local) if tag.is_none() => tag = Some(local.lower_name.borrow()), + _ => {} + } + } + if let Some(class) = class { + return Requirement::Class(class.to_ascii_lowercase()); + } + if let Some(tag) = tag { + return Requirement::Tag(tag.to_ascii_lowercase()); + } + Requirement::Always +} + +/// 桶内候选:一次选择器测试的全部输入(特异度已在解析期算好)。 +struct Candidate<'a> { + /// 规则在所属 origin 展平序列中的序号(CascadeKey::rule_order)。 + rule_order: usize, + /// 展平选择器槽位(同元素去重用:同一选择器可出现在多个桶)。 + slot: usize, + selector: &'a NextySelector, +} + +/// 一组样式表的规则桶索引(M5 ④):构建一次,全文档每元素复用。 +/// +/// 语义与全量扫描逐条一致:只有「必要条件已失败」的选择器被跳过——它们 +/// 本就不可能匹配。命中声明仍按 origin → importance → specificity → +/// 源顺序仲裁(CascadeKey 不变)。 +struct SheetIndex<'a> { + /// 展平的(序号, 规则)序列:rule_order 与声明借用的来源。 + rules: Vec<(usize, &'a StyleRule)>, + class: HashMap>>, + tag: HashMap>>, + id: HashMap>>, + /// 无可提取必要条件的选择器:每元素必测。 + always: Vec>, + /// 展平选择器总数(去重 scratch 的尺寸)。 + selector_count: usize, +} + +impl<'a> SheetIndex<'a> { + /// 为一组样式表构建索引(规则按传入顺序、选择器按源顺序展平编号)。 + fn build(sheets: &[&'a Stylesheet]) -> Self { + let mut rules = Vec::new(); + let mut class: HashMap>> = HashMap::new(); + let mut tag: HashMap>> = HashMap::new(); + let mut id: HashMap>> = HashMap::new(); + let mut always = Vec::new(); + let mut selector_count = 0usize; + for (rule_order, rule) in sheets.iter().flat_map(|sheet| sheet.rules()).enumerate() { + rules.push((rule_order, rule)); + for selector in rule.selectors() { + let slot = selector_count; + selector_count += 1; + let candidate = Candidate { + rule_order, + slot, + selector, + }; + match requirement_of(selector) { + Requirement::Class(key) => class.entry(key).or_default().push(candidate), + Requirement::Tag(key) => tag.entry(key).or_default().push(candidate), + Requirement::Id(key) => id.entry(key).or_default().push(candidate), + Requirement::Always => always.push(candidate), + } + } + } + Self { + rules, + class, + tag, + id, + always, + selector_count, + } + } + + /// 元素的必要条件集合:class 列表 + tag + id(键与桶同为小写)。 + fn requirements_of( + document: &Document, + element: NodeId, + ) -> (Vec, String, Option) { + let Some(NodeKind::Element(data)) = document.node(element) else { + return (Vec::new(), String::new(), None); + }; + let attribute = |name: &str| { + data.attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == name) + .map(|attr| attr.value.as_str()) + }; + let classes = attribute("class") + .map(|value| { + value + .split_ascii_whitespace() + .map(str::to_ascii_lowercase) + .collect() + }) + .unwrap_or_default(); + let tag = data.name.to_ascii_lowercase(); + let id = attribute("id").map(str::to_ascii_lowercase); + (classes, tag, id) + } +} + +/// 元素级收集的去重 scratch:跨元素复用(epoch 标记免清零)。 +#[derive(Default)] +struct GatherScratch { + seen: Vec, + epoch: u32, +} + +/// 收集一个元素在 UA + author 两个索引下的全部命中声明(引用,零克隆)。 +/// +/// `inline` 是本元素的内联样式解析结果([`InlineStyleCache`] 或现解析), +/// 声明同样以引用进入 matched——声明的生命周期覆盖 `resolve_all` 调用。 +fn collect_matched<'a: 'd, 'd>( + document: &Document, + element: NodeId, + ua: Option<&'a SheetIndex<'a>>, + author: &'a SheetIndex<'a>, + inline: Option<&'d [Declaration]>, + scratch: &mut GatherScratch, + matched: &mut Vec<(CascadeKey, &'d Declaration)>, +) { + // 把一个桶的去重候选并入 test(嵌套 fn 而非闭包:参数需要显式生命周期) + fn push_bucket<'a>( + bucket: &'a [Candidate<'a>], + is_ua: bool, + slot_offset: usize, + seen: &mut [u32], + epoch: u32, + test: &mut Vec<(&'a Candidate<'a>, bool)>, + ) { + for candidate in bucket { + let slot = candidate.slot + slot_offset; + if seen[slot] == epoch { + continue; + } + seen[slot] = epoch; + test.push((candidate, is_ua)); + } + } + + // 从一个索引的全部相关桶收集候选 + fn gather<'a>( + index: &'a SheetIndex<'a>, + document: &Document, + element: NodeId, + is_ua: bool, + slot_offset: usize, + scratch: &mut GatherScratch, + test: &mut Vec<(&'a Candidate<'a>, bool)>, + ) { + let (classes, tag, id) = SheetIndex::requirements_of(document, element); + for key in &classes { + if let Some(bucket) = index.class.get(key) { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + } + if let Some(bucket) = index.tag.get(&tag) { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + if let Some(id) = &id + && let Some(bucket) = index.id.get(id) + { + push_bucket( + bucket, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + push_bucket( + &index.always, + is_ua, + slot_offset, + &mut scratch.seen, + scratch.epoch, + test, + ); + } + + // 命中规则的声明组按引用入 matched(嵌套 fn:显式生命周期) + fn push_rule<'d>( + matched: &mut Vec<(CascadeKey, &'d Declaration)>, + origin: Origin, + rule_order: usize, + specificity: Option, + declarations: &'d [Declaration], + ) { + let Some(specificity) = specificity else { + return; + }; + for (declaration_order, declaration) in declarations.iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(origin, declaration.important), + inline: false, + specificity, + rule_order, + declaration_order, + }, + declaration, + )); + } + } + + // 槽位跨两个索引全局唯一:author 从 0 起,UA 偏移其后(去重 scratch) + let slot_count = author.selector_count + ua.map_or(0, |index| index.selector_count); + if scratch.seen.len() < slot_count { + scratch.seen.resize(slot_count, 0); + } + scratch.epoch = scratch.epoch.wrapping_add(1); + + // 逐桶收集候选选择器(epoch 去重:同一选择器可能同时命中多个 class 桶) + let mut test: Vec<(&Candidate<'a>, bool)> = Vec::new(); // (候选, 是否 UA) + if let Some(ua) = ua { + gather( + ua, + document, + element, + true, + author.selector_count, + scratch, + &mut test, + ); + } + gather(author, document, element, false, 0, scratch, &mut test); + + // 测试候选选择器:命中者按规则聚合最大特异度(与全量扫描一致: + // 声明的特异度取其匹配选择器中的最大值;UA 与 author 各自独立序号空间) + let mut author_specificity: Vec> = vec![None; author.rules.len()]; + let mut ua_specificity = ua.map(|index| vec![None; index.rules.len()]); + for (candidate, is_ua) in &test { + if !match_element_selectors(std::slice::from_ref(candidate.selector), document, element) { + continue; + } + let slots = if *is_ua { + ua_specificity.as_mut().expect("ua slots sized") + } else { + &mut author_specificity + }; + let entry = &mut slots[candidate.rule_order]; + *entry = Some(entry.map_or(candidate.selector.specificity, |current| { + current.max(candidate.selector.specificity) + })); + } + + // 生成 matched:author 表 + UA 表 + 内联(声明全部按引用) + for &(rule_order, rule) in &author.rules { + push_rule( + matched, + Origin::Author, + rule_order, + author_specificity[rule_order], + rule.declarations(), + ); + } + if let (Some(ua), Some(slots)) = (ua, ua_specificity.as_ref()) { + for &(rule_order, rule) in &ua.rules { + push_rule( + matched, + Origin::Ua, + rule_order, + slots[rule_order], + rule.declarations(), + ); + } + } + if let Some(inline) = inline { + for (declaration_order, declaration) in inline.iter().enumerate() { + matched.push(( + CascadeKey { + bucket: bucket_of(Origin::Author, declaration.important), + inline: true, + specificity: 0, + rule_order: usize::MAX, + declaration_order, + }, + declaration, + )); + } + } +} + +/// 内联样式解析缓存(M5 ②):元素 →(style 属性原文, 解析结果)。 +/// +/// recascade 时按**属性原文**校验——原文未变直接复用解析结果,不重解析 +/// 字符串。以原文为键保证任意来源的属性变更都自动失效(校验是廉价的 +/// 字符串比较)。存方(如 chrome 的 `Page`)跨级联调用持有本缓存。 +#[derive(Default)] +pub struct InlineStyleCache { + entries: HashMap)>, +} + +impl InlineStyleCache { + /// 空缓存。 + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// 元素内联声明的借用:原文命中直接复用,未命中现解析并入库。 + /// 无 style 属性返回 `None`。 + fn declarations_of(&mut self, document: &Document, element: NodeId) -> Option<&[Declaration]> { + let Some(NodeKind::Element(data)) = document.node(element) else { + return None; + }; + let attribute = data + .attributes + .iter() + .find(|attr| attr.namespace == nexty_dom::Namespace::None && attr.name == "style")? + .value + .clone(); + // 快路径:原文未变直接复用(属性原文是解析结果失效的唯一来源) + if let Some((cached, _)) = self.entries.get(&element) + && *cached == attribute + { + return Some(&self.entries[&element].1); + } + let declarations = parse_inline_style(&attribute); + self.entries.insert(element, (attribute, declarations)); + Some(&self.entries[&element].1) + } +} + +/// 对单个元素做级联,产出 computed style。 +/// +/// `ua_sheet` 是 UA origin 样式表(浏览器默认样式),参与级联但优先级 +/// 低于 author 声明(UA `!important` 最高,见 [`OriginBucket`])。 +/// `parent` 是树序父元素的 computed style(元素没有元素祖先时为 `None`)。 +/// 各属性:级联胜者 → CSS-wide 关键字 → 继承 → initial。 +/// 无视口信息:视口单位原样保留(见 [`cascade_in`])。 +#[must_use] +pub fn cascade( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, +) -> ComputedStyle { + cascade_in(document, element, stylesheets, ua_sheet, parent, None) +} + +/// [`cascade`] 的带视口版本:视口单位(vw/vh/vmin/vmax)在 computed 阶段 +/// 按给定视口折算为绝对 px(CSS Values 4 §6.2:1v* = 视口对应边的 1%)。 +/// 未提供视口时视口单位原样保留,由消费方按降级值处理。 +/// +/// 单元素入口每次调用重建一次规则桶索引(O(选择器总数),远小于逐元素 +/// 全量扫描);整文档入口走 [`compute_document_styles_in_with_cache`], +/// 索引只建一次。 +#[must_use] +pub fn cascade_in( + document: &Document, + element: NodeId, + stylesheets: &[&Stylesheet], + ua_sheet: Option<&Stylesheet>, + parent: Option<&ComputedStyle>, + viewport: Option, +) -> ComputedStyle { + let author = SheetIndex::build(stylesheets); + let ua = ua_sheet.map(|sheet| SheetIndex::build(std::slice::from_ref(&sheet))); + let mut scratch = GatherScratch::default(); + let mut cache = InlineStyleCache::new(); + let inline = cache.declarations_of(document, element); + let mut matched: Vec<(CascadeKey, &Declaration)> = Vec::new(); + collect_matched( + document, + element, + ua.as_ref(), + &author, + inline, + &mut scratch, + &mut matched, + ); + resolve_all(&matched, parent, viewport) +} + +/// 按树序计算整份文档的 computed style(父先于子)。 +/// +/// `