Merge pull request #2607 from Utakata/feat/open-camera-raw

format: open camera raw files as their developed picture
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 15:06:51 +07:00
commit dbe9eeb1bd
16 files changed
+662 -16

No files matched your search

Generated
+309 -5
View File
@@ -138,19 +138,34 @@ dependencies = [
"memchr",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
"alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -667,14 +682,24 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
]
[[package]]
@@ -1195,11 +1220,46 @@ dependencies = [
"egui",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"md-5",
"rayon",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"serde",
]
[[package]]
name = "craft-color-transform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-cms",
"craft-color",
"serde",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
@@ -1208,6 +1268,33 @@ dependencies = [
"rayon",
]
[[package]]
name = "craft-develop"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-color",
"craft-color-transform",
"craft-develop-model",
"craft-geom",
"craft-raw",
"rayon",
"serde",
"serde_json",
]
[[package]]
name = "craft-develop-model"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-geom",
"craft-metadata",
"miniz_oxide 0.9.1",
"serde",
"serde_json",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
@@ -1305,6 +1392,14 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
[[package]]
name = "craft-geom"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"serde",
]
[[package]]
name = "craft-gif"
version = "0.1.0"
@@ -1433,7 +1528,7 @@ name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
@@ -1505,6 +1600,24 @@ dependencies = [
"web-sys",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"chrono",
"craft-crw",
"craft-metadata",
"craft-tiff",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
"serde",
"thiserror 2.0.21",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "craft-settings"
version = "0.1.0"
@@ -2643,6 +2756,7 @@ dependencies = [
"craft-docpath",
"craft-font-catalog",
"craft-font-store",
"craft-raw",
"deunicode",
"figcraft-collab",
"figcraft-color",
@@ -2673,12 +2787,16 @@ dependencies = [
name = "figcraft-format"
version = "0.18.1"
dependencies = [
"craft-color-transform",
"craft-develop",
"craft-fig",
"craft-figcraft-format",
"craft-figma-rest",
"craft-geom",
"craft-image-codecs",
"craft-jpeg",
"craft-penpot",
"craft-raw",
"craft-sketch",
"craft-zip",
"figcraft-doc",
@@ -4101,6 +4219,182 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jxl-bitstream"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-coding"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
dependencies = [
"jxl-bitstream",
"tracing",
]
[[package]]
name = "jxl-color"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-frame"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-grid"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-image"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
dependencies = [
"jxl-bitstream",
"jxl-grid",
"jxl-oxide-common",
"tracing",
]
[[package]]
name = "jxl-jbr"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-modular"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-jbr",
"jxl-oxide-common",
"jxl-render",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide-common"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
dependencies = [
"jxl-bitstream",
]
[[package]]
name = "jxl-render"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
dependencies = [
"bytemuck",
"jxl-bitstream",
"jxl-coding",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-threadpool"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-vardct"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -4335,6 +4629,16 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest 0.10.7",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -8085,7 +8389,7 @@ version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 6.3.2",
"bytes",
]
+6
View File
@@ -76,6 +76,12 @@ craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev =
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Camera raw files (craft-libs): the container decoders, and the shared develop stages that turn
# sensor data into a picture (demosaic, white balance, colour matrices, tone).
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["frames"] }
# foundation
+2 -1
View File
@@ -14,7 +14,8 @@ use figcraft_doc::{PrintSettings, VdCompat};
///
/// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig
/// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort),
/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer).
/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2,
/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer).
#[derive(Parser)]
#[command(
name = "figcraft-cli",
+2
View File
@@ -43,3 +43,5 @@ craft-font-catalog = { workspace = true }
zip = { workspace = true }
wat = { workspace = true }
image = { workspace = true }
# Writes the DNG files the camera raw tests open.
craft-raw = { workspace = true }
+1 -1
View File
@@ -124,7 +124,7 @@ fn load_any(
font_notes.append(&mut notes); // Show missing-font details first in the UI toast.
Ok((figcraft_format::Loaded { issues: font_notes, ..doc.into() }, true))
}
"png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" => {
e if matches!(e, "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff") || figcraft_format::raw::is_extension(e) => {
let mut doc = Document::new(file_stem(name_hint));
let page = doc.first_page().ok_or(EngineError::NoDocument)?;
let (hash, w, h) = crate::cmd::create::add_readable_image(&mut doc, bytes.to_vec()).map_err(EngineError::Other)?;
+2
View File
@@ -562,6 +562,8 @@ mod proto_run_tests;
#[cfg(test)]
mod proto_tail_tests;
#[cfg(test)]
mod raw_tests;
#[cfg(test)]
mod reopen_tests;
#[cfg(test)]
mod responsive_tests;
+138
View File
@@ -0,0 +1,138 @@
//! Camera raw files open, import and place as the picture they develop to; damaged ones are
//! errors. The raw files are DNGs written here from synthetic sensor data (craft-raw's writer).
use base64::Engine as _;
use craft_raw::opcodes::OpcodeLists;
use craft_raw::{BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Orientation, RawData, RawFormat, RawImage, Rect};
use serde_json::json;
use crate::Session;
/// Sensor columns a band of the scene covers.
const BAND: usize = 22;
const BLACK: f32 = 64.0;
const WHITE: f32 = 4095.0;
/// The camera's response to a neutral (`AsShotNeutral`): white balance multiplies red by 2 and blue by 1/0.7.
const NEUTRAL: [f64; 3] = [0.5, 1.0, 0.7];
/// A 3 × 22 by 48 RGGB raw, turned a quarter (Exif orientation 6), whose camera RGB is linear sRGB.
/// Its sensor columns hold three bands: a red, a mid grey, and a light that clips every channel.
fn dng() -> Vec<u8> {
let (w, h) = (3 * BAND, 48);
let cfa = Cfa::bayer("RGGB").unwrap();
let scene = |x: usize| match x / BAND {
0 => [0.40, 0.08, 0.06],
1 => [0.18, 0.18, 0.18],
_ => [4.0, 4.0, 4.0],
};
let data = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
let c = cfa.color_at(x, y) as usize;
let level = (scene(x)[c] * NEUTRAL[c] as f32).clamp(0.0, 1.0);
(BLACK + (WHITE - BLACK) * level).round() as u16
})
.collect();
// XYZ (D65) → linear sRGB (IEC 61966-2-1): this camera sees in sRGB primaries.
let xyz_to_camera = [[3.2404542, -1.5371385, -0.4985314], [-0.9692660, 1.8760108, 0.0415560], [0.0556434, -0.2040259, 1.0572252]];
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16(data),
cfa: Some(cfa),
bits: 12,
black: BlackLevel::uniform(BLACK),
white: vec![WHITE],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Rotate90,
color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_camera), None], as_shot_neutral: Some(NEUTRAL), ..Default::default() },
wb_multipliers: None,
linearized: true,
linearization_table: None,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
camera: Default::default(),
cinema: Default::default(),
lens_metadata: Default::default(),
level_sources: Default::default(),
notices: Default::default(),
};
let opts = DngWriteOptions { compression: DngCompression::Uncompressed, software: "figcraft tests".into(), ..Default::default() };
craft_raw::write_dng(&raw, &opts).unwrap()
}
fn import(s: &mut Session, bytes: &[u8], name: &str) -> crate::Result<serde_json::Value> {
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
s.execute("file.import", &json!({"data": b64, "name": name, "x": 0, "y": 0}))
}
/// The mean colour of the 5 × 5 pixels around (`x`, `y`) of the layer's image.
fn colour_at(s: &Session, id: figcraft_doc::NodeId, x: u32, y: u32) -> [i32; 3] {
let doc = s.doc().unwrap();
let hash = match &doc.node(id).unwrap().fills[0].kind {
figcraft_color::PaintKind::Image(paint) => paint.image.clone(),
other => panic!("not an image fill: {other:?}"),
};
let picture = image::load_from_memory(&doc.images[&hash].bytes).unwrap().to_rgb8();
let mut sum = [0i32; 3];
for dy in 0..5 {
for dx in 0..5 {
let p = picture.get_pixel(x + dx - 2, y + dy - 2);
for c in 0..3 {
sum[c] += i32::from(p[c]);
}
}
}
sum.map(|v| v / 25)
}
fn spread(c: [i32; 3]) -> i32 {
c.iter().max().unwrap() - c.iter().min().unwrap()
}
#[test]
fn camera_raw_files_import_and_open_as_their_developed_picture() {
let bytes = dng();
let mut s = Session::new();
let out = import(&mut s, &bytes, "shot.dng").unwrap();
let id = crate::params::id_of(&out["id"]).unwrap();
let n = s.doc().unwrap().node(id).unwrap();
// The orientation tag is applied: the sensor's columns run down the picture.
assert!(n.height > n.width, "{} x {}", n.width, n.height);
let x = n.width as u32 / 2;
let band = BAND as u32;
let (red, grey, light) = (colour_at(&s, id, x, band / 2), colour_at(&s, id, x, band * 3 / 2), colour_at(&s, id, x, band * 5 / 2));
// White balance and the colour matrix give back the scene: red stays red, grey stays neutral.
assert!(red[0] > red[1] + 60 && red[0] > red[2] + 60, "red band: {red:?}");
assert!(spread(grey) <= 8, "grey band: {grey:?}");
// Clipped channels are rebuilt: white balance alone would turn the clipped light magenta.
assert!(light.iter().all(|&c| c > grey[1]) && spread(light) <= 8, "clipped band: {light:?}, grey {grey:?}");
let path = std::env::temp_dir().join(format!("figcraft-raw-{}.dng", std::process::id()));
std::fs::write(&path, &bytes).unwrap();
let opened = s.execute("file.open", &json!({"path": path.to_string_lossy()}));
let _ = std::fs::remove_file(&path);
opened.unwrap();
assert_eq!(s.doc().unwrap().images.len(), 1);
}
#[test]
fn damaged_camera_raw_files_are_errors() {
let mut s = Session::new();
// A Panasonic RW2 header over junk: refused, saying why.
let mut junk = b"IIU\0\x08\0\0\0".to_vec();
junk.extend(std::iter::repeat_n(0x5a, 4096));
let err = import(&mut s, &junk, "shot.rw2").unwrap_err().to_string();
assert!(err.contains("camera raw"), "{err}");
// Cut short anywhere: refused or placed, never a panic, and the renderer copes with what was placed.
let bytes = dng();
for len in [12, 200, bytes.len() / 3, bytes.len() - 100] {
if let Ok(out) = import(&mut s, &bytes[..len], "shot.dng") {
let id = crate::params::id_of(&out["id"]).unwrap();
assert!(s.doc().unwrap().node(id).is_some());
}
}
}
+4
View File
@@ -28,3 +28,7 @@ craft-figcraft-format = { workspace = true }
craft-figma-rest = { workspace = true }
craft-jpeg = { workspace = true }
craft-image-codecs = { workspace = true }
craft-raw = { workspace = true }
craft-develop = { workspace = true }
craft-color-transform = { workspace = true }
craft-geom = { workspace = true }
+18 -1
View File
@@ -21,6 +21,7 @@ pub mod fig;
pub mod jpeg;
pub mod library;
pub mod penpot;
pub mod raw;
pub mod rest;
pub mod sketch;
pub mod thumbnail;
@@ -174,14 +175,30 @@ fn stored_dimensions(bytes: &[u8]) -> Result<(u32, u32), craft_image_codecs::Cod
}
}
/// Register encoded image bytes with the document; returns the hash and pixel size.
/// Register encoded image bytes with the document; returns the hash and pixel size. A camera raw
/// file is developed first and the document keeps the developed picture (see [`raw`]).
pub fn add_image(doc: &mut Document, bytes: Vec<u8>) -> Result<(String, u32, u32), FormatError> {
let bytes = developed_if_raw(bytes)?;
let (w, h) = stored_dimensions(&bytes).map_err(|e| FormatError::Corrupt(format!("unsupported image: {e}")))?;
let hash = image_hash(&bytes);
doc.images.insert(hash.clone(), ImageData { bytes: Arc::new(bytes), width: w, height: h });
Ok((hash, w, h))
}
/// `bytes`, or the picture developed from them when they are a camera raw file. Camera makers
/// write raw files in TIFF containers, so a TIFF the raw reader claims but can't develop stays the
/// TIFF it is when it reads as one.
fn developed_if_raw(bytes: Vec<u8>) -> Result<Vec<u8>, FormatError> {
if !raw::is_camera_raw(&bytes) {
return Ok(bytes);
}
match raw::develop(&bytes) {
Ok(developed) => Ok(developed.bytes),
Err(_) if stored_dimensions(&bytes).is_ok() => Ok(bytes),
Err(e) => Err(e),
}
}
/// Image bytes with their pixel size (0×0 when they can't be decoded).
pub(crate) fn image_data(data: Vec<u8>) -> ImageData {
let (w, h) = stored_dimensions(&data).unwrap_or((0, 0));
+158
View File
@@ -0,0 +1,158 @@
//! Camera raw files (Panasonic RW2, Canon CR2 / CR3, Nikon NEF, Sony ARW, Fujifilm RAF, Olympus
//! ORF, DNG and the other containers [`craft_raw`] decodes) as images.
//!
//! A raw file holds sensor samples, not a picture, so it is developed once, when it enters a
//! document, and the document keeps the result: a JPEG at quality 95 with full chroma resolution,
//! untagged and so read as sRGB. Drawing, export, collaboration and the browser build then see an
//! ordinary image; the raw file itself is not stored. (A PNG of the same picture is several times
//! larger, and every collaborator downloads the document's images.)
//!
//! The development is the camera's as-shot rendering at neutral settings, made of the shared
//! stages in `craft-develop`:
//!
//! 1. [`craft_raw::decode_with`]: black and white levels, the active area and default crop, the
//! file's own corrections as DNG opcodes (defect pixels, the in-camera distortion correction of
//! RW2 and NEF files).
//! 2. The demosaic (AHD) of the white-balanced mosaic, cropped and with the pixel aspect applied
//! ([`RawDevelopExt::develop_balanced_masked`]).
//! 3. Clipped highlights rebuilt from the channels that did not clip ([`highlight`]).
//! 4. The as-shot white balance and the camera's colour matrices to linear ITU-R BT.2020 (the DNG
//! colour model, DNG 1.7.1 chapter 6), raised by the file's baseline exposure.
//! 5. The generic tone curve on luminance ([`ToneMap::rolloff_hdr`] at neutral settings).
//! 6. BT.2020 to BT.709 primaries, colours outside them desaturated toward their luminance
//! ([`gamut_map`]), the sRGB transfer function (IEC 61966-2-1) and the file's orientation.
//!
//! Not applied: the look tables and tone curve of a camera profile that some DNGs carry, lens
//! corrections a file only records as metadata, noise reduction and sharpening.
use craft_color_transform::{Mat3, REC2020, SRGB};
use craft_develop::finish::gamut_map;
use craft_develop::raster::{Image, par_rows};
use craft_develop::sensor::{Method, RawDevelopExt, color, highlight};
use craft_develop::tone::ToneMap;
use crate::FormatError;
/// A normalised sensor sample (1 = the white level) at or above this counts as clipped.
const CLIP: f32 = 0.99;
/// The most samples a raw file may declare: the pixels of the largest image the renderer decodes
/// (512 MiB of RGBA), so a raw that develops is also one the canvas can draw.
const MAX_SAMPLES: usize = 1 << 27;
/// JPEG quality of the developed picture.
const QUALITY: u8 = 95;
/// Luminance weights of the BT.2020 primaries (ITU-R BT.2020, table 4).
const LUMA_2020: [f32; 3] = [0.2627, 0.6780, 0.0593];
/// Luminance weights of the BT.709 primaries (ITU-R BT.709, item 3.2).
const LUMA_709: [f32; 3] = [0.2126, 0.7152, 0.0722];
/// The file extensions of the raw containers [`craft_raw`] decodes, lower case. Opening goes by the
/// extension; whether the bytes are a raw file is still [`is_camera_raw`]'s to say.
pub const EXTENSIONS: [&str; 21] = [
"3fr", "arw", "cr2", "cr3", "crw", "dng", "erf", "fff", "mef", "mrw", "nef", "nrw", "orf", "pef", "raf", "raw", "rw2", "rwl", "sr2", "srf", "srw",
];
/// Whether `ext` (any case, without the dot) is one of [`EXTENSIONS`].
pub fn is_extension(ext: &str) -> bool {
EXTENSIONS.iter().any(|e| e.eq_ignore_ascii_case(ext))
}
/// Whether `bytes` are a camera raw file (decodable in this build or not).
pub fn is_camera_raw(bytes: &[u8]) -> bool {
craft_raw::probe(bytes).is_some()
}
/// A camera raw file developed into an image.
#[derive(Clone, Debug)]
pub struct Developed {
/// The picture, encoded.
pub bytes: Vec<u8>,
pub width: u32,
pub height: u32,
}
/// Develop the camera raw file `bytes` (see the module docs). An error names what stopped it: not
/// a raw file, a raw variant this build doesn't decode, or damaged data.
pub fn develop(bytes: &[u8]) -> Result<Developed, FormatError> {
let format = craft_raw::probe(bytes).ok_or_else(|| raw_error("not a camera raw file"))?;
if !format.is_supported() {
return Err(raw_error(format!("{format:?} files can't be read")));
}
let mut limits = craft_raw::Limits::default();
limits.max_samples = MAX_SAMPLES;
let raw = craft_raw::decode_with(bytes, &limits).map_err(|e| raw_error(e.to_string()))?;
let white = color::as_shot_white_xy(&raw);
let transform = color::camera_transform(&raw, white);
let wb = transform.wb;
let (mut picture, clipped) = raw.develop_balanced_masked(Method::Ahd, wb, CLIP).map_err(|e| raw_error(e.to_string()))?;
match clipped {
Some(mask) => highlight::reconstruct_masked(&mut picture, wb, CLIP, [1.0; 3], &mask),
None => highlight::reconstruct(&mut picture, wb, CLIP),
};
let gain = 2f64.powf(transform.baseline_exposure);
let gain = if gain.is_finite() { gain } else { 1.0 };
// White-balanced camera RGB → scene-linear BT.2020, the baseline exposure included.
let to_2020 = rows(&transform.matrix.mul(&Mat3::diag(f64::from(wb[0]) * gain, f64::from(wb[1]) * gain, f64::from(wb[2]) * gain)));
let to_709 = rows(&SRGB.from_xyz().mul(&REC2020.to_xyz()));
let tone = ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0);
let (width, height) = (picture.width, picture.height);
let mut rgb: Image<[u8; 3]> = Image::new(width, height);
let source = &picture.data;
par_rows(&mut rgb.data, width, |y, row| {
for (x, out) in row.iter_mut().enumerate() {
let scene = apply(&to_2020, source[y * width + x]);
let luminance = dot(LUMA_2020, scene);
let display = if luminance > 0.0 { scene.map(|c| c * tone.apply(luminance) / luminance) } else { [0.0; 3] };
let (linear, _) = gamut_map(apply(&to_709, display), LUMA_709);
*out = linear.map(encode_srgb);
}
});
drop(picture);
let rgb = rgb.into_oriented(craft_geom::Orientation::from_exif(raw.orientation.to_exif()));
let (width, height) = (u32::try_from(rgb.width).map_err(|_| too_large())?, u32::try_from(rgb.height).map_err(|_| too_large())?);
let image = craft_image_codecs::Image::from_u8(width, height, craft_image_codecs::ChannelLayout::Rgb, rgb.data.into_flattened())
.map_err(|e| raw_error(e.to_string()))?;
let options = craft_image_codecs::EncodeOptions {
jpeg_quality: QUALITY,
jpeg_chroma_subsampling: false,
embed_icc: false,
embed_metadata: false,
..Default::default()
};
let bytes = craft_image_codecs::encode(&image, craft_image_codecs::Format::Jpeg, &options).map_err(|e| raw_error(e.to_string()))?;
Ok(Developed { bytes, width, height })
}
fn raw_error(reason: impl std::fmt::Display) -> FormatError {
FormatError::Corrupt(format!("unsupported image: camera raw: {reason}"))
}
fn too_large() -> FormatError {
raw_error("the picture is too large")
}
fn rows(m: &Mat3) -> [[f32; 3]; 3] {
m.0.map(|row| row.map(|v| v as f32))
}
fn apply(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
m.map(|row| dot(row, v))
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// Linear `v` (0 to 1) as an 8-bit sRGB code (IEC 61966-2-1, the inverse of its equation 1).
fn encode_srgb(v: f32) -> u8 {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let e = if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
(e * 255.0 + 0.5) as u8
}
+1 -1
View File
@@ -1,5 +1,5 @@
use super::clock::{AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, CJK_CHANGES, FrameClock, TOAST_SECS, ToastClock, repaint_in};
use super::open::OPEN_EXTENSIONS;
use super::open::open_extensions;
use super::services::{DialogFuture, PickFuture, Picked, RepaintWaker, Services};
use super::state::{LEFT_PANEL, LeftTab, MOBILE_STRIP, MobilePanel, NARROW_WIDTH, PANEL_DEFAULT, RIGHT_PANEL, RightTab, TitleBar, fit_panels};
use super::{
+6 -4
View File
@@ -1,6 +1,6 @@
use super::{
AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OPEN_EXTENSIONS, OsStr, Path, PathBuf, PendingDialog, PickFuture,
Picked, Poll, RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows,
AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OsStr, Path, PathBuf, PendingDialog, PickFuture, Picked, Poll,
RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows,
};
impl FigApp {
@@ -73,7 +73,7 @@ impl FigApp {
pub fn open_dialog(&mut self) {
// Opening needs no file in front: it goes ahead even if that file closed meanwhile.
self.pick_file(i18n::tr("Open"), OPEN_EXTENSIONS, false, |app, file| {
self.pick_file(i18n::tr("Open"), &super::open_extensions(), false, |app, file| {
if app.run_user("file.open", file).is_some() {
app.ui.home = false;
}
@@ -86,8 +86,10 @@ impl FigApp {
} else {
&["penpot", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "figcraft", "fig", "jam", "sketch"]
};
// Camera raw files place as the image they develop to.
let exts: Vec<&str> = exts.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect();
let title = if place { i18n::tr("Place image") } else { i18n::tr("Import") };
self.pick_file(title, exts, true, |app, file| {
self.pick_file(title, &exts, true, |app, file| {
app.run_user("file.import", file);
});
}
+8 -1
View File
@@ -7,9 +7,16 @@ use super::{OsStr, Path, theme};
pub(crate) const OPEN_EXTENSIONS: &[&str] =
&["figcraft", "fig", "jam", "penpot", "sketch", "json", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff"];
/// [`OPEN_EXTENSIONS`] and the camera raw files, which open as an image too: what File ▸ Open offers.
pub(crate) fn open_extensions() -> Vec<&'static str> {
OPEN_EXTENSIONS.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect()
}
/// Whether `path` names a file type that opens as a document (the extension, in any case).
pub(crate) fn opens(path: &Path) -> bool {
path.extension().and_then(OsStr::to_str).is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e)))
path.extension()
.and_then(OsStr::to_str)
.is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e)) || figcraft_format::raw::is_extension(e))
}
/// Whether `path` is a whole document (`.figcraft`, `.fig`, `.jam`, `.penpot`, `.sketch`, file JSON) rather than an image or SVG:
+3 -1
View File
@@ -640,7 +640,9 @@ fn picked_bytes(file: &serde_json::Value) -> Option<Vec<u8>> {
/// Ask for an image file for `target`: layers' paints keep their fill mode, crop and position.
fn upload_image(app: &mut FigApp, target: &PickerTarget) {
let target = target.clone();
app.pick_file(tr("Choose image"), &IMAGE_FILES, true, move |app, file| {
// Camera raw files fill as the image they develop to.
let files: Vec<&str> = IMAGE_FILES.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect();
app.pick_file(tr("Choose image"), &files, true, move |app, file| {
if let PickerTarget::Paint { fills, index, ids } = &target
&& !region_backed(app, &target)
{
+3 -1
View File
@@ -192,7 +192,9 @@ figcraft-cli export app.figcraft -o handoff.fig
By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort),
`.penpot` (Penpot 2.x archive, best effort), `.svg` (an editable frame: groups,
shapes, text, gradients, masks and effects; `info` lists what it left out as `note:` lines), `.png/.jpg/.webp/.gif/.tif/.bmp`
(an image layer). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`,
(an image layer), camera raw files (`.rw2`, `.cr2`, `.cr3`, `.nef`, `.arw`, `.raf`, `.orf`, `.dng` and the other
containers craft-raw reads: an image layer of the picture developed with the camera's as-shot white balance and a
neutral tone curve; the document keeps that picture, not the raw file). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`,
`.png/.jpg/.webp` (the current page rendered at 1x with its background), `.pdf` (the current page's
frames, one page each), `.fig` (the whole file, experimental, as `export --format fig`), `.penpot`
(the whole file as a Penpot 2.x archive, as `export --format penpot`).
+1
View File
@@ -37,6 +37,7 @@ and prototype interactions are still unchecked there.
| HEIC | yes | **no** | shortcut: no Rust decoder; the usable ones (libheif, libde265) are C libraries, and HEVC carries patents. Revisit when a Rust decoder exists | 2–3 |
| TIFF | Safari only | **yes** | open, import, place, drop (the `image` crate's TIFF decoder; its embedded ICC profile is honoured); SVG exports embed it (and BMP) as PNG, which SVG viewers show | — |
| BMP | — | yes | | — |
| Camera raw (RW2, CR2, CR3, NEF, ARW, RAF, ORF, DNG and the other containers craft-raw reads) | no | **yes**, developed | open, import, place, drop, image fills: the raw is developed once as it comes in (craft-raw decode; craft-develop demosaic, as-shot white balance, colour matrices, highlight rebuild and neutral tone curve) and the document keeps the picture as a JPEG at quality 95 with full chroma, not the raw file; a raw variant craft-raw doesn't decode is refused with its reason. Not applied: DNG camera-profile looks, lens corrections kept only as metadata, noise reduction, sharpening | — |
| MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 |
| Images over 4096 px | downscaled to 4096 | kept | | — |
| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). On macOS, pasting a single supported raster file copied in Finder places the file’s image on the canvas. Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` |