feat: render interactive manuscript from Endor through generic graphics

This commit is contained in:
2026-11-12 10:52:28 +08:00
parent d29a1be329
commit 2715c1ce2c
71 changed files with 3000 additions and 78 deletions
+158 -51
View File
@@ -1,18 +1,13 @@
//! 原生窗口输入到执行 worker 的纯数据传输。Input 只含窗口/会话/版本/Mount 身份及有限坐标。
//! 连续相机和滚动输入出队时可更新帧版本,但不改变捕获目标和所属 VM;离散点击仍保留严格的过期帧语义。
//! 队列有界且当前逐项经本地 HTTP 发送;这不意味着输入已经按显示帧合并,也不是无损无限队列。
//! 生产端只合并相同目标的相邻绝对指针采样;有序动作是边界。relay 直接进入串行 worker,后台等待确认。
//!
//! Native input transport. Frame/mount identities and optional logical pointer positions cross to the VM worker.
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
net::TcpStream,
sync::{
Arc, RwLock,
mpsc::{SyncSender, sync_channel},
},
collections::VecDeque,
sync::{Arc, Condvar, Mutex, RwLock},
thread,
time::Duration,
};
use winit::event_loop::EventLoopProxy;
@@ -142,6 +137,23 @@ impl Input {
_ => Err("scroll requires point and finite delta, with no press_point"),
};
}
if matches!(
self.kind.as_str(),
"pointermove" | "pointerdown" | "pointerup" | "pointerleave" | "pointercancel"
) {
return if self.mount != 0
&& self.press_point.is_none()
&& self.delta.is_none()
&& self.screen_position.is_none()
&& self
.point
.is_some_and(|p| p.iter().all(|v| v.is_finite() && v.abs() <= 1_000_000.))
{
Ok(())
} else {
Err("pointer event requires finite point and target")
};
}
if self.delta.is_some() {
return Err("delta is only accepted for scroll input");
}
@@ -161,20 +173,80 @@ impl Input {
}
}
#[derive(Clone)]
/// 原生输入的有界发送端,后台线程串行发往本地 API;所有窗口共享权威发布状态。
pub struct Client(SyncSender<Input>);
/// Bounded producer-side coalescing preserves action barriers while the relay
/// waits for a VM acknowledgement. Motion cannot fill the queue by itself.
struct Queue {
items: VecDeque<Input>,
senders: usize,
closed: bool,
}
struct Inbox {
queue: Mutex<Queue>,
ready: Condvar,
}
pub struct Client(Arc<Inbox>);
impl Clone for Client {
fn clone(&self) -> Self {
self.0.queue.lock().unwrap().senders += 1;
Self(self.0.clone())
}
}
impl Drop for Client {
fn drop(&mut self) {
if let Ok(mut q) = self.0.queue.lock() {
q.senders -= 1;
if q.senders == 0 {
q.closed = true;
q.items.clear();
self.0.ready.notify_all();
}
}
}
}
fn enqueue(queue: &mut VecDeque<Input>, input: Input) -> bool {
if input.kind == "pointermove"
&& let Some(last) = queue.back_mut()
&& last.kind == "pointermove"
&& (last.window, last.session, last.mount) == (input.window, input.session, input.mount)
{
*last = input;
return true;
}
if queue.len() >= 64 {
return false;
}
queue.push_back(input);
true
}
impl Inbox {
fn receive(&self) -> Option<Input> {
let mut q = self.queue.lock().ok()?;
while q.items.is_empty() && !q.closed {
q = self.ready.wait(q).ok()?;
}
if q.closed { None } else { q.items.pop_front() }
}
}
impl Client {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub fn new(
proxy: EventLoopProxy<crate::app::AppEvent>,
namespace: Arc<RwLock<crate::document::NamespaceState>>,
control: crate::api::RuntimeControl,
) -> anyhow::Result<Self> {
let (sender, receiver) = sync_channel::<Input>(64);
let inbox = Arc::new(Inbox {
queue: Mutex::new(Queue {
items: VecDeque::new(),
senders: 1,
closed: false,
}),
ready: Condvar::new(),
});
let receiver = inbox.clone();
thread::Builder::new()
.name("tessera-native-events".into())
.spawn(move || {
for mut input in receiver {
while let Some(mut input) = receiver.receive() {
if let Ok(current) = namespace.read() {
if !refresh_continuous_input(&mut input, &current) {
continue;
@@ -182,18 +254,28 @@ impl Client {
} else {
continue;
}
if let Err(error) = send(&input) {
if let Err(error) = control.dispatch_native(input) {
let _ = proxy.send_event(crate::app::AppEvent::RuntimeFailed {
message: error.to_string(),
});
}
}
})?;
Ok(Self(sender))
Ok(Self(inbox))
}
/// 通过有界原生输入客户端或本地 HTTP 发送纯数据事件;过期版本按既定协议处理。
pub fn send(&self, input: Input) -> bool {
self.0.try_send(input).is_ok()
let Ok(mut q) = self.0.queue.lock() else {
return false;
};
if q.closed {
return false;
}
let queued = enqueue(&mut q.items, input);
if queued {
self.0.ready.notify_one();
}
queued
}
}
@@ -201,10 +283,23 @@ impl Client {
// the version at dequeue, never session, window or target. HTTP callers and
// discrete actions still receive strict stale-frame rejection.
/// 连续手势出队时只更新有效目标的帧版本;保留原 session、窗口和 Mount,离散事件不自动重试。
fn refresh_continuous_input(input: &mut Input, current: &crate::document::NamespaceState) -> bool {
pub(crate) fn refresh_continuous_input(
input: &mut Input,
current: &crate::document::NamespaceState,
) -> bool {
if !matches!(
input.kind.as_str(),
"viewport-pan" | "viewport-zoom" | "scene-pan" | "scene-orbit" | "scene-zoom" | "scroll"
"viewport-pan"
| "viewport-zoom"
| "scene-pan"
| "scene-orbit"
| "scene-zoom"
| "scroll"
| "pointermove"
| "pointerdown"
| "pointerup"
| "pointerleave"
| "pointercancel"
) {
return true;
}
@@ -229,6 +324,8 @@ fn refresh_continuous_input(input: &mut Input, current: &crate::document::Namesp
mount.canvas_viewport
} else if input.kind.starts_with("scene-") {
mount.scene3d_viewport && mount.camera_controls
} else if input.kind.starts_with("pointer") {
mount.pointer_events
} else {
mount.scroll.is_some()
}
@@ -240,39 +337,6 @@ fn refresh_continuous_input(input: &mut Input, current: &crate::document::Namesp
true
}
/// 通过有界原生输入客户端或本地 HTTP 发送纯数据事件;过期版本按既定协议处理。
fn send(input: &Input) -> anyhow::Result<()> {
let body = serde_json::to_string(input)?;
let mut stream =
TcpStream::connect_timeout(&crate::api::API_ADDRESS.parse()?, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
stream.set_write_timeout(Some(Duration::from_secs(2)))?;
write!(
stream,
"POST /v1/namespaces/app.main/events HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
)?;
let mut response = String::new();
stream.take(32768).read_to_string(&mut response)?;
let status = response.split_whitespace().nth(1).unwrap_or("");
// An old frame's event is deliberately discarded, with no automatic retry.
if status == "409" {
return Ok(());
}
if status != "200" {
let body = response
.split_once("\r\n\r\n")
.map(|(_, body)| body)
.unwrap_or(&response);
anyhow::bail!(
"Native event failed: {}",
body.chars().take(1024).collect::<String>()
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -353,3 +417,46 @@ mod tests {
assert!(input.validate().is_err());
}
}
#[cfg(test)]
mod coalescing_tests {
use super::*;
#[test]
fn producer_side_motion_coalescing_keeps_action_and_target_boundaries() {
let template: Input = serde_json::from_str(
r#"{"session":1,"layout_version":1,"mount":2,"kind":"pointermove","point":[0,0]}"#,
)
.unwrap();
let mut q = VecDeque::new();
for i in 0..1000 {
let mut sample = template.clone();
sample.point = Some([i as f32, 0.]);
assert!(enqueue(&mut q, sample));
}
assert_eq!(q.len(), 1);
assert_eq!(q[0].point.unwrap()[0], 999.);
let mut down = template.clone();
down.kind = "pointerdown".into();
enqueue(&mut q, down);
let mut moved = template.clone();
moved.point = Some([1200., 0.]);
enqueue(&mut q, moved);
let mut up = template.clone();
up.kind = "pointerup".into();
enqueue(&mut q, up);
let mut other = template;
other.window = 2;
enqueue(&mut q, other);
assert_eq!(
q.iter().map(|i| i.kind.as_str()).collect::<Vec<_>>(),
[
"pointermove",
"pointerdown",
"pointermove",
"pointerup",
"pointermove"
]
);
assert_eq!(q.back().unwrap().window, 2);
}
}