mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-27 17:01:38 +01:00
M8: asset handoff for code projects
file.exportAssets and the MCP tool export_assets write a design's images and vectors into a folder: images as the bytes the file holds, never re-encoded, vectors through the SVG export, and layers with export settings by those settings. Each file says whether it is original, vector or rendered. Files are named by the first 16 hex digits of their SHA-256, so one asset has one file used by every layer listed and exporting again writes nothing. What a layer does to an image that isn't in its bytes (filters, crop, rotation, opacity) is listed, as is why an asset couldn't be handed over. Writes go through file_access, so automation roots confine them.
This commit is contained in:
1 parent
6cc578cede
commit
d09c82010d
11 files changed
+515
-1
No files matched your search
@@ -369,6 +369,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
|
||||
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
|
||||
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
|
||||
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
|
||||
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! `file.exportAssets`: originals stay byte for byte, names come from content, exports repeat cleanly.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::file_access::{Roots, confined};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-assets-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
/// An image file in `format`, with a little metadata re-encoding would lose: `seed` varies it.
|
||||
fn image_bytes(format: image::ImageFormat, seed: u8) -> Vec<u8> {
|
||||
let img = image::RgbImage::from_fn(16, 8, |x, y| image::Rgb([x as u8 * 16, y as u8 * 32, seed]));
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn place(s: &mut Session, bytes: &[u8]) -> u64 {
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
s.execute("image.place", &json!({"data": data})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn assets(v: &Value) -> &Vec<Value> {
|
||||
v["assets"].as_array().unwrap()
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, params: Value) -> Value {
|
||||
s.execute("file.exportAssets", ¶ms).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_are_the_files_own_bytes_named_by_their_content() {
|
||||
let (mut s, dir) = (session(), folder("original"));
|
||||
for format in [image::ImageFormat::Png, image::ImageFormat::Jpeg] {
|
||||
let bytes = image_bytes(format, 7);
|
||||
let id = place(&mut s, &bytes);
|
||||
let v = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
let a = &assets(&v)[0];
|
||||
assert_eq!(a["source"], "original");
|
||||
let hash = figcraft_format::image_hash(&bytes);
|
||||
assert!(a["file"].as_str().unwrap().starts_with(&hash[..16]), "{a}");
|
||||
assert_eq!(std::fs::read(a["path"].as_str().unwrap()).unwrap(), bytes, "not re-encoded");
|
||||
assert_eq!((a["width"].as_u64(), a["height"].as_u64()), (Some(16), Some(8)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_image_twice_is_one_file_listing_both_layers() {
|
||||
let (mut s, dir) = (session(), folder("dedupe"));
|
||||
let bytes = image_bytes(image::ImageFormat::Png, 1);
|
||||
let (a, b) = (place(&mut s, &bytes), place(&mut s, &bytes));
|
||||
let v = export(&mut s, json!({"ids": [a, b], "dir": dir}));
|
||||
assert_eq!(assets(&v).len(), 1);
|
||||
assert_eq!(assets(&v)[0]["layers"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(v["written"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporting_again_writes_nothing_and_names_dont_move() {
|
||||
let (mut s, dir) = (session(), folder("again"));
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 2));
|
||||
let first = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
let path = assets(&first)[0]["path"].as_str().unwrap().to_string();
|
||||
let when = std::fs::metadata(&path).unwrap().modified().unwrap();
|
||||
let second = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
assert_eq!((second["written"].as_u64(), second["reused"].as_u64()), (Some(0), Some(1)));
|
||||
assert_eq!(assets(&second)[0]["file"], assets(&first)[0]["file"]);
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), when);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_file_at_the_name_is_put_right() {
|
||||
let (mut s, dir) = (session(), folder("damaged"));
|
||||
let bytes = image_bytes(image::ImageFormat::Png, 3);
|
||||
let id = place(&mut s, &bytes);
|
||||
let v = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
let path = assets(&v)[0]["path"].as_str().unwrap().to_string();
|
||||
std::fs::write(&path, vec![0u8; bytes.len()]).unwrap();
|
||||
assert_eq!(export(&mut s, json!({"ids": [id], "dir": dir}))["written"], 1);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_writes_nothing() {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 4));
|
||||
let v = export(&mut s, json!({"ids": [id]}));
|
||||
assert_eq!(assets(&v).len(), 1);
|
||||
assert!(assets(&v)[0].get("path").is_none() && v.get("written").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vector_is_svg_and_says_so() {
|
||||
let (mut s, dir) = (session(), folder("vector"));
|
||||
let id =
|
||||
s.execute("node.create", &json!({"type": "star", "width": 24, "height": 24, "props": {"fill": "#112233"}})).unwrap()["id"].as_u64().unwrap();
|
||||
let v = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
let a = &assets(&v)[0];
|
||||
assert_eq!((a["source"].as_str(), a["format"].as_str()), (Some("vector"), Some("svg")));
|
||||
assert!(std::fs::read_to_string(a["path"].as_str().unwrap()).unwrap().contains("<svg"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layers_export_settings_are_a_render_and_its_image_stays_original() {
|
||||
let (mut s, dir) = (session(), folder("settings"));
|
||||
let bytes = image_bytes(image::ImageFormat::Png, 5);
|
||||
let id = place(&mut s, &bytes);
|
||||
s.execute("export.add", &json!({"ids": [id]})).unwrap();
|
||||
let v = export(&mut s, json!({"ids": [id], "dir": dir}));
|
||||
let sources: Vec<&str> = assets(&v).iter().map(|a| a["source"].as_str().unwrap()).collect();
|
||||
assert!(sources.contains(&"original") && sources.contains(&"rendered"), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_layer_does_to_its_image_is_listed() {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 6));
|
||||
s.execute("image.adjust", &json!({"ids": [id], "preset": "vivid"})).unwrap();
|
||||
let v = export(&mut s, json!({"ids": [id]}));
|
||||
assert!(assets(&v)[0]["adjustments"][0]["changes"]["filters"].is_object(), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_the_file_lacks_is_skipped_with_a_reason() {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 8));
|
||||
let doc = s.doc_mut().unwrap();
|
||||
let key = doc.images.keys().next().unwrap().clone();
|
||||
doc.images.insert(key, figcraft_doc::ImageData { bytes: Arc::new(vec![]), width: 0, height: 0 });
|
||||
let v = export(&mut s, json!({"ids": [id]}));
|
||||
assert!(assets(&v).is_empty());
|
||||
assert_eq!(v["skipped"][0]["id"], id);
|
||||
assert!(v["skipped"][0]["why"].as_str().unwrap().contains("doesn't hold"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_layers_stay_out() {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 9));
|
||||
s.execute("node.set", &json!({"ids": [id], "props": {"visible": false}})).unwrap();
|
||||
assert!(assets(&export(&mut s, json!({"ids": [id]}))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_written_outside_the_project() {
|
||||
let (mut s, inside, outside) = (session(), folder("inside"), folder("outside"));
|
||||
let id = place(&mut s, &image_bytes(image::ImageFormat::Png, 10));
|
||||
let roots = Arc::new(Roots::new(&[], &[inside.to_string_lossy().into_owned()]).unwrap());
|
||||
let refused = confined(Some(&roots), || s.execute("file.exportAssets", &json!({"ids": [id], "dir": outside})));
|
||||
assert!(refused.unwrap_err().to_string().contains("automation path rejected"));
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&outside, inside.join("out")).unwrap();
|
||||
assert!(confined(Some(&roots), || s.execute("file.exportAssets", &json!({"ids": [id], "dir": inside.join("out/deep")}))).is_err());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
}
|
||||
let ok = confined(Some(&roots), || s.execute("file.exportAssets", &json!({"ids": [id], "dir": inside.join("public/figcraft")})));
|
||||
assert_eq!(ok.unwrap()["written"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_is_refused_without_a_panic() {
|
||||
let mut s = session();
|
||||
for p in [json!({"dir": ""}), json!({"dir": " "}), json!({"dir": 3})] {
|
||||
assert!(s.execute("file.exportAssets", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(assets(&export(&mut s, json!({}))).is_empty());
|
||||
}
|
||||
@@ -101,6 +101,7 @@ fn registry() -> &'static Registry {
|
||||
list.extend(crate::codegen::specs());
|
||||
list.extend(crate::devinspect::specs());
|
||||
list.extend(crate::design_context::specs());
|
||||
list.extend(crate::asset_handoff::specs());
|
||||
list.extend(crate::component_codegen::specs());
|
||||
list.extend(crate::playground::specs());
|
||||
list.extend(crate::code_connect::specs());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod annotations;
|
||||
pub mod asset_handoff;
|
||||
pub mod code_connect;
|
||||
pub mod codegen;
|
||||
pub mod component_codegen;
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Asset handoff: the files a design's images and vectors become in a code project
|
||||
//! (`file.exportAssets`, the MCP tool `export_assets`). An image is written as the bytes the file
|
||||
//! holds, never re-encoded; a vector goes through the SVG export and a layer with export settings
|
||||
//! through those settings. Names come from the content, so the same asset always has the same file
|
||||
//! and a second export writes nothing. A result says of every file what it is (`source`), so an
|
||||
//! agent never takes a render for an original.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_color::{Paint, PaintKind};
|
||||
use figcraft_doc::{Document, ExportFormat, NodeId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::CommandSpec;
|
||||
use crate::cmd::file::{export_file, export_scale};
|
||||
use crate::devinspect::{Asset, AssetKind, MAX_ASSETS, assets};
|
||||
use crate::file_access;
|
||||
use crate::params::{get, targets};
|
||||
use crate::{Result, Session, bad, spec};
|
||||
|
||||
/// How much of the content hash names a file: 64 bits, far past a project's assets.
|
||||
const NAME_HEX: usize = 16;
|
||||
/// The largest file a repeated export reads back to compare, beyond the images a document holds.
|
||||
const MAX_COMPARE: u64 = 1 << 31;
|
||||
|
||||
/// A file to hand over.
|
||||
struct File {
|
||||
/// `<content hash>.<extension>`.
|
||||
name: String,
|
||||
hash: String,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
/// `original`: the file's own bytes. `vector`: written from its shapes. `rendered`: pixels.
|
||||
source: &'static str,
|
||||
format: String,
|
||||
size: Option<(u32, u32)>,
|
||||
/// The layers that use it.
|
||||
layers: Vec<Value>,
|
||||
/// What a layer does to the image that isn't in its bytes.
|
||||
adjustments: Vec<Value>,
|
||||
}
|
||||
|
||||
/// The extension encoded image `bytes` go by, from their signature.
|
||||
fn image_kind(b: &[u8]) -> Option<&'static str> {
|
||||
match b {
|
||||
[0x89, b'P', b'N', b'G', ..] => Some("png"),
|
||||
[0xFF, 0xD8, ..] => Some("jpg"),
|
||||
[b'G', b'I', b'F', ..] => Some("gif"),
|
||||
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => Some("webp"),
|
||||
[b'I', b'I', 42, 0, ..] | [b'M', b'M', 0, 42, ..] => Some("tiff"),
|
||||
[b'B', b'M', ..] => Some("bmp"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What paint `p` of a layer changes about its image, beyond the original's bytes.
|
||||
fn adjustments(p: &Paint) -> Option<Value> {
|
||||
let PaintKind::Image(i) = &p.kind else { return None };
|
||||
let mut changed = serde_json::Map::new();
|
||||
if i.filters != figcraft_color::ImageFilters::default() {
|
||||
changed.insert("filters".into(), serde_json::to_value(i.filters).unwrap_or(Value::Null));
|
||||
}
|
||||
if let Some(crop) = i.crop {
|
||||
changed.insert("crop".into(), json!(crop));
|
||||
}
|
||||
if i.rotation != 0 {
|
||||
changed.insert("rotation".into(), json!(i.rotation * 90));
|
||||
}
|
||||
if p.opacity < 1.0 {
|
||||
changed.insert("opacity".into(), json!(p.opacity));
|
||||
}
|
||||
(!changed.is_empty()).then_some(Value::Object(changed))
|
||||
}
|
||||
|
||||
/// Adds a file, or the layer to the file it is already.
|
||||
fn add(files: &mut BTreeMap<String, File>, mut file: File) {
|
||||
match files.get_mut(&file.name) {
|
||||
Some(known) => {
|
||||
known.layers.append(&mut file.layers);
|
||||
known.adjustments.append(&mut file.adjustments);
|
||||
}
|
||||
None => {
|
||||
files.insert(file.name.clone(), file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The image paints of layer `id`: their original bytes, or why one can't be handed over.
|
||||
fn image_files(doc: &Document, id: NodeId, files: &mut BTreeMap<String, File>, skipped: &mut Vec<Value>) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
for p in n.fills.iter().chain(&n.strokes).filter(|p| p.visible) {
|
||||
let PaintKind::Image(paint) = &p.kind else { continue };
|
||||
let refuse = |why: &str| json!({"id": id, "name": n.name, "image": paint.image, "why": why});
|
||||
let Some(data) = doc.images.get(&paint.image).filter(|d| !d.bytes.is_empty()) else {
|
||||
skipped.push(refuse("the file doesn't hold this image"));
|
||||
continue;
|
||||
};
|
||||
let Some(ext) = image_kind(&data.bytes) else {
|
||||
skipped.push(refuse("not an image format a project can use as it is"));
|
||||
continue;
|
||||
};
|
||||
let hash = figcraft_format::image_hash(&data.bytes);
|
||||
let name = format!("{}.{ext}", hash.get(..NAME_HEX).unwrap_or(&hash));
|
||||
let adjusted = adjustments(p).map(|changes| json!({"id": id, "changes": changes}));
|
||||
let file = File {
|
||||
name,
|
||||
hash,
|
||||
bytes: data.bytes.clone(),
|
||||
source: "original",
|
||||
format: ext.to_string(),
|
||||
size: Some((data.width, data.height)),
|
||||
layers: vec![json!({"id": id, "name": n.name})],
|
||||
adjustments: adjusted.into_iter().collect(),
|
||||
};
|
||||
add(files, file);
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the assets in and under `ids` make, and what can't be handed over.
|
||||
fn collect(doc: &Document, listed: &[Asset]) -> (BTreeMap<String, File>, Vec<Value>) {
|
||||
let mut files = BTreeMap::new();
|
||||
let mut skipped = Vec::new();
|
||||
for asset in listed {
|
||||
// A layer's export settings say how it renders; its images stay available as they are.
|
||||
image_files(doc, asset.id, &mut files, &mut skipped);
|
||||
if asset.kind == AssetKind::Image {
|
||||
continue;
|
||||
}
|
||||
let name = doc.node(asset.id).map(|n| n.name.clone()).unwrap_or_default();
|
||||
for setting in &asset.settings {
|
||||
let scale = export_scale(doc, &[asset.id], setting);
|
||||
let bytes = match export_file(doc, &[asset.id], setting, scale) {
|
||||
Ok((bytes, _)) => bytes,
|
||||
Err(e) => {
|
||||
skipped.push(json!({"id": asset.id, "name": name, "why": e.to_string()}));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let hash = figcraft_format::image_hash(&bytes);
|
||||
let vector = matches!(setting.format, ExportFormat::Svg);
|
||||
let file = File {
|
||||
name: format!("{}.{}", hash.get(..NAME_HEX).unwrap_or(&hash), setting.format.ext()),
|
||||
hash,
|
||||
bytes: Arc::new(bytes),
|
||||
source: if vector { "vector" } else { "rendered" },
|
||||
format: setting.format.ext().to_string(),
|
||||
size: None,
|
||||
layers: vec![json!({"id": asset.id, "name": name})],
|
||||
adjustments: vec![],
|
||||
};
|
||||
add(&mut files, file);
|
||||
}
|
||||
}
|
||||
(files, skipped)
|
||||
}
|
||||
|
||||
/// Whether `path` already holds exactly `file`.
|
||||
fn already_there(path: &std::path::Path, file: &File) -> bool {
|
||||
file_access::metadata(path).is_ok_and(|m| m.len() == file.bytes.len() as u64)
|
||||
&& file_access::read_capped(path, MAX_COMPARE).is_ok_and(|bytes| bytes == *file.bytes)
|
||||
}
|
||||
|
||||
fn export_assets(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.exportAssets";
|
||||
let dir = match get(p, "dir") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(d)) if !d.trim().is_empty() => Some(d.clone()),
|
||||
Some(_) => return Err(bad(cmd, "dir: a folder")),
|
||||
};
|
||||
let doc = s.doc()?;
|
||||
let mut ids = targets(s, p);
|
||||
if ids.is_empty() {
|
||||
ids = vec![s.page()?];
|
||||
}
|
||||
let found = assets(doc, &ids);
|
||||
let (files, skipped) = collect(doc, &found);
|
||||
let mut listed = Vec::with_capacity(files.len());
|
||||
let (mut written, mut reused) = (0usize, 0usize);
|
||||
for file in files.values() {
|
||||
let mut entry = json!({
|
||||
"file": file.name,
|
||||
"hash": file.hash,
|
||||
"source": file.source,
|
||||
"format": file.format,
|
||||
"bytes": file.bytes.len(),
|
||||
"layers": file.layers,
|
||||
});
|
||||
if let Some((w, h)) = file.size {
|
||||
entry["width"] = json!(w);
|
||||
entry["height"] = json!(h);
|
||||
}
|
||||
if !file.adjustments.is_empty() {
|
||||
entry["adjustments"] = json!(file.adjustments);
|
||||
}
|
||||
if let Some(d) = &dir {
|
||||
let path = std::path::Path::new(d).join(&file.name);
|
||||
if already_there(&path, file) {
|
||||
reused += 1;
|
||||
} else {
|
||||
file_access::create_dir_all(d)?;
|
||||
file_access::write(&path, &file.bytes)?;
|
||||
written += 1;
|
||||
}
|
||||
entry["path"] = json!(path.to_string_lossy());
|
||||
}
|
||||
listed.push(entry);
|
||||
}
|
||||
let mut out = json!({"assets": listed, "skipped": skipped});
|
||||
if found.len() >= MAX_ASSETS {
|
||||
out["truncated"] = json!({"maxAssets": MAX_ASSETS, "hint": "call again with the ids of the parts you need"});
|
||||
}
|
||||
if let Some(d) = &dir {
|
||||
out["dir"] = json!(d);
|
||||
out["written"] = json!(written);
|
||||
out["reused"] = json!(reused);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![spec!(
|
||||
"file.exportAssets",
|
||||
"Export assets",
|
||||
"{ids? (default the selection, else the page), dir? (write them there; without it they are only listed)} the images and vectors in and under the layers as files named by their content: images as the file's original bytes, vectors as SVG, layers with export settings by those settings. A file already there isn't written again → {assets: [{file, hash, source: original|vector|rendered, format, bytes, width?, height?, layers, adjustments?, path?}], skipped: [{id, name, why}], dir?, written?, reused?, truncated?}",
|
||||
false,
|
||||
export_assets
|
||||
)]
|
||||
}
|
||||
@@ -59,7 +59,7 @@ pub struct Asset {
|
||||
}
|
||||
|
||||
/// Most assets listed for one selection.
|
||||
const MAX_ASSETS: usize = 200;
|
||||
pub const MAX_ASSETS: usize = 200;
|
||||
/// Largest side of a layer listed as an icon.
|
||||
const ICON_MAX: f64 = 128.0;
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ pub use content::synthetic_ds;
|
||||
pub use content::templates;
|
||||
pub use content::textfit;
|
||||
pub use dev::annotations;
|
||||
pub use dev::asset_handoff;
|
||||
pub use dev::code_connect;
|
||||
pub use dev::codegen;
|
||||
pub use dev::component_codegen;
|
||||
@@ -195,6 +196,8 @@ mod arc_fields_tests;
|
||||
#[cfg(test)]
|
||||
mod arc_handles_tests;
|
||||
#[cfg(test)]
|
||||
mod asset_handoff_tests;
|
||||
#[cfg(test)]
|
||||
mod auto_layout_move_tests;
|
||||
#[cfg(test)]
|
||||
mod autosave_tests;
|
||||
|
||||
@@ -101,6 +101,7 @@ pub const TOOL_NAMES: &[&str] = &[
|
||||
"inspect_document",
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -124,6 +125,7 @@ const DOCUMENT_TOOLS: &[&str] = &[
|
||||
"inspect_document",
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -270,6 +272,20 @@ fn tools() -> Vec<Value> {
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"export_assets",
|
||||
"Export assets",
|
||||
"Write the selection's images and vectors into `dir` (relative to where this server runs) as files named by their content, and say where they went. Images are the file's original bytes, never re-encoded; each result says if it is `original`, `vector` or `rendered`, and lists `adjustments` a layer applies that aren't in the file. Exporting again writes nothing new. `dryRun` lists them without writing.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": ids_schema("Layers (default the selection, else the page)"),
|
||||
"dir": string("Folder to write to, absolute or relative to where this server runs (required unless dryRun)"),
|
||||
"dryRun": boolean("List the files without writing them")
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"select",
|
||||
"Select layers",
|
||||
@@ -456,6 +472,24 @@ fn design_context(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolRes
|
||||
}
|
||||
}
|
||||
|
||||
/// `file.exportAssets` into `dir`, made absolute here: an attached app runs in another folder.
|
||||
fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let mut params = Map::new();
|
||||
if let Some(ids) = a.get("ids") {
|
||||
params.insert("ids".into(), ids.clone());
|
||||
}
|
||||
let dry = a.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
|
||||
match (s_arg(a, "dir")?, dry) {
|
||||
(Some(dir), false) => {
|
||||
let dir = std::path::absolute(dir).map_err(|e| format!("dir: {e}"))?;
|
||||
params.insert("dir".into(), json!(dir.to_string_lossy()));
|
||||
}
|
||||
(None, false) => return Err("pass `dir`, the folder to write to, or `dryRun` to list the assets".into()),
|
||||
_ => {}
|
||||
}
|
||||
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
fn wait_for_changes(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
b.call("events.poll", Value::Object(a.clone())).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
@@ -602,6 +636,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
"inspect_document" => inspect_document(b, &a),
|
||||
"get_node" => get_node(b, &a),
|
||||
"design_context" => design_context(b, &a),
|
||||
"export_assets" => export_assets(b, &a),
|
||||
"select" => select(b, &a),
|
||||
"export" => export(b, &a),
|
||||
"screenshot" => screenshot(b, &a),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `export_assets`: the original bytes land in the folder asked for, and nothing is written without one.
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::Client;
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let img = image::RgbImage::from_fn(8, 4, |x, y| image::Rgb([x as u8 * 30, y as u8 * 60, 7]));
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-mcp-assets-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn originals_are_written_where_asked_and_listed_without_a_folder() {
|
||||
let mut c = Client::new();
|
||||
let bytes = png();
|
||||
let placed = c.ok("run_command", json!({"command": "image.place", "params": {"data": base64::engine::general_purpose::STANDARD.encode(&bytes)}}));
|
||||
let id = placed["id"].clone();
|
||||
let listed = c.ok("export_assets", json!({"ids": [id], "dryRun": true}));
|
||||
assert_eq!(listed["assets"][0]["source"], "original");
|
||||
assert!(listed["assets"][0].get("path").is_none(), "a dry run writes nothing");
|
||||
let refused = c.call("export_assets", json!({"ids": [id]}));
|
||||
assert_eq!(refused["isError"], true, "no folder, no write: {refused}");
|
||||
let dir = folder("written");
|
||||
let done = c.ok("export_assets", json!({"ids": [id], "dir": dir}));
|
||||
let path = done["assets"][0]["path"].as_str().unwrap().to_string();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "byte for byte");
|
||||
assert_eq!(c.ok("export_assets", json!({"ids": [id], "dir": dir}))["written"], 0, "nothing new the second time");
|
||||
}
|
||||
@@ -11,6 +11,8 @@ mod automation_roots;
|
||||
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod common;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod export_assets;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod export_hidden_roots;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod export_profile;
|
||||
|
||||
+22
@@ -409,6 +409,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
|
||||
| `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). |
|
||||
| `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. |
|
||||
| `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). |
|
||||
| `export_assets {ids?, dir?, dryRun?}` | Write the selection's images and vectors into `dir` as files named by their content: see [Asset handoff](#asset-handoff). |
|
||||
| `select {ids}` | Replace the selection (`[]` deselects). |
|
||||
| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?, quality?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`; `quality` is the JPG quality, 1 to 100 (default 90). The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps `<text>`, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (PNG: `sRGB` chunk, or ICC and `cICP` for Display P3; JPG: ICC profile; WebP: ICC profile for Display P3, none for sRGB) (SVG, XML and RGB PDF output are always sRGB; PDF with `cmyk` is DeviceCMYK). The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `<layer><suffix>.<format>`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). |
|
||||
| `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. |
|
||||
@@ -455,6 +456,27 @@ Each layer in `nodes` has `id`, `name`, `type` and:
|
||||
Values are the file's own. Nothing is converted to CSS or guessed. Hidden layers are in the tree, with
|
||||
`visible: false` in `explicit`.
|
||||
|
||||
### Asset handoff
|
||||
|
||||
`export_assets` (the command `file.exportAssets`) hands a design's assets to a code project. It writes
|
||||
to `dir`, absolute or relative to where the MCP server runs, and only lists them with `dryRun`. The
|
||||
files the call writes are confined like any other (see Confining file access).
|
||||
|
||||
- **Images** are the bytes the file holds, never re-encoded: `source: "original"`.
|
||||
- **Vectors** go through the SVG export: `source: "vector"`.
|
||||
- **Layers with export settings** go through those settings: `source: "rendered"`, or `vector` for
|
||||
SVG. Their images are listed as originals too.
|
||||
|
||||
Each file is named `<first 16 hex digits of its SHA-256>.<extension>`, so one asset has one file, used
|
||||
by every layer in `layers`. Exporting again rewrites nothing unless the file there differs
|
||||
(`written`, `reused`). `adjustments` lists what a layer does that isn't in the image's bytes (filters,
|
||||
crop, rotation, opacity), which code has to apply. `skipped` says why an asset couldn't be handed over,
|
||||
and hidden layers stay out. It reads what `inspect.assets` finds, up to 200 layers per call
|
||||
(`truncated` says so).
|
||||
|
||||
Fonts are never exported. The file holds only family and style names, and `design_context` lists them
|
||||
under `fonts`. Their licences are for the project to check.
|
||||
|
||||
### Compact layer trees
|
||||
|
||||
`inspect_document` and `get_node` accept `fields`, an array of exact, case-sensitive top-level node
|
||||
|
||||
Reference in new issue
Block a user