use std::collections::VecDeque;
use std::sync::{Arc, Mutex, OnceLock};
#[cfg(all(feature = "async-runtime", feature = "window"))]
use winit::event_loop::EventLoopProxy;
use crate::component::Component;
#[cfg(all(feature = "async-runtime", feature = "window"))]
static DEVTOOLS_PROXY: OnceLock<EventLoopProxy<crate::async_runtime::UserEvent>> = OnceLock::new();
#[derive(Debug)]
pub enum DevToolsCommand {
Click {
key: String,
response_tx: std::sync::mpsc::Sender<bool>,
},
SetState {
field: String,
value: serde_json::Value,
response_tx: std::sync::mpsc::Sender<bool>,
},
SaveState,
ReloadTemplate,
SaveAll {
response_tx: std::sync::mpsc::Sender<bool>,
},
Type {
key: String,
text: String,
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
Key {
key: String,
keyname: String,
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
Tree {
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
LayoutCmd {
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
Find {
query: String,
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
Shot {
response_tx: std::sync::mpsc::Sender<Option<String>>,
},
}
static LATEST_SNAPSHOT: OnceLock<Arc<Mutex<Option<String>>>> = OnceLock::new();
fn latest_snapshot_slot() -> &'static Arc<Mutex<Option<String>>> {
LATEST_SNAPSHOT.get_or_init(|| Arc::new(Mutex::new(None)))
}
pub fn update_latest_snapshot(json: String) {
let slot = latest_snapshot_slot();
if let Ok(mut guard) = slot.lock() {
*guard = Some(json);
}
}
#[doc(hidden)]
pub(crate) fn read_latest_snapshot() -> Option<String> {
let slot = latest_snapshot_slot();
slot.lock().ok()?.clone()
}
static COMMAND_QUEUE: OnceLock<Arc<Mutex<VecDeque<DevToolsCommand>>>> = OnceLock::new();
fn command_queue() -> &'static Arc<Mutex<VecDeque<DevToolsCommand>>> {
COMMAND_QUEUE.get_or_init(|| Arc::new(Mutex::new(VecDeque::new())))
}
#[doc(hidden)]
pub(crate) fn send_command(cmd: DevToolsCommand) {
#[cfg(all(feature = "async-runtime", feature = "window"))]
if let Some(proxy) = DEVTOOLS_PROXY.get() {
let _ = proxy.send_event(crate::async_runtime::UserEvent::DevTools(cmd));
return;
}
let queue = command_queue();
if let Ok(mut guard) = queue.lock() {
guard.push_back(cmd);
}
}
#[doc(hidden)]
#[cfg(all(feature = "async-runtime", feature = "window"))]
pub(crate) fn install_proxy(proxy: &EventLoopProxy<crate::async_runtime::UserEvent>) {
let _ = DEVTOOLS_PROXY.set(proxy.clone());
}
#[doc(hidden)]
#[allow(dead_code)]
pub(crate) fn drain_commands() -> Vec<DevToolsCommand> {
let queue = command_queue();
let mut cmds = Vec::new();
if let Ok(mut guard) = queue.lock() {
while let Some(cmd) = guard.pop_front() {
cmds.push(cmd);
}
}
cmds
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DevToolsSnapshot {
pub window_token: u32,
pub vdom: serde_json::Value,
pub state: serde_json::Value,
pub layout: Option<serde_json::Value>,
}
pub trait DevToolsInspect: Component {
fn inspect_state(&self) -> serde_json::Value;
}
impl<T: Component + ?Sized> DevToolsInspect for T {
fn inspect_state(&self) -> serde_json::Value {
<Self as Component>::inspect_state(self)
}
}
pub fn inspect_field<T: serde::Serialize + ?Sized>(value: &T) -> serde_json::Value {
serde_json::to_value(value).unwrap_or(serde_json::Value::Null)
}
pub fn capture_snapshot(token: u32, component: &dyn Component) -> DevToolsSnapshot {
DevToolsSnapshot {
window_token: token,
vdom: component.render().to_json(),
state: component.inspect_state(),
layout: None,
}
}
pub const STATE_FILE: &str = ".light/state.json";
pub fn state_file_path() -> std::path::PathBuf {
std::env::var_os("LIGHT_STATE_FILE")
.map(std::path::PathBuf::from)
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| std::path::PathBuf::from(STATE_FILE))
}
pub fn save_state_file(state: &serde_json::Value) -> std::io::Result<()> {
let path = state_file_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let json = serde_json::to_string_pretty(state).map_err(std::io::Error::other)?;
std::fs::write(&path, json)?;
Ok(())
}
pub fn load_state_file() -> Result<Option<serde_json::Value>, std::io::Error> {
let path = state_file_path();
if !path.exists() {
return Ok(None);
}
let raw = std::fs::read_to_string(&path)?;
let value: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("не удалось разобрать {}: {e}", path.display()),
)
})?;
Ok(Some(value))
}
#[cfg(feature = "devtools")]
pub fn encode_screenshot(buf: &[u8], width: u32, height: u32) -> String {
use base64::Engine;
let mut png_data = Vec::new();
let mut encoder = png::Encoder::new(&mut png_data, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.expect("png header")
.write_image_data(buf)
.expect("png write");
let b64 = base64::engine::general_purpose::STANDARD.encode(&png_data);
format!("base64:{b64}")
}
pub fn serialize_tree(element: &crate::vdom::VElement) -> serde_json::Value {
serialize_tree_inner(element)
}
fn serialize_tree_inner(el: &crate::vdom::VElement) -> serde_json::Value {
use crate::vdom::NodeKind;
let tag = if el.tag.is_empty() {
None
} else {
Some(serde_json::Value::String(el.tag.to_owned()))
};
let text = match &el.kind {
NodeKind::Text { content } => Some(serde_json::Value::String(content.clone())),
_ => None,
};
let children: Vec<serde_json::Value> = el.children.iter().map(serialize_tree_inner).collect();
let mut obj = serde_json::Map::new();
obj.insert("key".into(), serde_json::Value::String(el.key.to_owned()));
obj.insert("tag".into(), tag.unwrap_or(serde_json::Value::Null));
obj.insert("text".into(), text.unwrap_or(serde_json::Value::Null));
obj.insert("children".into(), serde_json::Value::Array(children));
serde_json::Value::Object(obj)
}
pub fn serialize_layout(
layout: &crate::layout::Layout,
tree: Option<&crate::vdom::VElement>,
) -> serde_json::Value {
let nodes = layout.nodes();
if nodes.is_empty() {
return serde_json::Value::Null;
}
serialize_layout_node(nodes, tree, 0, 0)
}
fn serialize_layout_node(
nodes: &[crate::layout::PlacedNode],
tree: Option<&crate::vdom::VElement>,
index: usize,
depth: usize,
) -> serde_json::Value {
if depth > 100 || index >= nodes.len() {
return serde_json::Value::Null;
}
let node = &nodes[index];
let tag = tree.and_then(|t| t.get(node.key)).and_then(|el| {
if el.tag.is_empty() {
None
} else {
Some(el.tag.to_owned())
}
});
let rect = node.rect;
let children: Vec<serde_json::Value> = node
.children
.iter()
.map(|&ci| serialize_layout_node(nodes, tree, ci, depth + 1))
.collect();
let mut obj = serde_json::Map::new();
obj.insert("key".into(), serde_json::Value::String(node.key.to_owned()));
obj.insert(
"tag".into(),
tag.map(serde_json::Value::String)
.unwrap_or(serde_json::Value::Null),
);
obj.insert("x".into(), serde_json::json!(rect.x));
obj.insert("y".into(), serde_json::json!(rect.y));
obj.insert("w".into(), serde_json::json!(rect.w));
obj.insert("h".into(), serde_json::json!(rect.h));
obj.insert("children".into(), serde_json::Value::Array(children));
serde_json::Value::Object(obj)
}
pub fn find_element(
tree: &crate::vdom::VElement,
layout: Option<&crate::layout::Layout>,
query: &str,
) -> Option<serde_json::Value> {
let q: serde_json::Value = serde_json::from_str(query).ok()?;
let want_tag = q.get("tag").and_then(|v| v.as_str());
let want_text = q.get("text").and_then(|v| v.as_str());
let want_attrs: Vec<(String, String)> = q
.get("attr")
.and_then(|a| a.as_object())
.map(|m| {
m.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_owned())))
.collect()
})
.unwrap_or_default();
for el in tree.descendants() {
if let Some(want_tag) = want_tag
&& el.tag != want_tag
{
continue;
}
if let Some(want_text) = want_text {
let mut buf = String::new();
collect_match_text(el, &mut buf);
if buf != want_text {
continue;
}
}
if !want_attrs.is_empty() {
let all_match = want_attrs
.iter()
.all(|(k, v)| el.attr(k) == Some(v.as_str()));
if !all_match {
continue;
}
}
let tag = if el.tag.is_empty() {
None
} else {
Some(el.tag.to_owned())
};
let rect = layout
.and_then(|l| l.node(el.key))
.map(|n| {
serde_json::json!({
"x": n.rect.x,
"y": n.rect.y,
"w": n.rect.w,
"h": n.rect.h,
})
})
.unwrap_or(serde_json::json!({"x": 0, "y": 0, "w": 0, "h": 0}));
let mut obj = serde_json::Map::new();
obj.insert("key".into(), serde_json::Value::String(el.key.to_owned()));
obj.insert(
"tag".into(),
tag.map(serde_json::Value::String)
.unwrap_or(serde_json::Value::Null),
);
obj.insert("rect".into(), rect);
return Some(serde_json::Value::Object(obj));
}
None
}
fn collect_match_text(el: &crate::vdom::VElement, out: &mut String) {
use crate::vdom::NodeKind;
if let NodeKind::Text { content } = &el.kind {
out.push_str(content);
return;
}
for child in &el.children {
collect_match_text(child, out);
}
}
pub mod server;
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::{Layout, TextMetrics};
use crate::vdom::{ButtonType, NodeKind, VElement};
struct StubMetrics;
impl TextMetrics for StubMetrics {
fn measure(&self, _text: &str, font_size: f32) -> (f32, f32) {
(font_size * 4.0, font_size * 1.5)
}
}
fn sample_tree() -> VElement {
VElement::container(
"0",
NodeKind::Window,
vec![
VElement::container(
"0.0",
NodeKind::Column,
vec![
VElement::container(
"0.0.0",
NodeKind::Button {
disabled: false,
button_type: ButtonType::default(),
},
vec![
VElement::leaf(
"0.0.0.0",
NodeKind::Text {
content: "+1".to_owned(),
},
)
.with_tag("span"),
],
)
.with_tag("button"),
VElement::leaf(
"0.1",
NodeKind::Text {
content: "Count".to_owned(),
},
),
],
)
.with_tag("div"),
],
)
.with_tag("window")
.with_window(crate::component::WindowConfig::default())
}
#[test]
fn serialize_tree_shape() {
let v = serialize_tree(&sample_tree());
assert_eq!(v["key"], "0");
assert_eq!(v["tag"], serde_json::json!("window"));
assert_eq!(v["text"], serde_json::Value::Null);
let div = &v["children"][0];
assert_eq!(div["key"], "0.0");
assert_eq!(div["tag"], serde_json::json!("div"));
let button = &div["children"][0];
assert_eq!(button["tag"], serde_json::json!("button"));
assert_eq!(button["text"], serde_json::Value::Null);
let text = &div["children"][1];
assert_eq!(text["text"], serde_json::json!("Count"));
assert_eq!(text["tag"], serde_json::Value::Null);
}
#[test]
fn serialize_layout_shape() {
let tree = sample_tree();
let layout = Layout::build(&tree, (400.0, 300.0), &StubMetrics);
let v = serialize_layout(&layout, Some(&tree));
assert_eq!(v["key"], "0");
assert_eq!(v["tag"], serde_json::json!("window"));
assert_eq!(v["w"], 400.0);
assert_eq!(v["h"], 300.0);
assert!(v["x"].is_number());
assert!(v["y"].is_number());
assert!(!v["children"].as_array().unwrap().is_empty());
}
#[test]
fn find_element_by_tag_and_text() {
let tree = sample_tree();
let layout = Layout::build(&tree, (400.0, 300.0), &StubMetrics);
let res = find_element(&tree, Some(&layout), r#"{"tag":"button","text":"+1"}"#)
.expect("button found");
assert_eq!(res["key"], "0.0.0");
assert_eq!(res["tag"], serde_json::json!("button"));
assert!(res["rect"]["w"].is_number());
}
#[test]
fn find_element_by_attr() {
let mut tree = sample_tree();
if let Some(div) = tree.children.get_mut(0)
&& let Some(btn) = div.children.get_mut(0)
{
btn.attrs.push(("class", "btn".to_owned()));
}
let res = find_element(&tree, None, r#"{"tag":"button","attr":{"class":"btn"}}"#)
.expect("found by attr");
assert_eq!(res["key"], "0.0.0");
}
#[test]
fn find_element_no_match_and_bad_json() {
let tree = sample_tree();
assert!(
find_element(&tree, None, r#"{"tag":"input"}"#).is_none(),
"no <input> in tree"
);
assert!(
find_element(&tree, None, "not-json").is_none(),
"bad json -> None"
);
}
#[cfg(feature = "devtools")]
#[test]
fn encode_screenshot_is_png_base64() {
let buf: Vec<u8> = vec![255, 0, 0, 255, 0, 255, 0, 255];
let out = encode_screenshot(&buf, 2, 1);
let b64 = out.strip_prefix("base64:").expect("base64: prefix");
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD
.decode(b64)
.expect("decodes");
assert_eq!(
&bytes[0..8],
&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]
);
}
}