1use facet::Facet;
7use serde::{Deserialize, Serialize};
8
9use crate::PluginResponse;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum PhotoFormat {
15 #[default]
18 Original,
19 Jpeg,
20 Png,
21 Webp,
24}
25
26impl PhotoFormat {
27 pub fn mime(self) -> &'static str {
28 match self {
29 Self::Png => "image/png",
30 Self::Webp => "image/webp",
31 Self::Jpeg | Self::Original => "image/jpeg",
32 }
33 }
34
35 pub fn extension(self) -> &'static str {
36 match self {
37 Self::Png => "png",
38 Self::Webp => "webp",
39 Self::Jpeg | Self::Original => "jpg",
40 }
41 }
42
43 fn is_original(&self) -> bool {
44 *self == Self::Original
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(default)]
52pub struct PhotoOptions {
53 #[serde(skip_serializing_if = "PhotoFormat::is_original")]
54 format: PhotoFormat,
55 #[serde(skip_serializing_if = "Option::is_none")]
56 max_dimension: Option<u32>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 max_bytes: Option<u64>,
59 #[serde(skip_serializing_if = "is_default_quality")]
60 quality: u8,
61 #[serde(skip_serializing_if = "is_true")]
62 strip_metadata: bool,
63}
64
65const DEFAULT_QUALITY: u8 = 85;
66
67fn is_default_quality(q: &u8) -> bool {
68 *q == DEFAULT_QUALITY
69}
70
71fn is_true(b: &bool) -> bool {
72 *b
73}
74
75impl Default for PhotoOptions {
76 fn default() -> Self {
77 Self { format: PhotoFormat::Original, max_dimension: None, max_bytes: None, quality: DEFAULT_QUALITY, strip_metadata: true }
78 }
79}
80
81impl PhotoOptions {
82 #[must_use]
83 pub fn new() -> Self {
84 Self::default()
85 }
86 #[must_use]
87 pub fn jpeg(mut self) -> Self {
88 self.format = PhotoFormat::Jpeg;
89 self
90 }
91 #[must_use]
92 pub fn png(mut self) -> Self {
93 self.format = PhotoFormat::Png;
94 self
95 }
96 #[must_use]
97 pub fn webp(mut self) -> Self {
98 self.format = PhotoFormat::Webp;
99 self
100 }
101 #[must_use]
102 pub fn original(mut self) -> Self {
103 self.format = PhotoFormat::Original;
104 self
105 }
106 #[must_use]
108 pub fn max_dimension(mut self, px: u32) -> Self {
109 self.max_dimension = (px > 0).then_some(px);
110 self
111 }
112 #[must_use]
115 pub fn max_bytes(mut self, bytes: u64) -> Self {
116 self.max_bytes = Some(bytes);
117 self
118 }
119 #[must_use]
121 pub fn quality(mut self, q: u8) -> Self {
122 self.quality = q.clamp(1, 100);
123 self
124 }
125 #[must_use]
128 pub fn keep_metadata(mut self) -> Self {
129 self.strip_metadata = false;
130 self
131 }
132
133 pub fn format(&self) -> PhotoFormat {
134 self.format
135 }
136 pub fn max_dimension_opt(&self) -> Option<u32> {
137 self.max_dimension
138 }
139 pub fn max_bytes_opt(&self) -> Option<u64> {
140 self.max_bytes
141 }
142 pub fn quality_value(&self) -> u8 {
143 self.quality.clamp(1, 100)
144 }
145 pub fn strip_metadata(&self) -> bool {
146 self.strip_metadata
147 }
148
149 pub(crate) fn to_input(&self) -> String {
150 serde_json::to_string(self).expect("serialize photo options")
151 }
152
153 pub fn from_input(input: &str) -> Self {
155 let mut o: Self = serde_json::from_str(input).unwrap_or_default();
156 o.quality = o.quality.clamp(1, 100);
157 o.max_dimension = o.max_dimension.filter(|px| *px > 0);
158 o
159 }
160}
161
162#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
170#[repr(C)]
171pub struct Photo {
172 pub handle: String,
173 pub mime: String,
175 pub bytes: u64,
176 pub width: u32,
178 pub height: u32,
179}
180
181impl Photo {
182 pub fn encode(&self) -> Vec<u8> {
184 use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
185 let mut buffer = Vec::new();
186 BincodeFfiFormat::serialize(&mut buffer, self).expect("encode Photo");
187 buffer
188 }
189
190 pub fn decode(bytes: &[u8]) -> Result<Self, String> {
191 use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
192 BincodeFfiFormat::deserialize(bytes).map_err(|e| e.to_string())
193 }
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub enum PhotoError {
199 Cancelled,
200 TooLarge,
202 UnsupportedImage,
204 Unavailable,
206 Failed(String),
207}
208
209impl PhotoError {
210 pub fn code(&self) -> &str {
211 match self {
212 Self::Cancelled => "cancelled",
213 Self::TooLarge => "too_large",
214 Self::UnsupportedImage => "unsupported_image",
215 Self::Unavailable => "unavailable",
216 Self::Failed(text) => text,
217 }
218 }
219
220 fn from_code(code: &str) -> Self {
221 match code {
222 "cancelled" => Self::Cancelled,
223 "too_large" => Self::TooLarge,
224 "unsupported_image" => Self::UnsupportedImage,
225 "unavailable" => Self::Unavailable,
226 other => Self::Failed(other.to_string()),
227 }
228 }
229}
230
231pub(crate) fn from_response(r: &PluginResponse) -> Result<Photo, PhotoError> {
232 if r.ok {
233 Photo::decode(&r.output).map_err(|_| PhotoError::Failed("unsupported shell".into()))
234 } else {
235 Err(PhotoError::from_code(&String::from_utf8_lossy(&r.output)))
236 }
237}
238
239pub fn needs_reencode(format: PhotoFormat, fits: bool, strip_metadata: bool, has_metadata: bool) -> bool {
242 format != PhotoFormat::Original || !fits || (strip_metadata && has_metadata)
243}
244
245pub const MAX_PIXELS: u64 = 16_000_000;
248
249pub fn target_size(width: u32, height: u32, max: Option<u32>) -> (u32, u32) {
252 let longest = width.max(height);
253 let dimension_cap = max.filter(|m| *m > 0 && longest > *m);
254 let mut scale = dimension_cap.map_or(1.0, |m| f64::from(m) / f64::from(longest));
255 let pixels = f64::from(width) * f64::from(height) * scale * scale;
256 let pixel_capped = pixels > MAX_PIXELS as f64;
257 if pixel_capped {
258 scale *= (MAX_PIXELS as f64 / pixels).sqrt();
259 }
260 if scale >= 1.0 {
261 return (width, height);
262 }
263 let fit = |v: u32| ((f64::from(v) * scale).floor() as u32).max(1);
264 let (mut w, mut h) = (fit(width), fit(height));
265 if let (Some(m), false) = (dimension_cap, pixel_capped) {
268 let short = |s: u32, l: u32| ((u64::from(s) * u64::from(m) / u64::from(l)) as u32).max(1);
269 if width >= height { (w, h) = (m, short(height, width)) } else { (w, h) = (short(width, height), m) }
270 }
271 (w, h)
272}
273
274const CLEAN_PNG_CHUNKS: [&[u8; 4]; 13] =
276 [b"IHDR", b"PLTE", b"IDAT", b"IEND", b"tRNS", b"gAMA", b"cHRM", b"sRGB", b"iCCP", b"sBIT", b"pHYs", b"bKGD", b"cICP"];
277
278pub fn png_is_clean(bytes: &[u8]) -> bool {
282 const MAGIC: &[u8] = b"\x89PNG\r\n\x1a\n";
283 let Some(mut rest) = bytes.strip_prefix(MAGIC) else { return false };
284 loop {
285 if rest.len() < 12 {
286 return false;
287 }
288 let len = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
289 let kind: &[u8; 4] = rest[4..8].try_into().expect("4 bytes");
290 if !CLEAN_PNG_CHUNKS.contains(&kind) {
291 return false;
292 }
293 let Some(next) = rest.get(12..).and_then(|r| r.get(len..)) else { return false };
295 if kind == b"IEND" {
296 return next.is_empty();
298 }
299 rest = next;
300 }
301}
302
303pub fn quality_ladder(start: u8) -> Vec<u8> {
305 let start = start.clamp(1, 100);
306 let mut steps = vec![start];
307 let mut q = start;
308 while q > 45 {
309 q = q.saturating_sub(10).max(45);
310 steps.push(q);
311 }
312 steps
313}
314
315pub fn output_format(requested: PhotoFormat, source_is_png: bool) -> PhotoFormat {
317 match requested {
318 PhotoFormat::Original if source_is_png => PhotoFormat::Png,
319 PhotoFormat::Original => PhotoFormat::Jpeg,
320 other => other,
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use crate::PluginResponse;
328
329 #[test]
330 fn options_json_omits_defaults_and_round_trips() {
331 assert_eq!(PhotoOptions::new().to_input(), "{}");
332 let o = PhotoOptions::new().jpeg().max_dimension(2048).max_bytes(4 << 20).quality(80).keep_metadata();
333 assert_eq!(o.to_input(), r#"{"format":"jpeg","max_dimension":2048,"max_bytes":4194304,"quality":80,"strip_metadata":false}"#);
334 assert_eq!(PhotoOptions::from_input(&o.to_input()), o);
335 assert_eq!(PhotoOptions::from_input("{}"), PhotoOptions::new());
336 assert_eq!(PhotoOptions::from_input("not json"), PhotoOptions::new());
337 assert_eq!(PhotoOptions::new().quality(0).quality_value(), 1);
338 assert_eq!(PhotoOptions::new().quality(200).quality_value(), 100);
339 }
340
341 #[test]
342 fn photo_round_trips() {
343 let p = Photo { handle: "file:///c/p.jpg".into(), mime: "image/jpeg".into(), bytes: 1_234_567, width: 2048, height: 1536 };
344 assert_eq!(Photo::decode(&p.encode()), Ok(p));
345 }
346
347 #[test]
348 fn codes_map_to_errors() {
349 for (code, e) in [("cancelled", PhotoError::Cancelled), ("too_large", PhotoError::TooLarge), ("unsupported_image", PhotoError::UnsupportedImage), ("unavailable", PhotoError::Unavailable)] {
350 assert_eq!(from_response(&PluginResponse::text(false, code)), Err(e.clone()));
351 assert_eq!(e.code(), code);
352 }
353 assert_eq!(from_response(&PluginResponse::text(false, "disk full")), Err(PhotoError::Failed("disk full".into())));
354 }
355
356 #[test]
357 fn ok_reply_that_is_not_a_photo_is_failed() {
358 assert_eq!(from_response(&PluginResponse::text(true, "content://media/1")), Err(PhotoError::Failed("unsupported shell".into())));
360 }
361
362 #[test]
363 fn pass_through_only_when_original_fits_and_clean() {
364 assert!(!needs_reencode(PhotoFormat::Original, true, true, false));
365 assert!(!needs_reencode(PhotoFormat::Original, true, false, true));
366 assert!(needs_reencode(PhotoFormat::Original, true, true, true));
367 assert!(needs_reencode(PhotoFormat::Original, false, false, false));
368 assert!(needs_reencode(PhotoFormat::Jpeg, true, false, false));
369 }
370
371 #[test]
372 fn target_size_caps_the_longest_side_and_never_upscales() {
373 assert_eq!(target_size(4000, 3000, Some(2048)), (2048, 1536));
374 assert_eq!(target_size(3000, 4000, Some(2048)), (1536, 2048));
375 assert_eq!(target_size(4000, 3000, Some(0)), (4000, 3000));
376 assert_eq!(target_size(800, 600, Some(2048)), (800, 600));
377 assert_eq!(target_size(800, 600, None), (800, 600));
378 assert_eq!(target_size(10_000, 1, Some(100)), (100, 1));
379 }
380
381 fn png(chunks: &[&[u8; 4]]) -> Vec<u8> {
382 let mut v = b"\x89PNG\r\n\x1a\n".to_vec();
383 for c in chunks {
384 v.extend_from_slice(&3u32.to_be_bytes());
385 v.extend_from_slice(*c);
386 v.extend_from_slice(b"abc");
387 v.extend_from_slice(&[0, 0, 0, 0]); }
389 v
390 }
391
392 #[test]
393 fn only_a_png_with_harmless_chunks_is_clean() {
394 assert!(png_is_clean(&png(&[b"IHDR", b"sRGB", b"pHYs", b"IDAT", b"IEND"])));
395 assert!(!png_is_clean(&png(&[b"IHDR", b"eXIf", b"IDAT", b"IEND"])));
396 assert!(!png_is_clean(&png(&[b"IHDR", b"iTXt", b"IDAT", b"IEND"])));
397 assert!(!png_is_clean(&png(&[b"IHDR", b"tEXt", b"IDAT", b"IEND"])));
398 assert!(!png_is_clean(b"\xff\xd8\xff\xe1 a JPEG renamed .png"));
399 let mut fake = png(&[b"IHDR", b"IDAT", b"IEND"]);
401 fake[..8].copy_from_slice(b"\xff\xd8\xff\xe0JFIF");
402 assert!(!png_is_clean(&fake));
403 assert!(!png_is_clean(&png(&[b"IHDR", b"IDAT"])[..20])); assert!(!png_is_clean(b""));
405 }
406
407 #[test]
408 fn a_png_must_end_at_iend() {
409 let mut trailing = png(&[b"IHDR", b"IDAT", b"IEND"]);
411 trailing.push(0);
412 assert!(!png_is_clean(&trailing));
413 }
414
415 #[test]
416 fn a_huge_chunk_length_is_not_clean() {
417 let mut huge = b"\x89PNG\r\n\x1a\n".to_vec();
419 huge.extend_from_slice(&0xFFFF_FFF4u32.to_be_bytes());
420 huge.extend_from_slice(b"IDAT");
421 huge.extend_from_slice(&[0; 8]);
422 assert!(!png_is_clean(&huge));
423 }
424
425 #[test]
426 fn the_long_side_lands_exactly_on_max_dimension() {
427 for (w, h, m) in [(4624, 3468, 1600), (4624, 3468, 800), (3468, 4624, 3000)] {
428 let (tw, th) = target_size(w, h, Some(m));
429 assert_eq!(tw.max(th), m, "{w}x{h} → {tw}x{th}");
430 }
431 for (side, m) in [(3000, 1600), (161, 100), (194, 100), (4000, 2048)] {
433 assert_eq!(target_size(side, side, Some(m)), (m, m), "{side}² at {m}");
434 }
435 }
436
437 #[test]
438 fn target_size_caps_the_pixel_count() {
439 let (w, h) = target_size(16_320, 12_240, None);
441 assert!(u64::from(w) * u64::from(h) <= MAX_PIXELS, "{w}x{h}");
442 assert_eq!((w as f64 / h as f64 * 100.0).round(), (16_320.0f64 / 12_240.0 * 100.0).round());
443 assert_eq!(target_size(4000, 3000, None), (4000, 3000)); }
445
446 #[test]
447 fn max_dimension_zero_means_no_limit() {
448 assert_eq!(PhotoOptions::new().max_dimension(0).max_dimension_opt(), None);
449 assert_eq!(PhotoOptions::from_input(r#"{"max_dimension":0}"#).max_dimension_opt(), None);
450 }
451
452 #[test]
453 fn quality_ladder_steps_down_to_45() {
454 assert_eq!(quality_ladder(85), vec![85, 75, 65, 55, 45]);
455 assert_eq!(quality_ladder(50), vec![50, 45]);
456 assert_eq!(quality_ladder(30), vec![30]);
457 assert!(quality_ladder(100).iter().all(|q| *q >= 45 || *q == 100));
458 }
459
460 #[test]
461 fn original_keeps_png_and_writes_everything_else_as_jpeg() {
462 assert_eq!(output_format(PhotoFormat::Original, true), PhotoFormat::Png);
463 assert_eq!(output_format(PhotoFormat::Original, false), PhotoFormat::Jpeg);
464 assert_eq!(output_format(PhotoFormat::Webp, false), PhotoFormat::Webp);
465 assert_eq!((PhotoFormat::Jpeg.mime(), PhotoFormat::Jpeg.extension()), ("image/jpeg", "jpg"));
466 }
467}