docs: explain graphics resources and runtime dispatch lifecycles
This commit is contained in:
+184
-2
@@ -1,5 +1,8 @@
|
||||
//! General retained graphics resources for source paint: images, fonts, prepared
|
||||
//! text, geometric exclusions and numerical functions. No application behaviour.
|
||||
//! 通用保留式图形资源桥接:图片、字体、预排文字、绕排避让形状和数值工具。
|
||||
//! ui_bridge::bootstrap 调用 install,把原生 callable 挂到 ui.graphics 与 ui.graphics.math。
|
||||
//! Endor 源程序调用这些函数创建模型资源/绘图命令;source_paint 解码图片命令时调用 decode_image。
|
||||
//! PointerDispatch 由 UiBridge::dispatch 包装成临时 callable,用同一 VM 分发原始指针事件。
|
||||
//! 这里不定义应用剧情或按钮业务。像素资源经 Arc 共享,托管资源身份与引用边仍由 Aster 管理。
|
||||
use crate::{
|
||||
document::{RenderCommand, parse_color},
|
||||
geometry::{Point, Rect},
|
||||
@@ -14,26 +17,34 @@ use endor_core::{
|
||||
ObjectStore, Value, Vm, VmError,
|
||||
};
|
||||
use std::{any::Any, sync::Arc};
|
||||
/// 本文件的解码和分派分支统一构造 VM 参数错误,让调用栈继续提供源代码诊断位置。
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
/// 图片/字体/避让对象参数的解码入口,只复制对象句柄;payload 种类由各调用点进一步检查。
|
||||
fn object(v: &Value) -> Result<ObjectRef, VmError> {
|
||||
// 不从 nil、字符串或数字猜测资源 ID,避免把源值误指到 VM 堆中任意对象。
|
||||
if let Value::Object(o) = v {
|
||||
Ok(*o)
|
||||
} else {
|
||||
Err(invalid("expected Object"))
|
||||
}
|
||||
}
|
||||
/// 图形几何参数调用,先用 Endor 数字转换再限制绝对值,最后降为渲染器使用的 f32。
|
||||
fn number(v: &Value) -> Result<f32, VmError> {
|
||||
// 原生签名没有逐参数类型声明,因此 invoke 内仍必须检查值的实际表示。
|
||||
let Value::Number(v) = v else {
|
||||
return Err(invalid("expected Number"));
|
||||
};
|
||||
// to_f64 传播无法有限转换等错误;通用坐标允许负数,宽高/半径的非负约束由具体操作检查。
|
||||
let n = v.to_f64()?;
|
||||
if n.abs() > 1_000_000. {
|
||||
// 在转换 f32 和进入排版/光栅化前限制坐标预算,拒绝极端图形数值。
|
||||
return Err(invalid("graphics number exceeds bounds"));
|
||||
}
|
||||
Ok(n as f32)
|
||||
}
|
||||
/// 文件路径、字体名和源文本参数调用,借用真实字符串而不对任意对象隐式执行 repr。
|
||||
fn text(v: &Value) -> Result<&str, VmError> {
|
||||
if let Value::Text(s) = v {
|
||||
Ok(s)
|
||||
@@ -41,37 +52,52 @@ fn text(v: &Value) -> Result<&str, VmError> {
|
||||
Err(invalid("expected String"))
|
||||
}
|
||||
}
|
||||
/// command/flow/指针事件把原生几何返回语言时调用,统一把 f32 提升为 Endor Number。
|
||||
fn n(v: f32) -> Value {
|
||||
Value::Number((v as f64).into())
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// LoadImage/flow 产生的托管资源 payload;Arc 像素可供发布命令持有,不要求 GUI 线程读取 VM。
|
||||
pub(crate) struct ImageResource(pub Arc<Image>);
|
||||
#[derive(Debug)]
|
||||
/// LoadFont 创建、Prepare 读取的字体族句柄,字体注册/塑形细节由 render::text 负责。
|
||||
struct FontResource(TextFamily);
|
||||
#[derive(Debug)]
|
||||
/// Prepare 生成、Flow 消费的字词/字母预排结果,昂贵的塑形可在多次绕排中复用。
|
||||
struct TextResource {
|
||||
// 图形流转中仅复制 Arc,不为每一行重复塑形和生成字形图片。
|
||||
prepared: Arc<Prepared>,
|
||||
// 每次 Flow 的行带高度,ranges 用它判断避让形状与这一行的相交范围。
|
||||
line: f32,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// Circle/Rectangle/ImageExclusion 产生,Flow/ranges 读取的纯原生避让形状,不保存 VM 子对象引用。
|
||||
struct Exclusion {
|
||||
// 圆用圆心/半径描述;多边形资源保持 None,避免两种形状同时隐式叠加。
|
||||
circle: Option<(Point, f32)>,
|
||||
// 图片轮廓或矩形顶点,已经变换到绕排使用的世界/页面逻辑坐标。
|
||||
polygon: Vec<Point>,
|
||||
// 在多边形行带与横向阻塞范围外再扩展的避让距离。
|
||||
padding: f32,
|
||||
}
|
||||
// 四类资源复用 ObjectPayload 适配;没有托管引用字段,因此不需要额外 trace 子对象。
|
||||
macro_rules! resource {
|
||||
($t:ty,$name:literal) => {
|
||||
impl ObjectPayload for $t {
|
||||
// VM 的 payload::<T> 通过 Any 向下转型,防止把普通 Object 当图形资源读取。
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
// 稳定种类名供类型错误/诊断显示,不代替 Endor 名义 Type。
|
||||
$name
|
||||
}
|
||||
fn allows_attributes(&self) -> bool {
|
||||
// 资源宽高等元信息作为普通托管属性暴露,仍经 store 的属性访问规则管理。
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
// 赋值共享同一资源对象,不能按值复制资源 payload 后失去既有身份。
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -81,21 +107,27 @@ resource!(ImageResource, "image-resource");
|
||||
resource!(FontResource, "font-resource");
|
||||
resource!(TextResource, "prepared-text");
|
||||
resource!(Exclusion, "layout-exclusion");
|
||||
/// Function/flow 分配原生资源后调用,附当前宿主域的 Object 名义类型,不创建新的资源专属类。
|
||||
fn attach(cx: &mut NativeContext<'_>, o: ObjectRef, desktop: ObjectRef) -> Result<(), VmError> {
|
||||
crate::ui_bridge::attach_desktop_type(cx, o, "Object", desktop)
|
||||
}
|
||||
/// LoadImage/LoadFont/ReadText 的同步文件读取助手;调用者先拒绝布局/绘制只读阶段的 I/O。
|
||||
fn file(path: &str, limit: u64) -> Result<Vec<u8>, VmError> {
|
||||
use std::io::Read;
|
||||
if path.len() > 8192 {
|
||||
// 路径本身也有限长,不能只限制最终文件大小而接受无限字符串操作。
|
||||
return Err(invalid("resource path too long"));
|
||||
}
|
||||
// 文件句柄限定在本调用作用域,任何 ? 返回都会由 Rust 关闭,不放进托管图形资源。
|
||||
let f = std::fs::File::open(path).map_err(|_| invalid("resource file cannot be opened"))?;
|
||||
// 只接收有界普通文件,拒绝目录/特殊设备等无法靠 metadata 给出可靠预算的输入。
|
||||
let meta = f
|
||||
.metadata()
|
||||
.map_err(|_| invalid("resource metadata unavailable"))?;
|
||||
if !meta.is_file() || meta.len() > limit {
|
||||
return Err(invalid("resource must be a bounded regular file"));
|
||||
}
|
||||
// metadata 检查后文件仍可能增长,所以实际读取最多 limit+1 字节并再次检查。
|
||||
let mut data = Vec::new();
|
||||
f.take(limit + 1)
|
||||
.read_to_end(&mut data)
|
||||
@@ -105,20 +137,26 @@ fn file(path: &str, limit: u64) -> Result<Vec<u8>, VmError> {
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
/// decode_image 读取 PaintCommand 的数值属性时调用,缺字段/错误类型直接传播,不自行补缺省。
|
||||
fn field(s: &ObjectStore, o: ObjectRef, key: &str) -> Result<f32, VmError> {
|
||||
number(&s.get_attr(o, key)?)
|
||||
}
|
||||
/// source_paint 的 image 命令分支及 Sprite/ImageExclusion 调用,验证托管命令并提取纯数据图片绘制命令。
|
||||
pub(crate) fn decode_image(s: &ObjectStore, c: ObjectRef) -> Result<RenderCommand, VmError> {
|
||||
// 命令引用真实 ImageResource,不能只靠同名 width/height 属性冒充有效图片。
|
||||
let resource = object(&s.get_attr(c, "image")?)?;
|
||||
// 克隆像素 Arc,使发布结果拥有资源,不再依赖命令/资源 ObjectRef 的 VM 生命周期。
|
||||
let image = s
|
||||
.payload::<ImageResource>(resource, "ImageResource")?
|
||||
.0
|
||||
.clone();
|
||||
// tint 可缺失/nil;显式错误颜色和其他属性读取失败仍报错,不静默退回无着色。
|
||||
let tint = match s.get_attr(c, "tint") {
|
||||
Ok(Value::Text(v)) => Some(parse_color(&v).map_err(|_| invalid("invalid image tint"))?),
|
||||
Ok(Value::Nil) | Err(VmError::AttributeNotFound(_)) => None,
|
||||
_ => return Err(invalid("invalid image tint")),
|
||||
};
|
||||
// 同名局部 c 从对象身份变为原生命令;所有几何字段均经受控 number 解码。
|
||||
let c = RenderCommand::Image {
|
||||
x: field(s, c, "x")?,
|
||||
y: field(s, c, "y")?,
|
||||
@@ -131,10 +169,12 @@ pub(crate) fn decode_image(s: &ObjectStore, c: ObjectRef) -> Result<RenderComman
|
||||
tint,
|
||||
image,
|
||||
};
|
||||
// 命令级约束继续检查宽高/透明度等组合语义,单个有限坐标检查不足以证明命令合法。
|
||||
c.validate()
|
||||
.map_err(|_| invalid("invalid image geometry"))?;
|
||||
Ok(c)
|
||||
}
|
||||
/// Sprite 和 Flow 生成 image 类 PaintCommand 的共同助手,保留图片托管强边及几何字段。
|
||||
fn command(
|
||||
cx: &mut NativeContext<'_>,
|
||||
desktop: ObjectRef,
|
||||
@@ -144,6 +184,7 @@ fn command(
|
||||
angle: f32,
|
||||
opacity: f32,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// origin 是旋转定位点,rect.x/y 是相对该原点的局部图像偏移,不与绝对 x/y 混用。
|
||||
let c = crate::native_visual::record(
|
||||
cx,
|
||||
desktop,
|
||||
@@ -164,6 +205,7 @@ fn command(
|
||||
Ok(c)
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
/// install 的名称表选择实际操作;arity/invoke 同用此枚举,不依赖函数显示名称猜业务分支。
|
||||
enum Op {
|
||||
LoadImage,
|
||||
LoadFont,
|
||||
@@ -189,34 +231,47 @@ enum Op {
|
||||
Clamp,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// install 分配到 VM 的 callable payload,供源代码经 ui.graphics/math 调用。
|
||||
struct Function {
|
||||
// 具体操作决定数量与实现,图形和数值名字可以挂在不同命名空间中共享分派器。
|
||||
op: Op,
|
||||
// 资源/命令的名义类型来自该注册域;captures 同时持有对应托管强边。
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Function {
|
||||
/// VM 在进入 invoke 前查询精确参数数目,下面按位置索引 args 依赖此调用边界检查。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
use Op::*;
|
||||
Some(endor_core::CallArity::exact(match self.op {
|
||||
// 时钟无参数;资源路径和一元数学操作各一参,类型/范围在具体分支校验。
|
||||
Now => 0,
|
||||
LoadImage | ReadText | Float | Sin | Cos | Sqrt | Abs | Stringify | Floor => 1,
|
||||
// 二参分别是路径+字体族、两个操作数,或图片命令+避让边距。
|
||||
LoadFont | Atan2 | Min | Max | ImageExclusion => 2,
|
||||
// 圆/矩形几何、数值上下界和文本切片都有固定数量,不接任意变参。
|
||||
Circle | Clamp | Slice => 3,
|
||||
Rectangle => 4,
|
||||
// Prepare 接文本/字体/字号/行高/颜色/比例;Flow/Sprite 再按各自几何接口解释位置参数。
|
||||
Prepare => 6,
|
||||
Flow => 7,
|
||||
Sprite => 9,
|
||||
}))
|
||||
}
|
||||
/// VM 执行注册 callable 时调用;同步资源加载拒绝只读阶段,纯资源派生/数学可供源 paint 使用。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
use Op::*;
|
||||
// 复制所属类型域身份,后面分配资源和协议值都复用这一个注册表。
|
||||
let desktop = self.desktop;
|
||||
// 各分支产出语言值,除提前返回数学分支外统一包成 NativeResult::Return。
|
||||
let result = match self.op {
|
||||
Now => {
|
||||
if cx.store().is_read_only() {
|
||||
// 时钟变化不能成为只读绘制中的隐式输入,源程序应在事件/任务里采样并存进模型。
|
||||
return Err(invalid(
|
||||
"sample the clock in an event/task and store it in the model",
|
||||
));
|
||||
}
|
||||
// 进程级首次调用确定单调起点,返回的是相对秒数,不是 UTC 时间戳或每 VM 独立时钟。
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
Value::Number(
|
||||
START
|
||||
@@ -228,11 +283,15 @@ impl NativeCallable for Function {
|
||||
}
|
||||
LoadImage => {
|
||||
if cx.store().is_read_only() {
|
||||
// 源布局/绘制可复用已加载图片,但不允许在只读阶段重新执行文件 I/O。
|
||||
return Err(invalid("load resources outside paint/layout"));
|
||||
}
|
||||
// 先限制输入文件 4 MiB,再由 PNG 解码器校验格式和解码图像预算。
|
||||
let image = Image::png(&file(text(&args[0])?, 4_194_304)?)
|
||||
.map_err(|_| invalid("invalid or oversized PNG"))?;
|
||||
// 宽高取自解码结果,而非源程序可任意伪造的资源属性。
|
||||
let (w, h) = (image.width, image.height);
|
||||
// 托管外壳提供稳定身份,像素仍由 Arc 共享给后续绘图命令。
|
||||
let resource = cx.allocate(ImageResource(image))?;
|
||||
attach(cx, resource, desktop)?;
|
||||
cx.set_attr(resource, "width", n(w as f32))?;
|
||||
@@ -243,17 +302,21 @@ impl NativeCallable for Function {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid("load resources outside paint/layout"));
|
||||
}
|
||||
// 显式字体族名用于注册与后续塑形查找,不把文件名直接当字体族名。
|
||||
let family = text(&args[1])?;
|
||||
if family.len() > 128 {
|
||||
return Err(invalid("font family name too long"));
|
||||
}
|
||||
// 文件读取预算与字体注册表预算分别检查;错误不返回一个看似有效但会回退的字体资源。
|
||||
let font = crate::text::register_font(file(text(&args[0])?, 4_194_304)?, family)
|
||||
.map_err(|_| invalid("invalid font family or registry budget"))?;
|
||||
// FontResource 只保存验证后的族句柄,源代码不能直接改写全局字体数据库。
|
||||
let resource = cx.allocate(FontResource(font))?;
|
||||
attach(cx, resource, desktop)?;
|
||||
Value::Object(resource)
|
||||
}
|
||||
ReadText => {
|
||||
// 同步读取小型资源文本供模型初始化使用;后台异步读取仍走 runtime/io_tasks 的接口。
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid("load resources outside paint/layout"));
|
||||
}
|
||||
@@ -263,22 +326,28 @@ impl NativeCallable for Function {
|
||||
)
|
||||
}
|
||||
Slice => {
|
||||
// 源文本切片按 Unicode 标量索引而非 UTF-8 字节下标;先保留原文借用再转换边界。
|
||||
let value = text(&args[0])?;
|
||||
// number 的通用预算之外,这两个索引还必须为非负、递增的整数值。
|
||||
let start = number(&args[1])?;
|
||||
// 结束位置为半开区间上界,不包含该索引上的字符。
|
||||
let end = number(&args[2])?;
|
||||
if start < 0. || end < start || start.fract() != 0. || end.fract() != 0. {
|
||||
return Err(invalid("invalid text slice"));
|
||||
}
|
||||
// char_indices 把字符序号换回合法字节边界;超出文本时夹到末尾,不切开多字节字符。
|
||||
let lo = value
|
||||
.char_indices()
|
||||
.nth(start as usize)
|
||||
.map_or(value.len(), |(i, _)| i);
|
||||
// 与 lo 同一转换规则保证切片边界总在原字符串范围内。
|
||||
let hi = value
|
||||
.char_indices()
|
||||
.nth(end as usize)
|
||||
.map_or(value.len(), |(i, _)| i);
|
||||
Value::Text(value[lo..hi].into())
|
||||
}
|
||||
// 仅格式化标量,不对任意对象调用 repr,避免资源/图形计算触发未知对象逻辑。
|
||||
Stringify => Value::Text(match &args[0] {
|
||||
Value::Text(s) => s.clone(),
|
||||
Value::Number(v) => v.to_string(),
|
||||
@@ -287,16 +356,21 @@ impl NativeCallable for Function {
|
||||
_ => return Err(invalid("string expects scalar value")),
|
||||
}),
|
||||
Prepare => {
|
||||
// 读取源文本并按 UTF-8 字节预算限制一次塑形的内容量。
|
||||
let value = text(&args[0])?;
|
||||
if value.len() > 16_384 {
|
||||
return Err(invalid("prepared text exceeds 16 KiB"));
|
||||
}
|
||||
// 必须是 loadFont 返回的原生 FontResource,普通对象的同名字体属性不能冒充资源。
|
||||
let family = cx
|
||||
.store()
|
||||
.payload::<FontResource>(object(&args[1])?, "FontResource")?
|
||||
.0;
|
||||
// size 是逻辑字体尺寸,line 是逻辑行带高度,scale 只控制字形预绘制清晰度/资源量。
|
||||
let size = number(&args[2])?;
|
||||
// 行高不得小于字号,避免绕排占位与字形高度约定完全失配。
|
||||
let line = number(&args[3])?;
|
||||
// 设备比例有独立预算,不能通过极大 scale 把短文本变成巨量像素资源。
|
||||
let scale = number(&args[5])?;
|
||||
if !(8. ..=96.).contains(&size)
|
||||
|| !(size..=192.).contains(&line)
|
||||
@@ -304,8 +378,10 @@ impl NativeCallable for Function {
|
||||
{
|
||||
return Err(invalid("invalid text metrics"));
|
||||
}
|
||||
// 颜色预先烘入字形图片,后续 flow 不为每个词重复解析/绘制文字。
|
||||
let color =
|
||||
parse_color(text(&args[4])?).map_err(|_| invalid("invalid text color"))?;
|
||||
// 交给 text_flow 完成词/字母拆分、塑形及像素墨迹提取,这里只描述样式与预算。
|
||||
let prepared = Prepared::new(
|
||||
value,
|
||||
TextStyle {
|
||||
@@ -316,7 +392,9 @@ impl NativeCallable for Function {
|
||||
scale,
|
||||
color,
|
||||
);
|
||||
// text_flow 的静态错误文本转成 VM 参数错误,源调用得到当前调用栈上下文。
|
||||
let prepared = prepared.map_err(invalid)?;
|
||||
// Arc 让多次 flow 复用同一预排结果,line 单独保存供每行障碍相交测试使用。
|
||||
let resource = cx.allocate(TextResource {
|
||||
prepared: Arc::new(prepared),
|
||||
line,
|
||||
@@ -325,17 +403,27 @@ impl NativeCallable for Function {
|
||||
Value::Object(resource)
|
||||
}
|
||||
Sprite => {
|
||||
// Sprite 返回一条变换图片命令,不立即画到屏幕;原图对象必须带真实 ImageResource payload。
|
||||
let image = object(&args[0])?;
|
||||
cx.store()
|
||||
.payload::<ImageResource>(image, "ImageResource")?;
|
||||
// x/y 是旋转定位原点,图像左上角还受 anchor 比例和尺寸影响。
|
||||
let x = number(&args[1])?;
|
||||
// 垂直定位与水平定位使用相同逻辑坐标空间。
|
||||
let y = number(&args[2])?;
|
||||
// 目标宽高允许缩放原图,但命令 validate 会拒绝非法几何范围。
|
||||
let w = number(&args[3])?;
|
||||
// 图片采样继续使用原像素尺寸,不把 h 当作纹理行数。
|
||||
let h = number(&args[4])?;
|
||||
// a 按渲染器约定为弧度,绕 origin 旋转局部矩形。
|
||||
let a = number(&args[5])?;
|
||||
// ax/ay 把图像内部相对锚点换成局部偏移,0 是边缘,0.5 是中心。
|
||||
let ax = number(&args[6])?;
|
||||
// 不在这里默认 clamp 锚点,源代码可以选择矩形之外的旋转中心。
|
||||
let ay = number(&args[7])?;
|
||||
// 透明度除通用有限值外还受 RenderCommand::validate 的 0..1 语义限制。
|
||||
let opacity = number(&args[8])?;
|
||||
// 本地矩形以负锚点偏移定位,确保绘制与 imageExclusion 共用同一几何变换。
|
||||
let c = command(
|
||||
cx,
|
||||
desktop,
|
||||
@@ -345,10 +433,12 @@ impl NativeCallable for Function {
|
||||
a,
|
||||
opacity,
|
||||
)?;
|
||||
// 立即复用实际 paint 解码器验证命令,不等到下一帧才暴露非法 sprite 几何。
|
||||
decode_image(cx.store(), c)?;
|
||||
Value::Object(c)
|
||||
}
|
||||
ImageExclusion => {
|
||||
// 从已验证图片命令拿同一套尺寸/偏移/角度,不用近似外接矩形替代透明轮廓。
|
||||
let RenderCommand::Image {
|
||||
x,
|
||||
y,
|
||||
@@ -361,22 +451,29 @@ impl NativeCallable for Function {
|
||||
..
|
||||
} = decode_image(cx.store(), object(&args[0])?)?
|
||||
else {
|
||||
// decode_image 的唯一成功变体是 Image,其他变体到此说明内部接口约定被破坏。
|
||||
unreachable!()
|
||||
};
|
||||
// 避让边距只扩展文字禁用区域,不改图片自身的绘制尺寸。
|
||||
let padding = number(&args[1])?;
|
||||
if !(0. ..=1000.).contains(&padding) {
|
||||
return Err(invalid("invalid exclusion padding"));
|
||||
}
|
||||
// 对全部轮廓顶点共用同一旋转三角值,保持与 sprite 绘制的角度一致。
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
// 原图像素轮廓按目标宽高缩放,再加 anchor 偏移、旋转、平移到绕排坐标。
|
||||
let polygon = image
|
||||
.outline
|
||||
.iter()
|
||||
.map(|p| {
|
||||
// 归一化原图 x 到目标图像宽度,并还原相对旋转中心的局部偏移。
|
||||
let px = offset_x + p.x / image.width as f32 * width;
|
||||
// y 方向使用原图高度归一化,非正方形缩放不能复用宽度比例。
|
||||
let py = offset_y + p.y / image.height as f32 * height;
|
||||
Point::new(x + cos * px - sin * py, y + sin * px + cos * py)
|
||||
})
|
||||
.collect();
|
||||
// 轮廓已经是普通 Point 数组,避让资源不再需要引用原图片对象。
|
||||
let e = cx.allocate(Exclusion {
|
||||
circle: None,
|
||||
polygon,
|
||||
@@ -386,12 +483,16 @@ impl NativeCallable for Function {
|
||||
Value::Object(e)
|
||||
}
|
||||
Circle | Rectangle => {
|
||||
// 圆的前两参是圆心,矩形的前两参是左上角;第三参分别为半径或宽度。
|
||||
let x = number(&args[0])?;
|
||||
// 坐标可负,几何 extent 的非负约束单独检查。
|
||||
let y = number(&args[1])?;
|
||||
// 共用 extent 检查,但不把圆半径误当直径或矩形面积。
|
||||
let size = number(&args[2])?;
|
||||
if size < 0. {
|
||||
return Err(invalid("negative exclusion extent"));
|
||||
}
|
||||
// 圆保留解析几何,矩形用闭合四点多边形,ranges 分别采用相应相交算法。
|
||||
let e = if matches!(self.op, Circle) {
|
||||
Exclusion {
|
||||
circle: Some((Point::new(x, y), size)),
|
||||
@@ -399,6 +500,7 @@ impl NativeCallable for Function {
|
||||
padding: 0.,
|
||||
}
|
||||
} else {
|
||||
// 矩形独有第四参数为高度,零面积形状允许存在但不制造负方向面积。
|
||||
let h = number(&args[3])?;
|
||||
if h < 0. {
|
||||
return Err(invalid("negative exclusion height"));
|
||||
@@ -414,28 +516,36 @@ impl NativeCallable for Function {
|
||||
padding: 0.,
|
||||
}
|
||||
};
|
||||
// 把纯几何避让值包装成有稳定身份的 VM 对象,供 ObjectList 在 flow 时引用。
|
||||
let e = cx.allocate(e)?;
|
||||
attach(cx, e, desktop)?;
|
||||
Value::Object(e)
|
||||
}
|
||||
// 绕排工作集中在助手中,复用已预排字形与已验证避让资源,返回 DisplayList。
|
||||
Flow => flow(cx, desktop, args)?,
|
||||
_ => {
|
||||
// 数学分支用 f64,和受 1e6 坐标预算的 number 解码区分,允许数学中间量范围更大。
|
||||
let real = |v: &Value| -> Result<f64, VmError> {
|
||||
if let Value::Number(n) = v {
|
||||
// Endor 的整数/十进制/二进制数统一按显式浮点近似参与这些数学函数。
|
||||
n.to_f64()
|
||||
} else {
|
||||
// 不进行文本到数字或布尔到整数的隐式强制转换。
|
||||
Err(invalid("math expects Number"))
|
||||
}
|
||||
};
|
||||
// 所有剩余操作至少有一个数字参数,数量已经由 arity 在 VM 调用边界验证。
|
||||
let x = real(&args[0])?;
|
||||
if matches!(self.op, Floor) {
|
||||
if x.abs() > 1_000_000_000. {
|
||||
// floor 返回整数,先限定转换预算,不能依靠 Rust 饱和转换掩盖超大数值。
|
||||
return Err(invalid("floor result exceeds integer conversion budget"));
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Number(
|
||||
(x.floor() as i64).into(),
|
||||
)));
|
||||
}
|
||||
// 按操作计算一个结果,二/三元分支继续解析额外数字,不预读不需要的参数。
|
||||
let v = match self.op {
|
||||
Float => x,
|
||||
Sin => x.sin(),
|
||||
@@ -446,16 +556,20 @@ impl NativeCallable for Function {
|
||||
Min => x.min(real(&args[1])?),
|
||||
Max => x.max(real(&args[1])?),
|
||||
Clamp => {
|
||||
// 下界/上界顺序必须合法,否则 f64::clamp 会 panic,不能让源参数引发宿主崩溃。
|
||||
let lo = real(&args[1])?;
|
||||
// 上界是第三参数,不能交换两端后悄悄修正调用者的错误范围。
|
||||
let hi = real(&args[2])?;
|
||||
if lo > hi {
|
||||
return Err(invalid("clamp minimum exceeds maximum"));
|
||||
}
|
||||
x.clamp(lo, hi)
|
||||
}
|
||||
// 非数学操作已经在外层 match 命中,Floor 也已提前返回,因此不存在其他合法分支。
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if !v.is_finite() {
|
||||
// sqrt 负数等情况会生成 NaN,必须转成语言错误而非让非有限数流入下一轮图形几何。
|
||||
return Err(invalid("non-finite math result"));
|
||||
}
|
||||
Value::Number(v.into())
|
||||
@@ -465,97 +579,141 @@ impl NativeCallable for Function {
|
||||
}
|
||||
}
|
||||
|
||||
/// flow 为每个行带调用:合并避让形状的水平阻塞范围,返回按 x 递增且至少 8 单位宽的可排文字区间。
|
||||
/// 这是按整行带求保守横向范围,不是每个字形轮廓与多边形的精确碰撞检测。
|
||||
fn ranges(left: f32, right: f32, y: f32, line: f32, exclusions: &[&Exclusion]) -> Vec<(f32, f32)> {
|
||||
// 每个形状先贡献一个阻塞区间;最后统一排序/扫线,支持多个重叠障碍。
|
||||
let mut blocked = Vec::new();
|
||||
for e in exclusions {
|
||||
if let Some((p, r)) = e.circle {
|
||||
// 行带包含圆心时 gap=0,否则为圆心到最近水平边的垂直距离。
|
||||
let gap = (y - p.y).max(p.y - y - line).max(0.);
|
||||
if gap < r {
|
||||
// 勾股关系求该行带可触及的最大半弦长,整段横向范围都留给圆形障碍。
|
||||
let dx = (r * r - gap * gap).sqrt();
|
||||
blocked.push((p.x - dx, p.x + dx));
|
||||
}
|
||||
}
|
||||
// 多边形先把行带上下扩 padding,随后还会把水平投影左右扩 padding。
|
||||
let (top, bottom) = (y - e.padding, y + line + e.padding);
|
||||
// 收集行带内的顶点以及边与上下边界交点,取最小/最大 x 形成保守阻塞范围。
|
||||
let mut xs = Vec::new();
|
||||
for i in 0..e.polygon.len() {
|
||||
// 当前顶点和下一顶点构成一条边;取模闭合最后一条边,不要求调用者重复首顶点。
|
||||
let a = e.polygon[i];
|
||||
// 空多边形不会进入循环,因此这里的取模不会对零求余。
|
||||
let b = e.polygon[(i + 1) % e.polygon.len()];
|
||||
if a.y >= top && a.y <= bottom {
|
||||
// 行带覆盖的顶点直接参与水平包围,避免水平边/角点没有穿越交点时被漏掉。
|
||||
xs.push(a.x);
|
||||
}
|
||||
for edge in [top, bottom] {
|
||||
if (a.y < edge && b.y > edge) || (b.y < edge && a.y > edge) {
|
||||
// 只有真正跨过水平边界才插值,分母 b.y-a.y 在此条件下非零。
|
||||
xs.push(a.x + (b.x - a.x) * (edge - a.y) / (b.y - a.y));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !xs.is_empty() {
|
||||
// 凹多边形也取整体横向包围,宁可留更宽避让,不在行带内钻进不可靠的局部空洞。
|
||||
blocked.push((
|
||||
xs.iter().copied().fold(f32::INFINITY, f32::min) - e.padding,
|
||||
xs.iter().copied().fold(f32::NEG_INFINITY, f32::max) + e.padding,
|
||||
));
|
||||
}
|
||||
}
|
||||
// 先按左端排序,扫描游标便可同时处理重叠和包含关系,避免输出交叉的可用区间。
|
||||
blocked.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
// x 是尚未被处理阻塞覆盖的最左位置,始终夹在文字行的 left..right 范围内。
|
||||
let mut x = left;
|
||||
// 与函数同名的局部值是结果区间数组,后面 Prepared::row 按这个顺序放词。
|
||||
let mut ranges = Vec::new();
|
||||
for (lo, hi) in blocked {
|
||||
if hi <= left || lo >= right {
|
||||
// 完全位于文本列外的形状不消耗可用宽度,也不移动扫描游标。
|
||||
continue;
|
||||
}
|
||||
if lo > x {
|
||||
// 当前阻塞前的空隙才是可用区间;右端不能超过列右边界。
|
||||
ranges.push((x, lo.min(right)));
|
||||
}
|
||||
// 重叠阻塞只推进到更右处,不因下一个区间的左端较小而倒退或重复输出空间。
|
||||
x = x.max(hi).min(right);
|
||||
}
|
||||
if x < right {
|
||||
// 所有阻塞处理后剩余的尾段仍可放文字,整行无障碍时这里返回完整列宽。
|
||||
ranges.push((x, right));
|
||||
}
|
||||
// 极窄缝不进入字词放置,既降低工作量,也避免在几何边缘生成难以使用的片段。
|
||||
ranges.into_iter().filter(|(l, r)| r - l >= 8.).collect()
|
||||
}
|
||||
/// Function 的 Flow 分支调用,把预排文字放入有限矩形并避开障碍,生成包含图片字形的 DisplayList。
|
||||
fn flow(cx: &mut NativeContext<'_>, desktop: ObjectRef, args: &[Value]) -> Result<Value, VmError> {
|
||||
// 第一参必须是 Prepare 返回的资源;只靠对象上的同名 prepared 属性不能替代原生 payload。
|
||||
let resource = object(&args[0])?;
|
||||
// 借 payload 取资源元数据,随后复制 Arc/行高以结束不可变借用,允许下面继续分配 VM 对象。
|
||||
let text = cx
|
||||
.store()
|
||||
.payload::<TextResource>(resource, "PreparedText")?;
|
||||
// 只共享塑形与字形图片,不把每次 Flow 的游标写回资源,多个视图可独立排同一份文字。
|
||||
let prepared = text.prepared.clone();
|
||||
// 行高在 Prepare 时已验证为正,下面 height/line 的行数预算因此有明确含义。
|
||||
let line = text.line;
|
||||
// x/y 是本次文字矩形的逻辑原点,与 Exclusion 中的点必须处于同一坐标空间。
|
||||
let x = number(&args[1])?;
|
||||
// y 也作为首行 top,不按字体 baseline 参数解释。
|
||||
let y = number(&args[2])?;
|
||||
// 列宽约束 ranges 的左右边界,不改变预排字形本身的宽度。
|
||||
let width = number(&args[3])?;
|
||||
// 矩形高度限定完整行带数量,行带放不下时停止而非溢出绘制区域。
|
||||
let height = number(&args[4])?;
|
||||
// 数字开关决定完整单词是否拆成独立字母图像命令;不是修改词/字母换行规则的开关。
|
||||
let letters = number(&args[6])? != 0.;
|
||||
if width < 0. || height < 0. || height / line > 1024. {
|
||||
// 限制布局循环最多 1024 行;可用区间全被遮挡时也不能无界向下寻找空间。
|
||||
return Err(invalid("text flow bounds exceed budget"));
|
||||
}
|
||||
// 障碍必须经宿主 ObjectList 的只读元素接口取得,避免在计算中执行任意源迭代协议。
|
||||
let items = crate::object_list::items(cx.store(), object(&args[5])?)?;
|
||||
if items.len() > 512 {
|
||||
return Err(invalid("text flow exceeds 512 exclusions"));
|
||||
}
|
||||
// 每个元素验证真实 Exclusion payload;普通对象不因拥有 circle/polygon 属性就成为障碍资源。
|
||||
let exclusions = items
|
||||
.iter()
|
||||
.map(|&o| cx.store().payload::<Exclusion>(o, "Exclusion"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// 第一阶段只计算词/字母摆放,仍未生成任何 VM PaintCommand。
|
||||
let mut placements = Vec::new();
|
||||
// 每次调用从词首开始,资源可复用但消费位置不跨调用保留。
|
||||
let mut cursor = Cursor::default();
|
||||
// 行扫描从原点向下推进,即使一行全被避让也会消耗 line 高度,保证循环有界。
|
||||
let mut top = y;
|
||||
while top + line <= y + height && cursor.word < prepared.words.len() {
|
||||
// 当前行的可用区间随障碍形状变化,不能沿用上一行的投影宽度。
|
||||
let intervals = ranges(x, x + width, top, line, &exclusions);
|
||||
prepared.row(&mut cursor, &intervals, top, &mut placements);
|
||||
top += line;
|
||||
}
|
||||
// 第二阶段将摆放变成图片命令,字符墨迹已在 Prepare 时形成,无需再次字体塑形。
|
||||
let mut commands = Vec::new();
|
||||
for p in placements {
|
||||
// p.word/p.letter 指回预排资源,同一个词的多个出现共享像素图片。
|
||||
let word = &prepared.words[p.word];
|
||||
// 已拆行的单字母必须只画该字母;完整词可按 letters 开关选择逐字图或整词图。
|
||||
let inks = if let Some(i) = p.letter {
|
||||
std::slice::from_ref(&word.letters[i])
|
||||
} else if letters {
|
||||
// 逐字命令便于源程序后续分别变换,每张图仍来自同一份字形预绘制结果。
|
||||
&word.letters[..]
|
||||
} else {
|
||||
// 整词图命令数量更少,布局宽度仍按同一 word 度量,视觉原点与字母模式一致。
|
||||
std::slice::from_ref(&word.ink)
|
||||
};
|
||||
// 字母模式沿词内 advance 累加 x;整词模式只迭代一张图,不重复应用词总宽。
|
||||
let mut px = p.x;
|
||||
for ink in inks {
|
||||
// 为图片共享像素创建托管资源外壳,PaintCommand 的 image 属性形成明确 VM 强边。
|
||||
let image = cx.allocate(ImageResource(ink.image.clone()))?;
|
||||
attach(cx, image, desktop)?;
|
||||
commands.push(command(
|
||||
@@ -569,10 +727,12 @@ fn flow(cx: &mut NativeContext<'_>, desktop: ObjectRef, args: &[Value]) -> Resul
|
||||
)?);
|
||||
px += ink.width;
|
||||
if commands.len() > 10_000 {
|
||||
// 行数预算之外再限制命令数,防止单行极多字母模式产生巨量发布数据。
|
||||
return Err(invalid("text flow command budget exceeded"));
|
||||
}
|
||||
}
|
||||
}
|
||||
// DisplayList 采用受检查 ObjectList,不把 Rust Vec 或任意用户对象当绘制命令集合。
|
||||
let commands = crate::object_list::collection(cx, commands, desktop)?;
|
||||
Ok(Value::Object(crate::native_visual::record(
|
||||
cx,
|
||||
@@ -581,15 +741,18 @@ fn flow(cx: &mut NativeContext<'_>, desktop: ObjectRef, args: &[Value]) -> Resul
|
||||
vec![("commands", Value::Object(commands))],
|
||||
)?))
|
||||
}
|
||||
/// ui_bridge::bootstrap 在类型/协议安装后调用,注册 ui.graphics 和 math 命名空间,不加载资源或执行绘制。
|
||||
pub(crate) fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
ui: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
// 命名空间自身是普通 Object,显式根由候选运行时统一管理,安装失败时也会清理。
|
||||
let graphics = vm.new_object()?;
|
||||
roots.push(graphics);
|
||||
attach_vm(vm, graphics, "Object", desktop)?;
|
||||
// 数值辅助函数独立挂在 graphics.math,避免把 sin/now 等名字注入用户全局命名空间。
|
||||
let math = vm.new_object()?;
|
||||
roots.push(math);
|
||||
attach_vm(vm, math, "Object", desktop)?;
|
||||
@@ -617,6 +780,7 @@ pub(crate) fn install(
|
||||
(math, "max", Op::Max),
|
||||
(math, "clamp", Op::Clamp),
|
||||
] {
|
||||
// 每个入口有独立 Op 标签及同一个 desktop 捕获,VM 根据 arity 检查数量再进入 Function::invoke。
|
||||
let f = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
Function { op, desktop },
|
||||
@@ -626,48 +790,66 @@ pub(crate) fn install(
|
||||
attach_vm(vm, f, "Function", desktop)?;
|
||||
vm.set_attr(owner, name, Value::Object(f))?;
|
||||
}
|
||||
// 圆周率是数值属性而非零参函数,读取无须采样时钟或进入原生调度。
|
||||
vm.set_attr(math, "pi", Value::Number(std::f64::consts::PI.into()))?;
|
||||
vm.set_attr(graphics, "math", Value::Object(math))?;
|
||||
vm.set_attr(ui, "graphics", Value::Object(graphics))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// install 使用直接 VM 分配而非 NativeContext,借此把命名空间/函数附上已注册名义类型。
|
||||
fn attach_vm(vm: &mut Vm, o: ObjectRef, name: &str, desktop: ObjectRef) -> Result<(), VmError> {
|
||||
// 查精确 Type 身份,不为每个函数重新创建名为 Function 的类型对象。
|
||||
let t = crate::ui_bridge::desktop_type(vm.object_store(), name, desktop)?;
|
||||
vm.attach_type(o, t)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// UiBridge::dispatch 为一次原始 pointer 输入创建的临时 payload,经 VM 调用进入事件传播。
|
||||
pub(crate) struct PointerDispatch {
|
||||
// 接收事件的业务 Block;同一个 Block 可以有多个 Mount,因此不能只存 owner。
|
||||
pub owner: ObjectRef,
|
||||
// 本次具体出现位置,提供挂载状态、局部变换与后续传播路径上下文。
|
||||
pub mount: ObjectRef,
|
||||
// Event 类型和传播资源域来自当前窗口 desktop,不从 GUI 持有的原生指针取得。
|
||||
pub desktop: ObjectRef,
|
||||
// 保留 pointer-down/move/up 等原始事件种类,不自动合成为 click。
|
||||
pub kind: String,
|
||||
// 输入坐标先保留外层空间表示,invoke 在所属 Mount 几何上逆投影。
|
||||
pub point: Point,
|
||||
}
|
||||
impl NativeCallable for PointerDispatch {
|
||||
/// VM 调用无参数临时驱动,全部输入已捕获在 payload 中,避免调用方再次传不匹配目标。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
/// VM 分派临时 callable 时验证 Mount,生成带局部 x/y 的 Event,再交事件模块执行捕获/目标/冒泡。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
// 再检查实时 payload,GUI 命中时的可交互标记不能保证当前对象仍挂载或仍订阅指针事件。
|
||||
let data = cx
|
||||
.store()
|
||||
.payload::<crate::mount::Mount>(self.mount, "Mount")?;
|
||||
// 几何属于具体出现位置,源对象属性上的 x/y 不能替代投影后的 Mount 几何。
|
||||
let g = &data.geometry;
|
||||
if !data.mounted || !g.pointer_events {
|
||||
return Err(invalid(
|
||||
"pointer target is detached or has no pointer subscriptions",
|
||||
));
|
||||
}
|
||||
// 先撤销嵌套视图/面板映射,再撤销该出现的二维视图,失败时不沿用原屏幕坐标。
|
||||
let local = g
|
||||
.view_point(self.point, false)
|
||||
.map(|p| g.view.unwrap_or_default().inverse(p))
|
||||
.ok_or(invalid("pointer cannot be projected"))?;
|
||||
// 目标事件坐标以该出现外框左上角为原点,不是页面/世界绝对位置。
|
||||
let (x, y) = (local.x - g.x, local.y - g.y);
|
||||
// Event 必须与当前宿主域的名义类型一致,不能借用另一个会话的类型身份。
|
||||
let definition = crate::ui_bridge::desktop_type(cx.store(), "Event", self.desktop)?;
|
||||
// NativeContext 负责临时根,返回/委托时提升输出,异常路径也不会遗留新建 Event 根。
|
||||
let event = crate::event_dispatch::new_event(cx, definition, &self.kind)?;
|
||||
cx.set_attr(event, "x", n(x))?;
|
||||
cx.set_attr(event, "y", n(y))?;
|
||||
// 事件模块可以返回 Invoke 延续源处理器,仍使用当前 VM 的预算/调用栈而非递归启动解释器。
|
||||
crate::event_dispatch::dispatch(cx, self.owner, event, Some(self.mount), self.desktop)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user