//! 运行时与窗口线程之间的发布数据契约。NamespaceState 管理提交序号、版本和当前完整文档。 //! RenderDocument/Frame 包含绘制命令、Mount 几何、页面标签和相机投影。发布前统一检查数量、坐标、颜色及索引一致性。 //! 屏幕命中、逻辑坐标和世界 UI 的射线映射必须与绘制采用同一变换;这里的 ID 是数据身份,不是窗口线程可操作的托管引用。 //! use std::collections::HashSet; use std::sync::Arc; use anyhow::{Context as _, Result, bail}; use serde::{Deserialize, Serialize}; use crate::{ display_list::{Color, DisplayList, DrawCommand}, geometry::{Point, Rect}, ui_bridge::UiNode, }; pub const DEFAULT_NAMESPACE: &str = "app.main"; #[derive(Clone, Debug)] /// HTTP/GUI 共享的最近完整发布状态;submission 决定结果归属,revision 表示实际发布次数。 pub struct NamespaceState { pub name: String, pub revision: u64, // 较新完整 PUT/DELETE 会改变提交身份;旧输入即使晚完成也不得覆盖新结果。 pub submission: u64, pub document: RenderDocument, // viewport 是主窗口逻辑页面区域;window_viewports 同时记录仍存活的副窗口。 pub viewport: Option, pub window_viewports: std::collections::BTreeMap, // 原生命令与运行时世代一起发布,防止窗口 ID 在跨 VM 时被误用。 pub runtime_session: u64, pub window_commands: Vec, } impl Default for NamespaceState { /// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。 fn default() -> Self { Self { name: DEFAULT_NAMESPACE.to_owned(), revision: 0, submission: 0, document: RenderDocument::default(), viewport: None, window_viewports: std::collections::BTreeMap::new(), runtime_session: 0, window_commands: Vec::new(), } } } impl NamespaceState { /// 在成功发布边界切换到指定 session,并按动作类别合并窗口命令;世代变化时丢弃旧命令。 pub fn publish_window_commands(&mut self, session: u64, commands: Vec) { // 跨运行时世代先丢弃旧命令,并去除旧副窗口视口记录;主壳窗口可跨 VM 替换继续存在。 if self.runtime_session != session { self.window_commands.clear(); // The primary shell survives VM replacement. Secondary native // resources belong to their originating runtime generation. self.window_viewports .retain(|id, _| *id == crate::window::MAIN_WINDOW); } self.runtime_session = session; // 零表示无有效 VM 会话,清空传输请求并忽略传入命令,不能让退役结果重新控制窗口。 if session == 0 { self.window_commands.clear(); return; } // 本方法接纳传入 session 作为当前世代,调用方负责只在成功发布边界调用;同资源同动作保留最新请求。 for command in commands { self.window_commands .retain(|old| !old.command.same_kind(&command)); self.window_commands .push(crate::window::Envelope { session, command }); } self.window_commands .sort_by_key(|command| command.command.sequence); } /// 计算下一个完整源码提交身份;计数溢出时返回错误而不是复用旧身份。 pub fn next_submission(&self) -> Result { self.submission .checked_add(1) .context("submission counter exhausted") } /// 仅当提交身份仍是最新时替换完整文档并递增版本;已被取代的结果不发布。 pub fn commit(&mut self, submission: u64, document: RenderDocument) -> Result> { // 先核对归属,再计算新版本;失败或过时的结果不会替换已显示文档。 if submission != self.submission { return Ok(None); } let revision = self .revision .checked_add(1) .context("revision counter exhausted")?; self.document = document; self.revision = revision; Ok(Some(revision)) } /// 推进提交身份和发布版本,替换为空文档并清除运行时命令,使旧提交不能覆盖清空结果。 pub fn clear(&mut self) -> Result { let submission = self.next_submission()?; let revision = self .revision .checked_add(1) .context("revision counter exhausted")?; // 先算好 submission 与 revision,任一溢出都不改状态;清空显示同时使旧异步发布失去提交资格。 self.submission = submission; self.document = RenderDocument::default(); self.runtime_session = 0; self.window_commands.clear(); self.revision = revision; Ok(revision) } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] /// 可以离开 VM 线程的完整展示值,包含源码投影、根帧和其他窗口的文档。 pub struct RenderDocument { #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub windows: std::collections::BTreeMap, #[serde(skip)] // 仅本机增量渲染使用,不序列化;JSON 文档仍可凭 frame.commands 绘制,不需要持有 VM 句柄。 pub ui_root: Option>, #[serde(default)] pub source: String, #[serde(default)] pub root: Option, #[serde(default)] pub frame: Frame, } impl RenderDocument { /// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。 pub fn validate(&self) -> Result<()> { // 校验页面兼容相机的缩放、pan 和有限 extent;独立视口变换随后按各表与 Mount 另行检查。 let surface = &self.frame.surface; if !surface.zoom.is_finite() || !(0.1..=4.0).contains(&surface.zoom) || ![surface.pan.x, surface.pan.y] .iter() .all(|v| v.is_finite() && v.abs() <= 1_000_000.0) || ![surface.extent.width, surface.extent.height] .iter() .all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v)) { bail!("invalid page camera or extent"); } if self.windows.len() > 15 { bail!("too many window projections"); } // 副窗口只允许一层投影,键须等于其 frame.window,不能重复嵌入主窗口或再带嵌套 windows。 for (id, document) in &self.windows { if *id == crate::window::MAIN_WINDOW || *id != document.frame.window || !document.windows.is_empty() { bail!("invalid secondary window projection"); } document.validate()?; } if self.source.len() > 1_048_576 { bail!("source exceeds the 1 MiB limit"); } if self.frame.commands.len() > 10_000 { bail!("frame exceeds the 10,000 command limit"); } if self.frame.window == 0 { bail!("invalid window identity"); } parse_color(&self.frame.background)?; // 空平行表是兼容的“全部无 clip/view”;一旦非空就必须与 commands 等长,禁止半张索引表。 if !self.frame.command_clips.is_empty() && self.frame.command_clips.len() != self.frame.commands.len() { bail!("invalid command clip table"); } for clip in self.frame.command_clips.iter().flatten() { validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?; } if !self.frame.command_views.is_empty() && self.frame.command_views.len() != self.frame.commands.len() { bail!("invalid command view table"); } for view in self.frame.command_views.iter().flatten() { if !view.valid() { bail!("invalid command view transform"); } } for command in &self.frame.commands { command.validate()?; } if self.frame.mounts.len() > 10_000 { bail!("frame exceeds the 10000 mount limit"); } // 标签 ID 必须非零且唯一,最多一个活动页;标题按 UTF-8 字节限长,标签数受 MAX_PAGES 限制。 let mut tab_ids = HashSet::new(); if self.frame.tabs.len() > crate::ui_bridge::MAX_PAGES || self.frame.tabs.iter().filter(|tab| tab.active).count() > 1 || self .frame .tabs .iter() .any(|tab| tab.id == 0 || !tab_ids.insert(tab.id) || tab.title.len() > 1024) { bail!("invalid tab projection"); } // 先收集全部 Mount ID 并校验几何,再第二遍核对关系下标,允许链接指向帧中较后位置。 let mut mount_ids = HashSet::new(); for mount in &self.frame.mounts { if mount.view.is_some_and(|view| !view.valid()) { bail!("invalid Mount view transform"); } if mount.id == 0 || mount.block_id.is_empty() || !mount_ids.insert(mount.id) { bail!("invalid or duplicate mount identity"); } validate_rect(mount.x, mount.y, mount.width, mount.height, 0.0)?; if let Some(clip) = mount.clip { validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?; } if let Some(clip) = mount.viewport_clip { validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?; } // 滚动投影为 [x,y,maxX,maxY],四项有限非负且实际偏移不得大于对应最大偏移。 if let Some(scroll) = mount.scroll && (!scroll.iter().all(|n| { n.is_finite() && (0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(n) }) || scroll[0] > scroll[2] || scroll[1] > scroll[3]) { bail!("invalid scroll projection"); } } // 此处只保证关系目标在帧内,不做完整树环/双向一致性验证;组成与生命周期层承担更强结构不变量。 for mount in &self.frame.mounts { for linked in [mount.parent, mount.first_child, mount.next_sibling] .into_iter() .flatten() { if !mount_ids.contains(&linked) { bail!("mount links outside this frame"); } } } // 携带本机视觉根时必须与第一个根出现的业务身份一致;反序列化无 ui_root 时跳过这项。 if let Some(root) = &self.ui_root && self .frame .mounts .first() .is_none_or(|mount| mount.block_id != root.block_id) { bail!("frame root does not match its visual projection"); } let mut ids = HashSet::new(); if let Some(root) = &self.root { root.validate(0, &mut ids)?; } Ok(()) } /// 将逻辑命令转换到设备比例并应用逐命令视图/裁剪;不自动调用 validate,发布入口须先校验。 pub fn display_list(&self, scale: f32) -> Result { let frame = &self.frame; let mut list = DisplayList::default(); list.push(DrawCommand::Clear(parse_color(&frame.background)?)); // 按命令顺序取对应 clip/view;缺项按无裁剪/单位变换处理,完整文档合法性应在发布入口预先验证。 for (index, command) in frame.commands.iter().enumerate() { let clip = frame.command_clips.get(index).copied().flatten(); // clip 已在父视图/面板对应空间,只乘设备 scale;命令本体则乘 view.zoom 再加 view 平移。 if let Some(clip) = clip { list.push(DrawCommand::PushClip(scaled_rect( clip[0], clip[1], clip[2], clip[3], scale, ))); } let view = frame .command_views .get(index) .copied() .flatten() .unwrap_or_default(); list.push( command // 均匀缩放包含字体、半径和描边,随后平移只改原点;不能把位移再乘一次 view.zoom。 .to_draw_command(scale * view.zoom)? .translated(Point::new(view.x * scale, view.y * scale)), ); if clip.is_some() { list.push(DrawCommand::PopClip); } } // 根层只绘制非面板的焦点框;面板内焦点已在 panel::compose 放入纹理,避免重复或脱离面板。 if let Some(focus) = frame .focus .and_then(|id| frame.mounts.iter().find(|m| m.id == id)) .filter(|mount| mount.panel.is_none()) { if let Some(c) = focus.clip { list.push(DrawCommand::PushClip(scaled_rect( c[0], c[1], c[2], c[3], scale, ))); } list.push( RenderCommand::StrokeRoundedRect { x: focus .view .unwrap_or_default() .rect(Rect::new(focus.x, focus.y, focus.width, focus.height)) .x, y: focus .view .unwrap_or_default() .rect(Rect::new(focus.x, focus.y, focus.width, focus.height)) .y, width: focus.width * focus.view.unwrap_or_default().zoom, height: focus.height * focus.view.unwrap_or_default().zoom, radius: 7.0, stroke_width: 2.0, color: "#4F6FDB".into(), } .to_draw_command(scale)?, ); if focus.clip.is_some() { list.push(DrawCommand::PopClip); } } // 故障提示最后追加在页面上方,只显示错误第一行;状态是否允许输入由 Frame.hit_test 等另行限制。 if let Some(error) = &frame.fault { list.push( RenderCommand::RoundedRect { x: 0.0, y: 0.0, width: 10000.0, height: 36.0, radius: 0.0, color: "#FFF1EF".into(), } .to_draw_command(scale)?, ); list.push( RenderCommand::Text { x: 12.0, y: 8.0, value: format!("运行已停止:{}", error.lines().next().unwrap_or_default()), size: 1, color: "#A32D25".into(), wrap_bounds: None, } .to_draw_command(scale)?, ); } Ok(list) } /// 从源码投影根按 ID 查找节点,供 Sources 查看与定位使用。 pub fn node(&self, id: &str) -> Option<&CodeNode> { self.root.as_ref()?.find(id) } } #[derive(Clone, Debug, Serialize, Deserialize)] /// Sources 使用的源码层次节点;ID、名称、种类和行列范围都属于代码投影而不是运行时对象句柄。 pub struct CodeNode { pub id: String, pub name: String, pub kind: String, #[serde(default)] pub start_line: usize, #[serde(default)] pub end_line: usize, #[serde(default)] pub children: Vec, } impl CodeNode { /// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。 fn validate<'a>(&'a self, depth: usize, ids: &mut HashSet<&'a str>) -> Result<()> { // 限制代码投影深度,避免递归查找/展示无界;同一 ids 集合跨所有分支检查全树 ID 唯一。 if depth > 64 { bail!("architecture tree exceeds 64 levels"); } if self.id.is_empty() { bail!("architecture node id cannot be empty"); } if !ids.insert(&self.id) { bail!("duplicate architecture node id: {}", self.id); } // 零行号表示未提供来源;只有两端均非零时检查顺序,不把兼容缺失字段当非法。 if self.start_line > 0 && self.end_line > 0 && self.start_line > self.end_line { bail!("invalid source range for node {}", self.id); } for child in &self.children { child.validate(depth + 1, ids)?; } Ok(()) } /// 按请求的代码节点身份或路径查找对应的源码投影。 fn find(&self, id: &str) -> Option<&CodeNode> { if self.id == id { return Some(self); } self.children.iter().find_map(|child| child.find(id)) } } #[derive(Clone, Debug, Serialize, Deserialize)] /// 一个窗口的一次完整视觉发布:有序命令及其裁剪/变换、出现几何、焦点和版本。平行索引表必须和命令数量一致。 pub struct Frame { // 命中索引是可重建的本地优化,不作为序列化协议的一部分保存。 #[serde(skip)] pub hit_index: Arc, #[serde(default)] pub surface: crate::page::Surface, #[serde(default = "default_window")] pub window: u64, #[serde(default = "default_background")] pub background: String, #[serde(default)] pub commands: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_clips: Vec>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_views: Vec>, #[serde(skip)] // 仅本机装配源覆盖/面板时使用的命令出现归属表,不进入 JSON;display_list 绘制本身不读取它。 pub command_mounts: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub mounts: Vec, #[serde(default)] pub layout_version: u64, #[serde(default)] // 运行时世代与 layout_version 共同确定输入归属;仅布局版本相同不能跨 VM 接受事件。 pub session: u64, #[serde(default)] pub focus: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tabs: Vec, #[serde(default)] pub fault: Option, } impl Default for Frame { /// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。 fn default() -> Self { Self { hit_index: Arc::default(), surface: crate::page::Surface::default(), window: crate::window::MAIN_WINDOW, background: default_background(), commands: Vec::new(), command_clips: Vec::new(), command_views: Vec::new(), command_mounts: Vec::new(), mounts: Vec::new(), layout_version: 0, session: 0, focus: None, tabs: Vec::new(), fault: None, } } } /// A position in a published frame. Identifiers are opaque data, never VM handles. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] /// 某次出现的几何与投影元数据。逻辑矩形不被相机直接改写,view/panel 保存通往视图空间的映射。 pub struct MountGeometry { #[serde(default, skip_serializing_if = "Option::is_none")] // 可嵌套的世界 UI 映射,把页面坐标还原到此出现所在面板纹理空间。 pub panel: Option>, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub canvas_viewport: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub scene3d_viewport: bool, #[serde(default)] pub camera_controls: bool, #[serde(default, skip_serializing_if = "Option::is_none")] // 视口内容区的额外裁剪,供相机手势锚点检查;区别于一般 Mount 的祖先 clip。 pub viewport_clip: Option<[f32; 4]>, #[serde(default, skip_serializing_if = "Option::is_none")] pub view: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub clip: Option<[f32; 4]>, #[serde(default, skip_serializing_if = "Option::is_none")] // 当前有效滚动位置和上限,不是原始请求值;非滚动容器为 None。 pub scroll: Option<[f32; 4]>, pub id: u64, pub block_id: String, pub parent: Option, pub first_child: Option, pub next_sibling: Option, pub x: f32, pub y: f32, pub width: f32, pub height: f32, pub interactive: bool, #[serde(default)] pub pointer_events: bool, } impl MountGeometry { /// 先沿世界 UI 面板逆投影指针,按需要执行可见性和裁剪检查。 pub fn view_point(&self, point: Point, clipped: bool) -> Option { self.panel .as_ref() .map_or(Some(point), |panel| panel.texture_point(point, clipped)) } /// 把页面指针转换为该出现的布局坐标,供 hitTest 和局部事件处理使用。 pub fn logical_point(&self, point: Point) -> Option { // 先处理面板反投影及遮挡,再撤销二维 view,结果仍是布局空间绝对坐标,尚未减节点原点。 let point = self.view_point(point, true)?; Some(self.view.unwrap_or_default().inverse(point)) } /// 把视图位移换算成目标出现的局部位移,处理缩放与世界 UI 投影差异。 pub fn logical_delta(&self, point: Option<[f32; 2]>, delta: [f32; 2]) -> Option<[f32; 2]> { let zoom = self.view.unwrap_or_default().zoom; // 普通二维映射为线性,只除累计 zoom 即可;世界面板透视非线性,必须映射两个点求差。 if self.panel.is_none() { return Some([delta[0] / zoom, delta[1] / zoom]); } let point = point?; let current = self.view_point(Point::new(point[0], point[1]), false)?; // 对 point 与 point+delta 分别投影,使用 clipped=false 允许捕获拖动越出面板;投影不可逆则返回 None。 let previous = self.view_point(Point::new(point[0] + delta[0], point[1] + delta[1]), false)?; Some([ ((previous.x - current.x) / zoom).clamp(-1_000_000., 1_000_000.), ((previous.y - current.y) / zoom).clamp(-1_000_000., 1_000_000.), ]) } /// 判断给定点是否位于目标范围;需要相机转换的类型会先转换再判断。 pub fn contains(&self, point: Point) -> bool { let Some(point) = self.view_point(point, true) else { return false; }; // 节点矩形在逻辑布局空间检查,clip 在视图/面板纹理空间检查,不能将二者坐标混用。 let local = self.view.map_or(point, |view| view.inverse(point)); Rect::new(self.x, self.y, self.width, self.height).contains(local) && self.clip.is_none_or(|c| { c[2] > 0.0 && c[3] > 0.0 && Rect::new(c[0], c[1], c[2], c[3]).contains(point) }) } } impl Frame { /// 从顶层绘制顺序向后查找可控制的视口,命中与裁剪均成立才接收相机手势。 pub fn camera_at(&self, point: Point) -> Option<&MountGeometry> { self.hit_index .candidates(point, self.mounts.len()) .into_iter() .map(|index| &self.mounts[index]) .find(|mount| { // 二维视口可控制,三维视口还要求显式 camera_controls;命中外框之外,还须位于内容 viewport_clip。 (mount.canvas_viewport || mount.scene3d_viewport && mount.camera_controls) && mount.contains(point) && mount.viewport_clip.is_some_and(|clip| { mount.view_point(point, true).is_some_and(|point| { Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point) }) }) }) } /// 在无故障帧中按逆绘制顺序选中可交互的出现,空间索引只缩小候选。 pub fn hit_test(&self, point: Point) -> Option<&MountGeometry> { // 故障帧不返回可交互目标,防止用户继续向已经停止的域发送页面点击。 if self.fault.is_some() { return None; } // 索引只筛几何候选,返回最前景 interactive 出现;真正源 hitTest 协议由 worker 的 source_hit 再执行。 self.hit_index .candidates(point, self.mounts.len()) .into_iter() .map(|index| &self.mounts[index]) .find(|mount| mount.interactive && mount.contains(point)) } } /// 返回默认主窗口身份,供省略窗口字段的兼容输入使用。 fn default_window() -> u64 { crate::window::MAIN_WINDOW } /// 提供空帧或未指定背景时的默认页面底色。 fn default_background() -> String { "#F7F7F5".to_owned() } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] /// 可校验、可序列化的逻辑绘制命令;转换到设备像素在 display_list 阶段完成。 pub enum RenderCommand { #[serde(skip_deserializing)] Image { x: f32, y: f32, width: f32, height: f32, offset_x: f32, offset_y: f32, angle: f32, opacity: f32, tint: Option, image: Arc, }, Scene3D { x: f32, y: f32, width: f32, height: f32, view: Arc, }, RoundedRect { x: f32, y: f32, width: f32, height: f32, #[serde(default)] radius: f32, color: String, }, StrokeRoundedRect { x: f32, y: f32, width: f32, height: f32, #[serde(default)] radius: f32, #[serde(default = "default_stroke_width")] stroke_width: f32, color: String, }, Text { x: f32, y: f32, value: String, #[serde(default = "default_text_size")] size: u32, color: String, #[serde(default, skip_serializing_if = "Option::is_none")] wrap_bounds: Option<[f32; 2]>, }, } impl RenderCommand { /// 检查当前输入或发布值的不变量,调用方据校验结果决定是否继续。 pub(crate) fn validate(&self) -> Result<()> { match self { Self::Image { x, y, width, height, offset_x, offset_y, angle, opacity, image, .. } => { validate_rect(*x, *y, *width, *height, 0.)?; if ![offset_x, offset_y, angle, opacity] .iter() .all(|v| v.is_finite()) || !(0. ..=1.).contains(opacity) || image.width == 0 || image.height == 0 { bail!("invalid image command"); } } Self::Scene3D { x, y, width, height, view, } => { validate_rect(*x, *y, *width, *height, 0.0)?; if !view.valid() { bail!("invalid 3D view"); } } Self::RoundedRect { x, y, width, height, radius, color, } => { validate_rect(*x, *y, *width, *height, *radius)?; parse_color(color)?; } Self::StrokeRoundedRect { x, y, width, height, radius, stroke_width, color, } => { validate_rect(*x, *y, *width, *height, *radius)?; // 描边必须正且有限;具体半宽限制在软件渲染器处理,这里不要求描边小于矩形尺寸。 if !stroke_width.is_finite() || *stroke_width <= 0.0 { bail!("stroke_width must be a positive finite number"); } parse_color(color)?; } Self::Text { x, y, value, size, color, wrap_bounds, } => { if !x.is_finite() || !y.is_finite() { bail!("text coordinates must be finite"); } // 有换行框时同时限制框尺寸、原点与右/下端点;无框文本在此只校验坐标有限性和文本/字号预算。 if let Some([width, height]) = wrap_bounds { validate_rect(*x, *y, *width, *height, 0.0)?; if [*x, *y, *width, *height, *x + *width, *y + *height] .iter() .any(|value| value.abs() > crate::ui_bridge::MAX_DIMENSION as f32) { bail!("text wrap bounds exceed limits"); } } if value.len() > 16_384 { bail!("text command exceeds 16 KiB"); } if !(1..=8).contains(size) { bail!("text size must be between 1 and 8"); } parse_color(color)?; } } Ok(()) } /// 把一条已验证的发布命令变成原生绘制原语,缩放几何和文字样式。 fn to_draw_command(&self, scale: f32) -> Result { Ok(match self { Self::Image { x, y, width, height, offset_x, offset_y, angle, opacity, tint, image, } => DrawCommand::Image { image: image.clone(), origin: Point::new(x * scale, y * scale), rect: scaled_rect(*offset_x, *offset_y, *width, *height, scale), angle: *angle, opacity: *opacity, tint: *tint, }, Self::Scene3D { x, y, width, height, view, } => DrawCommand::Scene3D { rect: scaled_rect(*x, *y, *width, *height, scale), view: view.clone(), }, Self::RoundedRect { x, y, width, height, radius, color, } => DrawCommand::FillRoundedRect { rect: scaled_rect(*x, *y, *width, *height, scale), radius: radius * scale, color: parse_color(color)?, }, Self::StrokeRoundedRect { x, y, width, height, radius, stroke_width, color, } => DrawCommand::StrokeRoundedRect { rect: scaled_rect(*x, *y, *width, *height, scale), radius: radius * scale, width: stroke_width * scale, color: parse_color(color)?, }, Self::Text { x, y, value, size, color, wrap_bounds, // 根据是否提供换行边界选择 WrappedText 或 Text;两者都使用同一等级字号与设备缩放。 } => match wrap_bounds { Some([width, height]) => DrawCommand::WrappedText { rect: scaled_rect(*x, *y, *width, *height, scale), value: value.clone(), style: crate::text::TextStyle::ui(*size).scaled(scale), color: parse_color(color)?, }, None => DrawCommand::Text { origin: Point::new(x * scale, y * scale), value: value.clone(), style: crate::text::TextStyle::ui(*size).scaled(scale), color: parse_color(color)?, }, }, }) } } /// 提供未指定描边宽度时的兼容默认值。 fn default_stroke_width() -> f32 { 1.0 } /// 提供未指定字号时的协议默认值。 fn default_text_size() -> u32 { 1 } /// 统一检查有限矩形坐标、尺寸与可选圆角,阻止异常值进入光栅循环。 fn validate_rect(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Result<()> { if !x.is_finite() || !y.is_finite() || !width.is_finite() || !height.is_finite() { bail!("rectangle values must be finite"); } // 此基础检查只要求有限、非负几何与圆角,不加世界坐标绝对值上限;更严格范围由具体协议调用路径决定。 if width < 0.0 || height < 0.0 || !radius.is_finite() || radius < 0.0 { bail!("rectangle dimensions and radius cannot be negative"); } Ok(()) } /// 将逻辑矩形转换为设备比例下的矩形,保持位置与尺寸同比缩放。 fn scaled_rect(x: f32, y: f32, width: f32, height: f32, scale: f32) -> Rect { Rect::new(x * scale, y * scale, width * scale, height * scale) } /// 解析支持的十六进制 RGB/RGBA 文本,拒绝错误长度或非法字符。 pub fn parse_color(value: &str) -> Result { let hex = value .strip_prefix('#') .ok_or_else(|| anyhow::anyhow!("color must begin with #"))?; // 先验证 ASCII 和精确长度,后面按字节区间切片才不会在多字节字符中间切开;不支持短色号或命名颜色。 if !hex.is_ascii() || (hex.len() != 6 && hex.len() != 8) { bail!("color must use #RRGGBB or #RRGGBBAA"); } let parse = |range| u8::from_str_radix(&hex[range], 16); Ok(Color::rgba( parse(0..2)?, parse(2..4)?, parse(4..6)?, // 顺序为 RRGGBBAA 而非 AARRGGBB,六位色号默认完全不透明。 if hex.len() == 8 { parse(6..8)? } else { 255 }, )) } #[cfg(test)] mod tests { #[test] /// 旧文字JSON缺wrap_bounds仍走不换行命令;合法边界随DPI缩放,负宽度在发布验证中拒绝。 fn text_wrap_bounds_validate_and_legacy_text_remains_unwrapped() { let mut command: RenderCommand = serde_json::from_str( r##"{"type":"text","x":0,"y":0,"value":"text","size":1,"color":"#000000"}"##, ) .unwrap(); assert!(matches!( command.to_draw_command(1.0).unwrap(), DrawCommand::Text { .. } )); if let RenderCommand::Text { wrap_bounds, .. } = &mut command { *wrap_bounds = Some([40.0, 20.0]); } command.validate().unwrap(); assert!( matches!(command.to_draw_command(1.25).unwrap(),DrawCommand::WrappedText{rect,..}if rect.width==50.0 && rect.height==25.0) ); if let RenderCommand::Text { wrap_bounds, .. } = &mut command { *wrap_bounds = Some([-1.0, 20.0]); } assert!(command.validate().is_err()); } use super::*; #[test] /// 默认空文档可通过验证且没有结构根/绘图命令,支持初始状态与清空发布。 fn empty_document_is_valid_and_blank() { let document = RenderDocument::default(); document.validate().unwrap(); assert!(document.root.is_none()); assert!(document.frame.commands.is_empty()); } #[test] /// 检查六位色默认alpha255,八位色按RRGGBBAA解码,避免将末尾透明度当成首通道。 fn parses_rgb_and_rgba_colors() { assert_eq!( parse_color("#102030").unwrap(), Color::rgba(16, 32, 48, 255) ); assert_eq!( parse_color("#10203080").unwrap(), Color::rgba(16, 32, 48, 128) ); } } #[cfg(test)] mod window_projection_tests { use super::*; #[test] /// 同会话窗口命令可累积,新会话发布先丢旧命令;clear重置runtime_session并清空所有原生命令。 fn replacement_and_reset_discard_old_window_projections() { let mut state = NamespaceState::default(); let command = crate::window::Command { window: 1, sequence: 1, action: crate::window::Action::Focus, }; state.publish_window_commands(1, vec![command.clone()]); let resize = crate::window::Command { window: 1, sequence: 2, action: crate::window::Action::Resize { width: 900.0, height: 600.0, }, }; state.publish_window_commands(1, vec![resize.clone()]); assert_eq!(state.window_commands.len(), 2); state.publish_window_commands(2, vec![resize]); assert_eq!(state.window_commands.len(), 1); assert_eq!(state.window_commands[0].session, 2); state.clear().unwrap(); assert_eq!(state.runtime_session, 0); assert!(state.window_commands.is_empty()); } }