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)]
165#[repr(C)]
166pub struct Photo {
167 pub handle: String,
168 pub mime: String,
170 pub bytes: u64,
171 pub width: u32,
173 pub height: u32,
174}
175
176impl Photo {
177 pub fn encode(&self) -> Vec<u8> {
179 use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
180 let mut buffer = Vec::new();
181 BincodeFfiFormat::serialize(&mut buffer, self).expect("encode Photo");
182 buffer
183 }
184
185 pub fn decode(bytes: &[u8]) -> Result<Self, String> {
186 use crux_core::bridge::{BincodeFfiFormat, FfiFormat};
187 BincodeFfiFormat::deserialize(bytes).map_err(|e| e.to_string())
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub enum PhotoError {
194 Cancelled,
195 TooLarge,
197 UnsupportedImage,
199 Unavailable,
201 Failed(String),
202}
203
204impl PhotoError {
205 pub fn code(&self) -> &str {
206 match self {
207 Self::Cancelled => "cancelled",
208 Self::TooLarge => "too_large",
209 Self::UnsupportedImage => "unsupported_image",
210 Self::Unavailable => "unavailable",
211 Self::Failed(text) => text,
212 }
213 }
214
215 fn from_code(code: &str) -> Self {
216 match code {
217 "cancelled" => Self::Cancelled,
218 "too_large" => Self::TooLarge,
219 "unsupported_image" => Self::UnsupportedImage,
220 "unavailable" => Self::Unavailable,
221 other => Self::Failed(other.to_string()),
222 }
223 }
224}
225
226pub(crate) fn from_response(r: &PluginResponse) -> Result<Photo, PhotoError> {
227 if r.ok {
228 Photo::decode(&r.output).map_err(|_| PhotoError::Failed("unsupported shell".into()))
229 } else {
230 Err(PhotoError::from_code(&String::from_utf8_lossy(&r.output)))
231 }
232}
233
234pub fn needs_reencode(format: PhotoFormat, fits: bool, strip_metadata: bool, has_metadata: bool) -> bool {
237 format != PhotoFormat::Original || !fits || (strip_metadata && has_metadata)
238}
239
240pub const MAX_PIXELS: u64 = 16_000_000;
243
244pub fn target_size(width: u32, height: u32, max: Option<u32>) -> (u32, u32) {
247 let longest = width.max(height);
248 let dimension_cap = max.filter(|m| *m > 0 && longest > *m);
249 let mut scale = dimension_cap.map_or(1.0, |m| f64::from(m) / f64::from(longest));
250 let pixels = f64::from(width) * f64::from(height) * scale * scale;
251 let pixel_capped = pixels > MAX_PIXELS as f64;
252 if pixel_capped {
253 scale *= (MAX_PIXELS as f64 / pixels).sqrt();
254 }
255 if scale >= 1.0 {
256 return (width, height);
257 }
258 let fit = |v: u32| ((f64::from(v) * scale).floor() as u32).max(1);
259 let (mut w, mut h) = (fit(width), fit(height));
260 if let (Some(m), false) = (dimension_cap, pixel_capped) {
263 let short = |s: u32, l: u32| ((u64::from(s) * u64::from(m) / u64::from(l)) as u32).max(1);
264 if width >= height { (w, h) = (m, short(height, width)) } else { (w, h) = (short(width, height), m) }
265 }
266 (w, h)
267}
268
269const CLEAN_PNG_CHUNKS: [&[u8; 4]; 13] =
271 [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"];
272
273pub fn png_is_clean(bytes: &[u8]) -> bool {
277 const MAGIC: &[u8] = b"\x89PNG\r\n\x1a\n";
278 let Some(mut rest) = bytes.strip_prefix(MAGIC) else { return false };
279 loop {
280 if rest.len() < 12 {
281 return false;
282 }
283 let len = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
284 let kind: &[u8; 4] = rest[4..8].try_into().expect("4 bytes");
285 if !CLEAN_PNG_CHUNKS.contains(&kind) {
286 return false;
287 }
288 let Some(next) = rest.get(12..).and_then(|r| r.get(len..)) else { return false };
290 if kind == b"IEND" {
291 return next.is_empty();
293 }
294 rest = next;
295 }
296}
297
298pub fn quality_ladder(start: u8) -> Vec<u8> {
300 let start = start.clamp(1, 100);
301 let mut steps = vec![start];
302 let mut q = start;
303 while q > 45 {
304 q = q.saturating_sub(10).max(45);
305 steps.push(q);
306 }
307 steps
308}
309
310pub fn output_format(requested: PhotoFormat, source_is_png: bool) -> PhotoFormat {
312 match requested {
313 PhotoFormat::Original if source_is_png => PhotoFormat::Png,
314 PhotoFormat::Original => PhotoFormat::Jpeg,
315 other => other,
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::PluginResponse;
323
324 #[test]
325 fn options_json_omits_defaults_and_round_trips() {
326 assert_eq!(PhotoOptions::new().to_input(), "{}");
327 let o = PhotoOptions::new().jpeg().max_dimension(2048).max_bytes(4 << 20).quality(80).keep_metadata();
328 assert_eq!(o.to_input(), r#"{"format":"jpeg","max_dimension":2048,"max_bytes":4194304,"quality":80,"strip_metadata":false}"#);
329 assert_eq!(PhotoOptions::from_input(&o.to_input()), o);
330 assert_eq!(PhotoOptions::from_input("{}"), PhotoOptions::new());
331 assert_eq!(PhotoOptions::from_input("not json"), PhotoOptions::new());
332 assert_eq!(PhotoOptions::new().quality(0).quality_value(), 1);
333 assert_eq!(PhotoOptions::new().quality(200).quality_value(), 100);
334 }
335
336 #[test]
337 fn photo_round_trips() {
338 let p = Photo { handle: "file:///c/p.jpg".into(), mime: "image/jpeg".into(), bytes: 1_234_567, width: 2048, height: 1536 };
339 assert_eq!(Photo::decode(&p.encode()), Ok(p));
340 }
341
342 #[test]
343 fn codes_map_to_errors() {
344 for (code, e) in [("cancelled", PhotoError::Cancelled), ("too_large", PhotoError::TooLarge), ("unsupported_image", PhotoError::UnsupportedImage), ("unavailable", PhotoError::Unavailable)] {
345 assert_eq!(from_response(&PluginResponse::text(false, code)), Err(e.clone()));
346 assert_eq!(e.code(), code);
347 }
348 assert_eq!(from_response(&PluginResponse::text(false, "disk full")), Err(PhotoError::Failed("disk full".into())));
349 }
350
351 #[test]
352 fn ok_reply_that_is_not_a_photo_is_failed() {
353 assert_eq!(from_response(&PluginResponse::text(true, "content://media/1")), Err(PhotoError::Failed("unsupported shell".into())));
355 }
356
357 #[test]
358 fn pass_through_only_when_original_fits_and_clean() {
359 assert!(!needs_reencode(PhotoFormat::Original, true, true, false));
360 assert!(!needs_reencode(PhotoFormat::Original, true, false, true));
361 assert!(needs_reencode(PhotoFormat::Original, true, true, true));
362 assert!(needs_reencode(PhotoFormat::Original, false, false, false));
363 assert!(needs_reencode(PhotoFormat::Jpeg, true, false, false));
364 }
365
366 #[test]
367 fn target_size_caps_the_longest_side_and_never_upscales() {
368 assert_eq!(target_size(4000, 3000, Some(2048)), (2048, 1536));
369 assert_eq!(target_size(3000, 4000, Some(2048)), (1536, 2048));
370 assert_eq!(target_size(4000, 3000, Some(0)), (4000, 3000));
371 assert_eq!(target_size(800, 600, Some(2048)), (800, 600));
372 assert_eq!(target_size(800, 600, None), (800, 600));
373 assert_eq!(target_size(10_000, 1, Some(100)), (100, 1));
374 }
375
376 fn png(chunks: &[&[u8; 4]]) -> Vec<u8> {
377 let mut v = b"\x89PNG\r\n\x1a\n".to_vec();
378 for c in chunks {
379 v.extend_from_slice(&3u32.to_be_bytes());
380 v.extend_from_slice(*c);
381 v.extend_from_slice(b"abc");
382 v.extend_from_slice(&[0, 0, 0, 0]); }
384 v
385 }
386
387 #[test]
388 fn only_a_png_with_harmless_chunks_is_clean() {
389 assert!(png_is_clean(&png(&[b"IHDR", b"sRGB", b"pHYs", b"IDAT", b"IEND"])));
390 assert!(!png_is_clean(&png(&[b"IHDR", b"eXIf", b"IDAT", b"IEND"])));
391 assert!(!png_is_clean(&png(&[b"IHDR", b"iTXt", b"IDAT", b"IEND"])));
392 assert!(!png_is_clean(&png(&[b"IHDR", b"tEXt", b"IDAT", b"IEND"])));
393 assert!(!png_is_clean(b"\xff\xd8\xff\xe1 a JPEG renamed .png"));
394 let mut fake = png(&[b"IHDR", b"IDAT", b"IEND"]);
396 fake[..8].copy_from_slice(b"\xff\xd8\xff\xe0JFIF");
397 assert!(!png_is_clean(&fake));
398 assert!(!png_is_clean(&png(&[b"IHDR", b"IDAT"])[..20])); assert!(!png_is_clean(b""));
400 }
401
402 #[test]
403 fn a_png_must_end_at_iend() {
404 let mut trailing = png(&[b"IHDR", b"IDAT", b"IEND"]);
406 trailing.push(0);
407 assert!(!png_is_clean(&trailing));
408 }
409
410 #[test]
411 fn a_huge_chunk_length_is_not_clean() {
412 let mut huge = b"\x89PNG\r\n\x1a\n".to_vec();
414 huge.extend_from_slice(&0xFFFF_FFF4u32.to_be_bytes());
415 huge.extend_from_slice(b"IDAT");
416 huge.extend_from_slice(&[0; 8]);
417 assert!(!png_is_clean(&huge));
418 }
419
420 #[test]
421 fn the_long_side_lands_exactly_on_max_dimension() {
422 for (w, h, m) in [(4624, 3468, 1600), (4624, 3468, 800), (3468, 4624, 3000)] {
423 let (tw, th) = target_size(w, h, Some(m));
424 assert_eq!(tw.max(th), m, "{w}x{h} → {tw}x{th}");
425 }
426 for (side, m) in [(3000, 1600), (161, 100), (194, 100), (4000, 2048)] {
428 assert_eq!(target_size(side, side, Some(m)), (m, m), "{side}² at {m}");
429 }
430 }
431
432 #[test]
433 fn target_size_caps_the_pixel_count() {
434 let (w, h) = target_size(16_320, 12_240, None);
436 assert!(u64::from(w) * u64::from(h) <= MAX_PIXELS, "{w}x{h}");
437 assert_eq!((w as f64 / h as f64 * 100.0).round(), (16_320.0f64 / 12_240.0 * 100.0).round());
438 assert_eq!(target_size(4000, 3000, None), (4000, 3000)); }
440
441 #[test]
442 fn max_dimension_zero_means_no_limit() {
443 assert_eq!(PhotoOptions::new().max_dimension(0).max_dimension_opt(), None);
444 assert_eq!(PhotoOptions::from_input(r#"{"max_dimension":0}"#).max_dimension_opt(), None);
445 }
446
447 #[test]
448 fn quality_ladder_steps_down_to_45() {
449 assert_eq!(quality_ladder(85), vec![85, 75, 65, 55, 45]);
450 assert_eq!(quality_ladder(50), vec![50, 45]);
451 assert_eq!(quality_ladder(30), vec![30]);
452 assert!(quality_ladder(100).iter().all(|q| *q >= 45 || *q == 100));
453 }
454
455 #[test]
456 fn original_keeps_png_and_writes_everything_else_as_jpeg() {
457 assert_eq!(output_format(PhotoFormat::Original, true), PhotoFormat::Png);
458 assert_eq!(output_format(PhotoFormat::Original, false), PhotoFormat::Jpeg);
459 assert_eq!(output_format(PhotoFormat::Webp, false), PhotoFormat::Webp);
460 assert_eq!((PhotoFormat::Jpeg.mime(), PhotoFormat::Jpeg.extension()), ("image/jpeg", "jpg"));
461 }
462}