beffroi-tools/crates/midra-layout/src/device.rs

294 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Eikos snapshots. Explicit layer writes live in `device_send`.
use crate::{
Geometry,
import::{DetectedShape, ImportDocument},
};
use serde_json::Value;
use std::{io::Read, net::IpAddr, time::Duration};
const MAX_RESPONSE: u64 = 32 * 1024 * 1024;
/// A locally captured device snapshot, not an editor project or writable payload.
#[derive(Clone, Debug)]
pub struct Snapshot {
pub identity: String,
pub screens: Vec<Screen>,
/// In-memory firmware state used for reviewed sends; never saved to projects.
pub raw: Value,
}
#[derive(Clone, Debug)]
pub struct Screen {
pub id: String,
pub resolution: [u32; 2],
pub preview_bank: String,
pub layers: Vec<Layer>,
}
#[derive(Clone, Debug)]
pub struct Layer {
pub id: String,
pub source: String,
pub geometry: Geometry,
pub container: Geometry,
pub framing: Option<(crate::formats::Source, crate::formats::Crop)>,
pub unsupported: Option<String>,
}
fn value<'a>(v: &'a Value, path: &str) -> Result<&'a Value, String> {
v.pointer(path)
.ok_or_else(|| format!("Missing device field {path}"))
}
fn text(v: &Value, path: &str) -> Result<String, String> {
value(v, path)?
.as_str()
.map(str::to_owned)
.ok_or_else(|| format!("Invalid device text {path}"))
}
fn number(v: &Value, path: &str) -> Result<f64, String> {
value(v, path)?
.as_f64()
.filter(|n| n.is_finite())
.ok_or_else(|| format!("Invalid device number {path}"))
}
impl Snapshot {
pub fn parse(identity: &Value, raw: &Value) -> Result<Self, String> {
let kind = text(identity, "/type")?;
if kind != "Eikos 4K" {
return Err(format!(
"Unsupported device {kind}; this adapter targets Eikos 4K."
));
}
let version =
["major", "minor", "patch"].map(|k| number(identity, &format!("/version/{k}")));
let [major, minor, patch] = version;
let identity = format!("{kind} · firmware {}.{}.{}", major?, minor?, patch?);
let device = value(raw, "/device")?;
let items = value(device, "/screenList/items")?
.as_object()
.ok_or("Invalid screen list")?;
let mut screens = Vec::new();
for (id, s) in items {
let transition = text(
device,
&format!("/transition/screenList/items/{id}/status/pp/transition"),
)?;
let bank = match transition.as_str() {
"AT_DOWN" => "UP",
"AT_UP" => "DOWN",
_ => return Err(format!("Screen {id} is transitioning. Refresh when idle.")),
};
let w = number(s, "/canvas/status/size/pp/sizeH")?;
let h = number(s, "/canvas/status/size/pp/sizeV")?;
// The firmware includes disabled screen slots with a zero canvas.
if w == 0.0 && h == 0.0 {
continue;
}
if w.fract() != 0.0
|| h.fract() != 0.0
|| !(1.0..=16384.0).contains(&w)
|| !(1.0..=16384.0).contains(&h)
{
return Err(format!("Invalid canvas for screen {id}"));
}
let entries = value(s, &format!("/presetList/items/{bank}/liveLayerList/items"))?
.as_object()
.ok_or("Invalid layer list")?;
let mut layers = Vec::new();
for (id, layer) in entries {
let source = text(layer, "/source/pp/input")?;
if source == "NONE" || source.is_empty() {
continue;
}
let width = number(layer, "/size/pp/sizeH")?;
let height = number(layer, "/size/pp/sizeV")?;
let geometry = Geometry {
x: number(layer, "/position/pp/posH")? - width / 2.0,
y: number(layer, "/position/pp/posV")? - height / 2.0,
width,
height,
}
.validate()?;
let mut unsupported = None;
for field in ["crop", "mask"] {
for edge in ["left", "right", "top", "bottom"] {
if number(layer, &format!("/{field}/pp/{edge}"))? != 0.0 {
unsupported = Some(format!(
"Nonzero {field}: visible-bound conversion is not verified."
));
}
}
}
let container = geometry;
let mut geometry = geometry;
let mut framing = None;
if layer
.pointer("/crop/pp/aspectOverride")
.and_then(Value::as_str)
== Some("CENTERED")
&& ["left", "right", "top", "bottom"].iter().all(|edge| {
layer
.pointer(&format!("/mask/pp/{edge}"))
.and_then(Value::as_i64)
== Some(0)
})
{
match centered_framing(layer, container) {
Ok((visible, source, crop)) => {
geometry = visible;
framing = Some((source, crop));
unsupported = None;
}
Err(error) => unsupported = Some(error),
}
}
layers.push(Layer {
id: id.clone(),
source,
geometry,
container,
framing,
unsupported,
});
}
screens.push(Screen {
id: id.clone(),
resolution: [w as u32, h as u32],
preview_bank: bank.into(),
layers,
});
}
if screens.is_empty() {
return Err("No screens returned by device".into());
}
Ok(Self {
identity,
screens,
raw: raw.clone(),
})
}
}
fn centered_framing(
layer: &Value,
container: Geometry,
) -> Result<(Geometry, crate::formats::Source, crate::formats::Crop), String> {
use crate::formats::{self, Aspect, Crop, Source};
let native = formats::resolution_from_values([
number(layer, "/status/pp/contentWidth")?,
number(layer, "/status/pp/contentHeight")?,
])?;
let edge = |name: &str, axis: usize| -> Result<f64, String> {
let value = number(layer, &format!("/crop/pp/{name}"))?;
if value.fract() != 0.0 || !(0.0..=65535.0).contains(&value) {
return Err("Invalid device crop units".into());
}
Ok(value / 65535.0 * native[axis] as f64)
};
let crop = Crop {
left: edge("left", 0)?,
right: edge("right", 0)?,
top: edge("top", 1)?,
bottom: edge("bottom", 1)?,
};
let remaining = crop.remaining(native.map(f64::from))?;
let scale = (container.width / remaining[0]).min(container.height / remaining[1]);
let [cx, cy] = container.center();
let geometry = Geometry {
x: cx - remaining[0] * scale / 2.0,
y: cy - remaining[1] * scale / 2.0,
width: remaining[0] * scale,
height: remaining[1] * scale,
}
.validate()?;
formats::mapping(
native.map(f64::from),
[geometry.width, geometry.height],
crop,
)?;
let aspect = if (native[0] as f64 / native[1] as f64 - 16.0 / 9.0).abs() < 1e-8 {
Aspect::SixteenNine
} else {
Aspect::Custom
};
Ok((
geometry,
Source {
native,
aspect,
input_crop: Crop::default(),
},
crop,
))
}
impl Screen {
pub fn import(&self, indices: &[usize]) -> Result<ImportDocument, String> {
if indices.is_empty() {
return Err("Choose device layers to import.".into());
}
let mut shapes = Vec::new();
for &index in indices {
let layer = self
.layers
.get(index)
.ok_or("Device layer no longer exists")?;
if let Some(reason) = &layer.unsupported {
return Err(format!("Layer {}: {reason}", layer.id));
}
let id = format!("Screen {} · Layer {} · {}", self.id, layer.id, layer.source);
if shapes.iter().any(|s: &DetectedShape| s.id == id) {
return Err("Duplicate device layer selection".into());
}
shapes.push(DetectedShape {
id,
geometry: layer.geometry,
outline: [0.0; 2],
background: false,
background_only: false,
zoom: None,
});
}
Ok(ImportDocument {
shapes,
svg: false,
note: format!(
"Preview screen {} ({} × {}). Centered layers include visible bounds and framing. Other aspect modes use container geometry only. Routing, shared input crop and effects are not imported. Device slots may include unavailable layers. Review mapping before applying.",
self.id, self.resolution[0], self.resolution[1]
),
})
}
}
fn read_json(client: &reqwest::blocking::Client, url: &str) -> Result<Value, String> {
let response = client
.get(url)
.send()
.and_then(|r| r.error_for_status())
.map_err(|e| format!("Cannot read Midra: {e}"))?;
let mut bytes = Vec::new();
response
.take(MAX_RESPONSE + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_RESPONSE {
return Err("Device response exceeds 32 MiB".into());
}
serde_json::from_slice(&bytes).map_err(|e| format!("Invalid device JSON: {e}"))
}
/// Perform two GET requests, only on an explicit IP. Call from a worker thread.
pub fn fetch(host: &str) -> Result<Snapshot, String> {
let ip: IpAddr = host
.trim()
.parse()
.map_err(|_| "Enter a device IP address, without http:// or a path.")?;
let authority = match ip {
IpAddr::V4(ip) => ip.to_string(),
IpAddr::V6(ip) => format!("[{ip}]"),
};
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(15))
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| e.to_string())?;
let identity = read_json(&client, &format!("http://{authority}/api/tpp/v1/system"))?;
let state = read_json(&client, &format!("http://{authority}/api/stores/device"))?;
Snapshot::parse(&identity, &state)
}