use crate::automation::command::{app_command, parse_args, schema_of, CommandSpec, Ctx, Empty, Outcome};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum Region {
Named(String),
Rect { x: f32, y: f32, w: f32, h: f32 },
}
impl Default for Region {
fn default() -> Self {
Region::Named("full".into())
}
}
#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenshotArgs {
#[serde(default)]
pub region: Region,
pub scale: Option<f32>,
pub width: Option<u32>,
pub height: Option<u32>,
}
pub fn screenshot_args(region: Value, resolution: Value) -> Value {
let mut args = json!({ "region": region });
if let Value::Object(fields) = resolution {
for key in ["scale", "width", "height"] {
if let Some(v) = fields.get(key).filter(|v| !v.is_null()) {
args[key] = v.clone();
}
}
}
args
}
pub const MAX_CAPTURE_SCALE: f32 = 8.0;
pub fn capture_scale(a: &ScreenshotArgs, ppp: f32, view: Option<egui::Rect>, w: u32, h: u32, max_side: Option<u32>) -> Result<f32, String> {
let given = [a.scale.is_some(), a.width.is_some(), a.height.is_some()].iter().filter(|g| **g).count();
if given > 1 {
return Err("bad_args: give at most one of scale, width and height".into());
}
let (_, _, cw, ch, _) = region_px(&a.region, ppp, view, w, h)?;
let scale = match (a.scale, a.width, a.height) {
(Some(s), _, _) => s,
(_, Some(px), _) => px as f32 / cw as f32,
(_, _, Some(px)) => px as f32 / ch as f32,
_ => 1.0,
};
if !(scale.is_finite() && scale > 0.0 && scale <= MAX_CAPTURE_SCALE) {
return Err(format!("bad_args: the capture scale must be in (0, {MAX_CAPTURE_SCALE}] (got {scale})"));
}
if let Some(side) = max_side {
let big = ((w.max(h) as f32) * scale).round() as u32;
if big > side {
return Err(format!("capture_too_large: {scale}x renders the {w}x{h} px surface at {big} px, past this device's {side} px texture limit"));
}
}
Ok(scale)
}
#[derive(Serialize, schemars::JsonSchema)]
pub struct ScreenshotInfo {
pub width: u32,
pub height: u32,
pub ppp: f32,
pub scale: f32,
pub region: [f32; 4],
pub png_bytes: usize,
pub document: Option<Value>,
}
pub fn region_px(region: &Region, ppp: f32, view: Option<egui::Rect>, w: u32, h: u32) -> Result<(u32, u32, u32, u32, [f32; 4]), String> {
let pts = match region {
Region::Named(n) if n == "full" => [0.0, 0.0, w as f32 / ppp, h as f32 / ppp],
Region::Named(n) if n == "viewport" => {
let r = view.ok_or("no viewport rect: the 3D view was not drawn last frame")?;
[r.min.x, r.min.y, r.width(), r.height()]
}
Region::Named(n) => return Err(format!("unknown region `{n}` (full | viewport | {{x,y,w,h}})")),
Region::Rect { x, y, w, h } => [*x, *y, *w, *h],
};
let px = |v: f32| (v * ppp).round().max(0.0) as u32;
let x0 = px(pts[0]).min(w.saturating_sub(1));
let y0 = px(pts[1]).min(h.saturating_sub(1));
let cw = px(pts[2]).clamp(1, w - x0);
let ch = px(pts[3]).clamp(1, h - y0);
Ok((x0, y0, cw, ch, pts))
}
pub fn encode_capture(image: &egui::ColorImage, ppp: f32, view: Option<egui::Rect>, region: &Region) -> Result<(Value, Vec<u8>), String> {
encode_capture_scaled(image, ppp, 1.0, view, region)
}
pub fn scaled_region_px(region: &Region, ppp: f32, scale: f32, view: Option<egui::Rect>, w: u32, h: u32) -> Result<(u32, u32, u32, u32, [f32; 4]), String> {
if scale == 1.0 {
return region_px(region, ppp, view, w, h);
}
let base = |v: u32| (v as f32 / scale).round().max(1.0) as u32;
let (x0, y0, cw, ch, pts) = region_px(region, ppp, view, base(w), base(h))?;
let px = |v: u32| (v as f32 * scale).round() as u32;
let (x0, y0) = (px(x0).min(w.saturating_sub(1)), px(y0).min(h.saturating_sub(1)));
Ok((x0, y0, px(cw).clamp(1, w - x0), px(ch).clamp(1, h - y0), pts))
}
pub fn encode_capture_scaled(image: &egui::ColorImage, ppp: f32, scale: f32, view: Option<egui::Rect>, region: &Region) -> Result<(Value, Vec<u8>), String> {
let (w, h) = (image.width() as u32, image.height() as u32);
let (x0, y0, cw, ch, pts) = scaled_region_px(region, ppp, scale, view, w, h)?;
let full = image::RgbaImage::from_raw(w, h, image.as_raw().to_vec()).ok_or("frame buffer size mismatch")?;
let cropped = image::imageops::crop_imm(&full, x0, y0, cw, ch).to_image();
let mut out = std::io::Cursor::new(Vec::new());
cropped.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("png encode: {e}"))?;
let png = out.into_inner();
let info = ScreenshotInfo { width: cw, height: ch, ppp: ppp * scale, scale, region: pts, png_bytes: png.len(), document: None };
Ok((serde_json::to_value(info).map_err(|e| e.to_string())?, png))
}
fn screenshot(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
let a: ScreenshotArgs = parse_args(args)?;
let queue = ctx.app.automation.clone();
let ppp = ctx.egui.pixels_per_point() / queue.pass_scale();
let size = ctx.egui.content_rect().size() * ppp;
let max_side = Some(ctx.egui.input(|i| i.max_texture_side) as u32);
let scale = capture_scale(&a, ppp, ctx.app.view_rect(), size.x.round() as u32, size.y.round() as u32, max_side)?;
let token = queue.next_token();
if scale == 1.0 {
ctx.egui.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(token)));
} else if !queue.request_scaled_capture(token, scale) {
return Err("unsupported: this host cannot render a scaled capture (scale, width and height are native desktop and headless only); capture at scale 1".into());
}
let document = Some(ctx.app.docs.view().handle().to_string());
Ok(Outcome::AwaitScreenshot { token, region: a.region, document, ppp, scale })
}
#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct IllustrationArgs {
pub action: String,
pub document_id: Option<u64>,
pub view: Option<Value>,
}
fn illustration_presentation(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
let a: IllustrationArgs = parse_args(args)?;
if let Some(id) = a.document_id {
let index = ctx.app.docs.iter().position(|d| d.id() == id).ok_or("illustration document is no longer open")?;
ctx.app.docs.activate(index);
}
let id = ctx.app.docs.active_id();
let engine = ctx.app.docs.engine_mut();
match a.action.as_str() {
"begin" => { engine.illustration_begin()?; Ok(Outcome::Done(json!({"document_id":id}))) },
"view" => engine.illustration_apply(&a.view.unwrap_or(json!({}))).map(Outcome::Done),
"end" => { engine.illustration_end()?; Ok(Outcome::Done(json!({"restored":true,"document_id":id}))) },
_ => Err("action must be begin, view or end".into()),
}
}
pub static COMMANDS: &[CommandSpec] = &[
app_command!("capture", "illustration_presentation", "Internal presentation loan for illustration_capture_many: preserves camera, full selection, display settings, saved-view state and display transforms without editing history or creating documents.", IllustrationArgs, illustration_presentation, Mutate, MUTATE_NOWAIT, schema_of::<Empty>),
app_command!("capture", "screenshot", "Capture the composited frame (egui chrome and the 3D view) as PNG: region `full` (default), `viewport`, or `{x,y,w,h}` in egui points. `scale` (or an exact `width` / `height` in pixels) renders it natively at that multiple of the window's density, with the same layout, camera, PMI and ViewCube positions, without resizing the window. The PNG rides beside the JSON reply.", ScreenshotArgs, screenshot, Mutate, READ, schema_of::<ScreenshotInfo>),
];
#[allow(dead_code)]
fn _unused(_: Value) -> Value {
json!({})
}