Decode binary native preview replies without SVG text conversion

This commit is contained in:
gloamxun committed 2026-12-02 03:58:07 +08:00
1 parent 3c09d6486d
commit 4df8983ff5
3 files changed
+73 -11

No files matched your search

+38 -4
View File
@@ -1,5 +1,5 @@
use super::{Edit, EditorSession, MAX_EDIT_BODY, PreviewReply, reply};
use serde_json::json;
use serde_json::{Value, json};
use std::{
sync::{Mutex, Weak, mpsc},
time::Instant,
@@ -67,6 +67,7 @@ pub(super) fn open(request: Request, session: Weak<Mutex<EditorSession>>) {
break;
};
let sequence = edit.sequence;
let binary_preview = edit.binary_preview;
let (status, body) = if let Some(session) = session.upgrade() {
let (sender, receiver) = mpsc::channel();
session
@@ -85,9 +86,7 @@ pub(super) fn open(request: Request, session: Weak<Mutex<EditorSession>>) {
)
};
if socket
.send(Message::text(
json!({ "sequence": sequence, "status": status, "body": body }).to_string(),
))
.send(preview_message(sequence, status, body, binary_preview))
.is_err()
{
break;
@@ -96,6 +95,41 @@ pub(super) fn open(request: Request, session: Weak<Mutex<EditorSession>>) {
});
}
fn preview_message(sequence: u64, status: u16, mut body: Value, binary: bool) -> Message {
if binary
&& (200..300).contains(&status)
&& let Some(pages) = body
.pointer_mut("/update/pages")
.and_then(Value::as_array_mut)
&& pages.iter().all(|page| page["svg"].is_string())
{
// The frame starts with a little-endian JSON length. After the JSON,
// the page SVGs are concatenated in the same order as their byte lengths.
let mut svgs = Vec::with_capacity(pages.len());
for page in pages {
let Value::String(svg) = std::mem::take(&mut page["svg"]) else {
unreachable!("page SVG strings were checked before encoding");
};
page["svg"] = svg.len().into();
svgs.push(svg);
}
let metadata = json!({ "sequence": sequence, "status": status, "body": body });
let mut frame = vec![0; 4];
serde_json::to_writer(&mut frame, &metadata)
.expect("serializing preview metadata to memory");
let metadata_len = u32::try_from(frame.len() - 4).expect("preview metadata fits in u32");
frame[..4].copy_from_slice(&metadata_len.to_le_bytes());
frame.reserve(svgs.iter().map(String::len).sum());
for svg in svgs {
frame.extend_from_slice(svg.as_bytes());
}
return Message::binary(frame);
}
Message::text(json!({ "sequence": sequence, "status": status, "body": body }).to_string())
}
fn header<'a>(request: &'a Request, name: &'static str) -> Option<&'a str> {
let mut matches = request
.headers()