Skip to main content

oxideav_cli_convert/
op.rs

1//! IM-style operations supported by `oxideav convert`.
2//!
3//! Each variant carries exactly the data the CLI needs to hand to
4//! [`crate::plan_to_job`], nothing more.
5
6/// Dither strategy used when `-colors N` forces a paletted output.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Dither {
9    None,
10    Bayer,
11    FloydSteinberg,
12}
13
14impl Dither {
15    /// Parse the value after `-dither`. Accepts ImageMagick-ish names
16    /// case-insensitively (`None`, `FloydSteinberg`, `floyd_steinberg`,
17    /// `o8x8` / `ordered` → Bayer).
18    pub fn parse(s: &str) -> Result<Dither, String> {
19        match s.to_ascii_lowercase().as_str() {
20            "none" => Ok(Dither::None),
21            "floyd_steinberg" | "floyd-steinberg" | "floydsteinberg" | "fs" => {
22                Ok(Dither::FloydSteinberg)
23            }
24            "bayer" | "ordered" | "o8x8" => Ok(Dither::Bayer),
25            other => Err(format!(
26                "convert: -dither: unknown strategy '{other}' (expected 'none', 'bayer', or 'floyd_steinberg')"
27            )),
28        }
29    }
30}
31
32/// `-alpha SUBCOMMAND`. ImageMagick exposes a small grammar of alpha-channel
33/// edits — we cover the ones with deterministic semantics on RGBA buffers.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum AlphaOp {
36    /// `on` / `activate` — enable alpha (no-op when output is already RGBA).
37    On,
38    /// `off` / `deactivate` — strip the alpha channel from the output
39    /// (Rgba → Rgb24).
40    Off,
41    /// `remove` — composite the image over the current `-background`
42    /// colour and force every output pixel's alpha to `255`.
43    Remove,
44    /// `set` / `opaque` — set every alpha sample to `255` without
45    /// compositing.
46    Set,
47    /// `transparent` — set every alpha sample to `0` without touching
48    /// the colour channels.
49    Transparent,
50}
51
52impl AlphaOp {
53    pub fn parse(s: &str) -> Result<AlphaOp, String> {
54        match s.to_ascii_lowercase().as_str() {
55            "on" | "activate" => Ok(AlphaOp::On),
56            "off" | "deactivate" => Ok(AlphaOp::Off),
57            "remove" => Ok(AlphaOp::Remove),
58            "set" | "opaque" => Ok(AlphaOp::Set),
59            "transparent" => Ok(AlphaOp::Transparent),
60            other => Err(format!(
61                "convert: -alpha: unknown subcommand '{other}' (expected 'on'/'off'/'activate'/'deactivate'/'remove'/'set'/'opaque'/'transparent')"
62            )),
63        }
64    }
65}
66
67/// `-resize` / `-thumbnail` geometry-modifier suffix.
68///
69/// ImageMagick's geometry grammar tags the literal `WxH` with a single
70/// trailing character that selects the scaling policy. We honour the
71/// six common ones; everything else (`%@` combos, gravity flags, …)
72/// is a documented follow-up.
73///
74/// The runtime sees the original `WxH` plus this tag and resolves the
75/// final pixel dimensions against the actual source size — most modes
76/// can't be eagerly resolved at parse time because we don't yet know
77/// the source dims.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79pub enum ResizeMode {
80    /// No suffix — preserve aspect ratio and FIT inside the `WxH` box
81    /// (the larger of the two scale factors wins, so neither output
82    /// dimension exceeds the request). IM's default geometry policy.
83    #[default]
84    Default,
85    /// `WxH!` — IGNORE aspect ratio, force the exact `WxH` dimensions.
86    /// Equivalent to the original `bang = true`.
87    Force,
88    /// `WxH^` — preserve aspect ratio and FILL the `WxH` box (the
89    /// smaller of the two scale factors wins, so both output
90    /// dimensions are at least the request). Common pairing with a
91    /// follow-up `-crop` to land on exact `WxH`.
92    Fill,
93    /// `WxH>` — only resize when the input is LARGER than `WxH`
94    /// (otherwise pass through unchanged). IM's "shrink-only" policy.
95    Shrink,
96    /// `WxH<` — only resize when the input is SMALLER than `WxH`
97    /// (otherwise pass through unchanged). IM's "enlarge-only" policy.
98    Grow,
99    /// `WxH%` — interpret `W` and `H` as percentages of the source
100    /// dimensions (independent X / Y scale). `WxH` are still parsed as
101    /// integer percentages by `parse_wxh`; if only one number is given
102    /// it applies to both axes (handled at parse time).
103    Percent,
104    /// `WxH@` — interpret `W*H` as the TARGET pixel area; both output
105    /// dims are scaled by `sqrt(target_area / source_area)` so the
106    /// aspect ratio is preserved AND the output area matches the
107    /// request.
108    Area,
109}
110
111impl ResizeMode {
112    /// Strip an IM geometry-modifier suffix off `WxH`.
113    /// Returns `(mode, geometry-without-suffix)`. No suffix means
114    /// `Default` plus the input verbatim. Multiple suffix chars
115    /// (e.g. `WxH^!`) are rejected by the args parser layer; here we
116    /// only peel the LAST one and report what we found.
117    pub fn split_suffix(s: &str) -> (ResizeMode, &str) {
118        if let Some(core) = s.strip_suffix('!') {
119            return (ResizeMode::Force, core);
120        }
121        if let Some(core) = s.strip_suffix('^') {
122            return (ResizeMode::Fill, core);
123        }
124        if let Some(core) = s.strip_suffix('>') {
125            return (ResizeMode::Shrink, core);
126        }
127        if let Some(core) = s.strip_suffix('<') {
128            return (ResizeMode::Grow, core);
129        }
130        if let Some(core) = s.strip_suffix('%') {
131            return (ResizeMode::Percent, core);
132        }
133        if let Some(core) = s.strip_suffix('@') {
134            return (ResizeMode::Area, core);
135        }
136        (ResizeMode::Default, s)
137    }
138
139    /// Lowercase tag string used in JSON params handed to the resize
140    /// factory. Stable identifiers — codecs that grow geometry-mode
141    /// awareness can branch off these.
142    pub fn as_tag(self) -> &'static str {
143        match self {
144            ResizeMode::Default => "default",
145            ResizeMode::Force => "force",
146            ResizeMode::Fill => "fill",
147            ResizeMode::Shrink => "shrink",
148            ResizeMode::Grow => "grow",
149            ResizeMode::Percent => "percent",
150            ResizeMode::Area => "area",
151        }
152    }
153
154    /// Resolve the final `(out_w, out_h)` for a request of `(req_w,
155    /// req_h)` against a source size of `(src_w, src_h)`.
156    ///
157    /// Output is always >= 1 on both axes; clipping to source dims for
158    /// `Shrink` / `Grow` modes happens here so the caller can blindly
159    /// hand the result to the resize filter without re-checking.
160    pub fn resolve(self, req_w: u32, req_h: u32, src_w: u32, src_h: u32) -> (u32, u32) {
161        let sw = src_w.max(1) as f64;
162        let sh = src_h.max(1) as f64;
163        let rw = req_w.max(1) as f64;
164        let rh = req_h.max(1) as f64;
165        let (out_w, out_h) = match self {
166            ResizeMode::Default => {
167                // Aspect-preserving fit: pick the smaller scale.
168                let s = (rw / sw).min(rh / sh);
169                ((sw * s).round(), (sh * s).round())
170            }
171            ResizeMode::Force => (rw, rh),
172            ResizeMode::Fill => {
173                let s = (rw / sw).max(rh / sh);
174                ((sw * s).round(), (sh * s).round())
175            }
176            ResizeMode::Shrink => {
177                if (src_w <= req_w) && (src_h <= req_h) {
178                    (sw, sh)
179                } else {
180                    let s = (rw / sw).min(rh / sh);
181                    ((sw * s).round(), (sh * s).round())
182                }
183            }
184            ResizeMode::Grow => {
185                if (src_w >= req_w) && (src_h >= req_h) {
186                    (sw, sh)
187                } else {
188                    let s = (rw / sw).min(rh / sh);
189                    ((sw * s).round(), (sh * s).round())
190                }
191            }
192            ResizeMode::Percent => {
193                // req_w / req_h are percentages: 50 → half, 200 → double.
194                ((sw * rw / 100.0).round(), (sh * rh / 100.0).round())
195            }
196            ResizeMode::Area => {
197                let target_area = rw * rh;
198                let src_area = sw * sh;
199                let s = (target_area / src_area).sqrt();
200                ((sw * s).round(), (sh * s).round())
201            }
202        };
203        ((out_w as i64).max(1) as u32, (out_h as i64).max(1) as u32)
204    }
205}
206
207/// One convert operation.
208///
209/// Operations apply in source order — same as `imagemagick convert`,
210/// even though we don't yet support IM's stack-reset semantics.
211#[derive(Clone, Debug, PartialEq)]
212pub enum Op {
213    /// `-resize WxH[!^<>%@]`. The trailing modifier selects the
214    /// scaling policy via [`ResizeMode`]; absence of any modifier is
215    /// `ResizeMode::Default` (aspect-preserving fit-inside).
216    Resize {
217        width: u32,
218        height: u32,
219        mode: ResizeMode,
220    },
221    /// `-thumbnail WxH[!^<>%@]` — IM convenience flag. Same geometry
222    /// grammar as `-resize`; the runner unrolls it into a Resize plus
223    /// Strip pair (and, eventually, an auto-orient pass) so the
224    /// downstream pipeline doesn't need a dedicated thumbnail node.
225    Thumbnail {
226        width: u32,
227        height: u32,
228        mode: ResizeMode,
229    },
230    /// `-define KEY[=VALUE]` — opaque codec-specific tunable forwarded
231    /// to the sink. Keys keep their literal form (e.g.
232    /// `jpeg:dct-method`); the sink encoder picks up keys it
233    /// recognises and silently ignores the rest, mirroring IM's
234    /// "tolerant of irrelevant options" posture. Bare `-define KEY`
235    /// (no `=VALUE`) sets the key to JSON `true`.
236    Define { key: String, value: Option<String> },
237    /// `-blur RxS`. Sigma defaults to `radius / 2.0` when the `xS`
238    /// portion is omitted (matches IM's convention).
239    Blur { radius: u32, sigma: f32 },
240    /// `-edge R`. Radius ignored by the current Sobel impl but parsed
241    /// for forward-compatibility.
242    Edge { radius: u32 },
243    /// `-colors N` paired with an optional `-dither` preceding it.
244    /// When present, the output is paletted via
245    /// [`oxideav_pixfmt`] before encoding.
246    Colors { count: u32, dither: Dither },
247    /// `-format FMT` — override the container/codec decision
248    /// otherwise derived from the output extension.
249    Format(String),
250    /// `-quality N` — forwarded to the sink codec (e.g. JPEG quality,
251    /// WebP quality). Silently dropped by codecs that don't honour it.
252    Quality(u32),
253    /// `-strip` — request that metadata (EXIF, XMP, ID3, etc.) be
254    /// dropped on write.
255    Strip,
256    /// `-density N` — DPI for vector→raster conversion. PDF / SVG
257    /// pages are measured in PostScript points (1/72 inch); a page at
258    /// 300 DPI rasterises to `points × (300 / 72)` pixels per axis.
259    /// Ignored on raster-only inputs.
260    Density(u32),
261    /// `-background COLOR` — canvas fill colour used by the
262    /// rasteriser and by `-alpha remove`. CSS L3 named colours and
263    /// `#hex` 3/4/6/8 forms accepted (same parser as `xc:`).
264    Background([u8; 4]),
265    /// `-alpha SUBCOMMAND` — see [`AlphaOp`].
266    Alpha(AlphaOp),
267    /// `-rotate N` — rotate by N degrees. Round-1 supports only
268    /// multiples of 90 (90/180/270 and the negatives). Other angles
269    /// are rejected by the args parser with a "only multiples of 90
270    /// supported" message.
271    Rotate { degrees: i32 },
272    /// `-flip` — vertical flip (reverse row order).
273    Flip,
274    /// `-flop` — horizontal flip (reverse column order within each row).
275    Flop,
276    /// `-crop WxH+X+Y` — extract a `WxH` bounding box at offset `(X,Y)`.
277    /// The args parser accepts the IM grammar; runtime checks that the
278    /// bbox fits inside the input dimensions and errors cleanly when
279    /// it doesn't.
280    Crop { x: u32, y: u32, w: u32, h: u32 },
281    /// `-negate` — per-pixel `out = 255 - in` on the colour channels;
282    /// alpha (when present) is unchanged.
283    Negate,
284    /// `-sharpen RxS` — unsharp-mask sharpening with radius / sigma
285    /// (amount defaults to 1.0 in the factory). Sigma defaults to
286    /// `radius / 2.0` when only `R` is given.
287    Sharpen { radius: u32, sigma: f32 },
288    /// `-unsharp RxS+amount+threshold` — full unsharp-mask grammar.
289    /// Amount and threshold each default to a sensible value when
290    /// omitted (`amount = 1.0`, `threshold = 0`).
291    Unsharp {
292        radius: u32,
293        sigma: f32,
294        amount: f32,
295        threshold: u8,
296    },
297    /// `-gamma G` — power-law gamma correction. `G > 0`.
298    Gamma { value: f32 },
299    /// `-brightness-contrast B[,C]` — brightness in `[-100..=100]`,
300    /// contrast in `[-100..=100]` (both percent-of-range). Either
301    /// argument may be omitted; the IM grammar tolerates `B`,
302    /// `Bx`, `BxC`, `B,C`.
303    BrightnessContrast { brightness: f32, contrast: f32 },
304    /// `-contrast` (no value) — IM applies a tiny per-channel contrast
305    /// step. Multiple `-contrast` flags accumulate; we collapse them
306    /// into a single delta carried on the op (positive for `-contrast`,
307    /// negative for `+contrast`, which IM uses for the inverse). The
308    /// factory wires this to `BrightnessContrast::new(0, 5*delta)` —
309    /// a 5-percent step matching IM's "single contrast bump" feel.
310    Contrast { delta: i32 },
311    /// `-sepia THRESHOLD%` — warm-tint mapping. `threshold` is a
312    /// scalar in `0.0..=1.0` (IM expresses it as a percentage of the
313    /// dynamic range; we accept either form on parse).
314    Sepia { threshold: f32 },
315    /// `-modulate B,S,H` — IM's HSL-style triplet. Each component is
316    /// percent-of-base around 100 (so `100,100,0` is identity, `200`
317    /// doubles, `0` zeros, etc.). The hue field is "hue offset
318    /// percent" but image-filter takes degrees; we translate.
319    Modulate {
320        brightness: f32,
321        saturation: f32,
322        hue: f32,
323    },
324    /// `-level B/G/W` — input black point, gamma, white point. Black
325    /// and white are 0..=255; gamma must be `> 0`.
326    Level { black: u8, gamma: f32, white: u8 },
327    /// `-normalize` — stretch the histogram to fill 0..=255.
328    Normalize,
329    /// `-threshold N%` — binarise: pixels below `value` map to 0,
330    /// pixels at or above map to 255.
331    Threshold { value: u8 },
332    /// `-posterize N` — collapse to `N` levels per channel.
333    Posterize { levels: u32 },
334    /// `-solarize N%` — invert pixels above the threshold.
335    Solarize { value: u8 },
336    /// `-colorspace gray|grey|rgb|srgb` — round-1 covers only the
337    /// grayscale conversion (everything else is treated as a
338    /// pass-through, keeping the input colourspace).
339    Colorspace(String),
340    /// `-vignette R+S+X+Y` — Gaussian radial darkening centred at
341    /// `(x, y)`. `radius`/`sigma` are in pixels (`sigma` defaults to
342    /// `radius / 2.0` when omitted, matching IM); `x`/`y` are
343    /// **normalised** image-relative offsets in `[0.0, 1.0]` (the
344    /// image-filter factory takes them this way to stay
345    /// resolution-independent), defaulting to `0.5 / 0.5` (image
346    /// centre) when omitted.
347    Vignette {
348        radius: f32,
349        sigma: f32,
350        x: f32,
351        y: f32,
352    },
353    /// `-colorize C[xC[xC]]/A%` — linear blend toward a target colour
354    /// by `amount`. `color` is `[R, G, B, A]` (alpha defaults to
355    /// `255`); `amount` is a unit scalar in `[0.0, 1.0]` (IM expresses
356    /// it as a percentage of the dynamic range).
357    Colorize { color: [u8; 4], amount: f32 },
358    /// `-equalize` (no value) — per-channel histogram equalisation via
359    /// CDF mapping.
360    Equalize,
361    /// `-auto-gamma` (no value) — auto-gamma: pick a per-channel gamma
362    /// so the geometric mean lands at `0.5`.
363    AutoGamma,
364    /// `-extent WxH[+X+Y]` — re-window the input onto a fixed `WxH`
365    /// canvas. The source is placed at signed offset `(x, y)` (default
366    /// `(0, 0)`, IM's top-left convention); pixels outside the source
367    /// rectangle are painted with `bg` (RGBA). Offsets may be negative
368    /// (`-extent 100x100-10-10`) to translate the source toward the
369    /// upper-left so its right / bottom edge can land inside the
370    /// window. Unlike `Crop` (only shrinks) and `Resize` (only scales),
371    /// `Extent` can both add canvas and discard content depending on
372    /// the requested geometry.
373    ///
374    /// `bg` is captured at args-parse time from the most recent
375    /// `-background` op seen in source order (defaulting to IM's
376    /// opaque white `[255, 255, 255, 255]` when none was set). Pinning
377    /// the colour onto the op preserves source-order semantics — a
378    /// later `-background` does NOT retroactively repaint an earlier
379    /// `-extent`'s padding.
380    Extent {
381        width: u32,
382        height: u32,
383        x: i32,
384        y: i32,
385        bg: [u8; 4],
386    },
387    /// `-trim` — auto-crop to the bounding box of pixels that differ
388    /// from a reference background colour by more than `fuzz` per
389    /// channel. The reference colour is the input's `(0, 0)` pixel
390    /// (matching IM's behaviour when no `-bordercolor`/`-background`
391    /// override is set). `fuzz` defaults to `0` (exact match); a
392    /// preceding `-fuzz N[%]` flag updates the value carried on this
393    /// op at args-parse time, so source order is preserved (`-fuzz 10
394    /// -trim -fuzz 0 -trim` lands as `Trim { fuzz: 10 }, Trim { fuzz:
395    /// 0 }`).
396    Trim { fuzz: u8 },
397    /// `-roll ±X±Y` — circular pixel shift. `dx` shifts columns
398    /// to the right by `dx` pixels (negative = left); `dy` shifts
399    /// rows down by `dy` pixels (negative = up). Pixels that fall
400    /// off one edge wrap around to the opposite edge — width and
401    /// height stay unchanged, and the total pixel count is
402    /// preserved. The IM grammar requires both X and Y signed
403    /// (`-roll +5+10`, `-roll -3+2`); a single offset (`-roll +5`)
404    /// is rejected at parse time.
405    Roll { dx: i32, dy: i32 },
406}
407
408/// A printf-style multi-output template. Detected by the args parser
409/// when the output filename contains `%[0-9]*d`. Used by Scene-shaped
410/// inputs (PDF) to fan out one file per page.
411///
412/// Examples:
413///   `page-%03d.png` → prefix=`page-`, width=3, suffix=`.png` →
414///   `page-000.png`, `page-001.png`, …
415///   `out%d.jpg`     → prefix=`out`, width=0, suffix=`.jpg` →
416///   `out0.jpg`, `out1.jpg`, …
417#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct PrintfTemplate {
419    pub prefix: String,
420    pub width: u8,
421    pub suffix: String,
422}
423
424impl PrintfTemplate {
425    /// Render the template at the given index.
426    pub fn expand(&self, n: usize) -> String {
427        if self.width == 0 {
428            format!("{}{}{}", self.prefix, n, self.suffix)
429        } else {
430            format!(
431                "{}{:0>width$}{}",
432                self.prefix,
433                n,
434                self.suffix,
435                width = self.width as usize
436            )
437        }
438    }
439}
440
441/// One atomic spec inside a [`PageSelector`].
442///
443/// A single index (`5`, `-1`) or an inclusive range (`2-5`, `5--1`).
444/// Indices are signed so the IM convention `-1` = last page,
445/// `-2` = second-to-last, … can ride through unchanged. Resolution
446/// against an actual page count is `PageAtom::resolve`.
447#[derive(Clone, Debug, PartialEq, Eq)]
448pub enum PageAtom {
449    /// Single page index. Negative values count from the end:
450    /// `-1` = last page, `-2` = second-to-last, ….
451    Single(isize),
452    /// Inclusive range `start..=end`. Either endpoint may be negative
453    /// (`5..=-1` = "page 5 through the last page"). After resolution
454    /// against the actual page count, `start <= end` is required.
455    Range(isize, isize),
456}
457
458impl PageAtom {
459    /// Resolve this atom against a known `total_pages` count, appending
460    /// the resulting zero-based indices to `out` in IM-source order
461    /// (range left-to-right). Negative indices `-k` map to
462    /// `total_pages - k`.
463    fn resolve_into(&self, total_pages: usize, out: &mut Vec<usize>) -> Result<(), String> {
464        match self {
465            PageAtom::Single(n) => {
466                let idx = resolve_signed_index(*n, total_pages)?;
467                out.push(idx);
468                Ok(())
469            }
470            PageAtom::Range(a, b) => {
471                let aa = resolve_signed_index(*a, total_pages)?;
472                let bb = resolve_signed_index(*b, total_pages)?;
473                if aa > bb {
474                    return Err(format!(
475                        "page range [{a}-{b}] resolves to inverted [{aa}-{bb}] (start > end after negative-index resolution)"
476                    ));
477                }
478                out.extend(aa..=bb);
479                Ok(())
480            }
481        }
482    }
483}
484
485fn resolve_signed_index(n: isize, total_pages: usize) -> Result<usize, String> {
486    if n >= 0 {
487        let u = n as usize;
488        if u >= total_pages {
489            Err(format!(
490                "page index {n} out of range (input has {total_pages} page(s))"
491            ))
492        } else {
493            Ok(u)
494        }
495    } else {
496        // Negative — count from the end. `-1` = last page.
497        let off = (-n) as usize;
498        if off > total_pages || off == 0 {
499            Err(format!(
500                "negative page index {n} out of range (input has {total_pages} page(s); valid: -1..=-{total_pages})"
501            ))
502        } else {
503            Ok(total_pages - off)
504        }
505    }
506}
507
508/// ImageMagick-style `[N]` / `[N-M]` / `[A,B,…]` page-selection suffix
509/// on an input path. `input.pdf[0]` selects page 0; `input.pdf[2-5]`
510/// selects pages 2, 3, 4, 5 (inclusive on both ends, like IM);
511/// `input.pdf[-1]` selects the last page; `input.pdf[0,2,4]` selects a
512/// comma-separated list (atoms may themselves be ranges, so
513/// `[0-2,5,-1]` picks pages 0, 1, 2, 5, and the last page).
514///
515/// The single-atom variants ([`Single`](Self::Single) /
516/// [`Range`](Self::Range)) are preserved for ergonomics — most callers
517/// only care about the one-atom case — but every comma-separated
518/// invocation lands as a [`List`](Self::List).
519#[derive(Clone, Debug, PartialEq, Eq)]
520pub enum PageSelector {
521    /// Single page index. Negative values count from the end
522    /// (`-1` = last page).
523    Single(isize),
524    /// Inclusive range `start..=end`. Either endpoint may be negative.
525    Range(isize, isize),
526    /// Comma-separated list of atoms. Order is preserved on resolve;
527    /// duplicates are NOT collapsed (IM convention — `[0,0,0]` writes
528    /// the same page three times). Empty list rejected at parse time.
529    List(Vec<PageAtom>),
530}
531
532impl PageSelector {
533    /// Resolve the selector to a list of zero-based page indices,
534    /// validated against `total_pages`. Negative indices `-k` resolve
535    /// to `total_pages - k`. Order matches the IM source order:
536    /// `[0,2,4]` yields `[0, 2, 4]`; `[-1,0]` yields
537    /// `[total_pages-1, 0]`. Duplicates (e.g. `[0,0]`) are preserved.
538    pub fn resolve(&self, total_pages: usize) -> Result<Vec<usize>, String> {
539        let mut out = Vec::new();
540        match self {
541            PageSelector::Single(n) => {
542                PageAtom::Single(*n).resolve_into(total_pages, &mut out)?;
543            }
544            PageSelector::Range(a, b) => {
545                PageAtom::Range(*a, *b).resolve_into(total_pages, &mut out)?;
546            }
547            PageSelector::List(atoms) => {
548                for atom in atoms {
549                    atom.resolve_into(total_pages, &mut out)?;
550                }
551            }
552        }
553        Ok(out)
554    }
555}
556
557/// `-stl-format` value. Selects which STL-on-disk flavour the encoder
558/// emits. Default is [`Binary`](Self::Binary), matching the registry
559/// factory.
560#[derive(Clone, Copy, Debug, PartialEq, Eq)]
561pub enum StlFormatChoice {
562    /// 80-byte header + `uint32` triangle count + `N × 50`-byte triangle
563    /// records. Compact and binary-stable.
564    Binary,
565    /// `solid … endsolid` ASCII grammar. Larger and floating-point
566    /// formatted but human-readable.
567    Ascii,
568}
569
570impl StlFormatChoice {
571    /// Parse the value after `-stl-format`. Accepts ImageMagick-ish
572    /// tokens case-insensitively (`binary`/`bin` → Binary, `ascii`/`text`
573    /// → Ascii).
574    pub fn parse(s: &str) -> Result<StlFormatChoice, String> {
575        match s.to_ascii_lowercase().as_str() {
576            "binary" | "bin" => Ok(StlFormatChoice::Binary),
577            "ascii" | "text" => Ok(StlFormatChoice::Ascii),
578            other => Err(format!(
579                "convert: -stl-format: unknown flavour '{other}' (expected 'binary' or 'ascii')"
580            )),
581        }
582    }
583}
584
585/// `-gltf-format` value. Selects the glTF on-disk container.
586///
587/// `JsonExternal` is documented but not yet implementable today
588/// (the underlying `OutputFlavour::JsonExternal` is missing in
589/// published `oxideav-gltf` 0.0.0); the args parser accepts the
590/// token now and the encoder will reject it cleanly until the
591/// upstream variant lands. See gltf-rN follow-up.
592#[derive(Clone, Copy, Debug, PartialEq, Eq)]
593pub enum GltfFormatChoice {
594    /// `.glb` self-contained binary container.
595    Glb,
596    /// `.gltf` JSON document with the binary buffer inlined as a
597    /// base64 `data:application/octet-stream;base64,…` URI.
598    JsonEmbedded,
599    /// `.gltf` JSON document referencing a sidecar `.bin` file.
600    /// Reserved — emits an "unsupported" error today (gltf-rN).
601    JsonExternal,
602}
603
604impl GltfFormatChoice {
605    /// Parse the value after `-gltf-format`. Accepts case-insensitive
606    /// `glb`, `embedded`, `external`. `binary` is an alias for `glb`
607    /// (mirrors how IM-style flags often accept short-form synonyms).
608    pub fn parse(s: &str) -> Result<GltfFormatChoice, String> {
609        match s.to_ascii_lowercase().as_str() {
610            "glb" | "binary" => Ok(GltfFormatChoice::Glb),
611            "embedded" | "json" | "json-embedded" => Ok(GltfFormatChoice::JsonEmbedded),
612            "external" | "json-external" => Ok(GltfFormatChoice::JsonExternal),
613            other => Err(format!(
614                "convert: -gltf-format: unknown flavour '{other}' (expected 'glb', 'embedded', or 'external')"
615            )),
616        }
617    }
618}
619
620/// `-render MODE` value. Selects which surface model the 3D→raster
621/// renderer uses when the user pairs a 3D input (`.stl`/`.obj`/
622/// `.gltf`/`.glb`/`.usdz`) with a raster output (`.png`/`.jpg`/
623/// `.bmp`/`.webp`).
624///
625/// Default is [`Flat`](Self::Flat) — one constant colour per primitive
626/// derived from the material's `base_color` (or a fallback grey when
627/// no material is attached). [`Gouraud`](Self::Gouraud) and
628/// [`Phong`](Self::Phong) add per-vertex / per-pixel lighting using
629/// either the primitive's stored vertex normals or face normals
630/// computed from the triangle vertices when none are provided.
631/// [`NormalDebug`](Self::NormalDebug) and [`DepthDebug`](Self::DepthDebug)
632/// are diagnostic visualisations that bypass the lighting equation
633/// entirely — useful when normals look wrong, a Z-fighting glitch
634/// shows up, or the camera framing seems off.
635#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
636pub enum Mesh3DRenderMode {
637    /// Flat-shaded triangles, one colour per primitive (no per-pixel
638    /// lighting). Cheapest mode and the default.
639    #[default]
640    Flat,
641    /// Wireframe — only triangle edges are drawn, interior pixels stay
642    /// at the background. Same colour-per-primitive as [`Flat`](Self::Flat).
643    Wireframe,
644    /// Gouraud — light is evaluated at each vertex using the per-vertex
645    /// normal, then the resulting RGB is bilinearly interpolated across
646    /// the triangle. Requires (or computes) one normal per vertex.
647    Gouraud,
648    /// Phong — the per-vertex normal is interpolated across the
649    /// triangle and the lighting equation is evaluated per pixel.
650    /// Smoother than Gouraud at the cost of one normalise + dot per
651    /// fragment.
652    Phong,
653    /// NormalDebug — paint each pixel with the world-space interpolated
654    /// normal mapped into RGB (`[r,g,b] = (n + 1) / 2 * 255`). Light /
655    /// camera / material settings are ignored. Useful for inspecting
656    /// whether per-vertex normals were loaded correctly or whether the
657    /// face-normal fallback is firing.
658    NormalDebug,
659    /// DepthDebug — paint each pixel a grayscale value derived from the
660    /// interpolated NDC z (near = white, far = black). Light / camera
661    /// orbit / material settings are ignored; useful for spotting
662    /// Z-fighting and for picking sane near/far planes.
663    DepthDebug,
664}
665
666impl Mesh3DRenderMode {
667    /// Parse the value after `-render`. Accepts case-insensitive
668    /// `flat` / `wireframe` / `gouraud` / `phong` / `normal-debug` /
669    /// `depth-debug`. `wire` is a short alias for `wireframe`;
670    /// `shaded` aliases `flat`; `normal` / `normals` alias
671    /// `normal-debug`; `depth` / `z` alias `depth-debug`.
672    pub fn parse(s: &str) -> Result<Mesh3DRenderMode, String> {
673        match s.to_ascii_lowercase().as_str() {
674            "flat" | "shaded" => Ok(Mesh3DRenderMode::Flat),
675            "wireframe" | "wire" => Ok(Mesh3DRenderMode::Wireframe),
676            "gouraud" => Ok(Mesh3DRenderMode::Gouraud),
677            "phong" => Ok(Mesh3DRenderMode::Phong),
678            "normal-debug" | "normaldebug" | "normal" | "normals" => {
679                Ok(Mesh3DRenderMode::NormalDebug)
680            }
681            "depth-debug" | "depthdebug" | "depth" | "z" => Ok(Mesh3DRenderMode::DepthDebug),
682            other => Err(format!(
683                "convert: -render: unknown mode '{other}' (expected 'flat', 'wireframe', 'gouraud', 'phong', 'normal-debug', or 'depth-debug')"
684            )),
685        }
686    }
687}
688
689/// `-projection MODE` value. Selects perspective vs. orthographic
690/// projection for the 3D→raster renderer. Default is
691/// [`Perspective`](Self::Perspective) — the IM convention for vector
692/// rasterisation matches what most 3D viewers ship.
693#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
694pub enum ProjectionMode {
695    /// Perspective projection — objects shrink with distance.
696    #[default]
697    Perspective,
698    /// Orthographic projection — parallel rays, no foreshortening.
699    /// Useful for technical drawings / part diagrams.
700    Orthographic,
701}
702
703impl ProjectionMode {
704    /// Parse the value after `-projection`. Case-insensitive synonyms:
705    /// `perspective` / `persp` / `p`, `orthographic` / `ortho` / `o`.
706    pub fn parse(s: &str) -> Result<ProjectionMode, String> {
707        match s.to_ascii_lowercase().as_str() {
708            "perspective" | "persp" | "p" => Ok(ProjectionMode::Perspective),
709            "orthographic" | "ortho" | "o" => Ok(ProjectionMode::Orthographic),
710            other => Err(format!(
711                "convert: -projection: unknown mode '{other}' (expected 'perspective' or 'orthographic')"
712            )),
713        }
714    }
715}
716
717/// `-light AZIMUTH,ELEVATION,INTENSITY` — directional light override
718/// for the 3D→raster renderer.
719///
720/// `azimuth` and `elevation` are in degrees; `intensity` is a unit
721/// scalar in `[0.0, ~]` multiplied into the diffuse term. The
722/// renderer always also applies a small constant ambient term so
723/// back-faces stay visible.
724#[derive(Clone, Copy, Debug, PartialEq)]
725pub struct LightSpec {
726    pub azimuth_deg: f32,
727    pub elevation_deg: f32,
728    pub intensity: f32,
729}
730
731impl LightSpec {
732    /// Default directional light: from the upper-right-front quadrant
733    /// at unit intensity. Matches the renderer baseline so explicit
734    /// `-light` is never required.
735    pub fn default_light() -> Self {
736        Self {
737            azimuth_deg: 45.0,
738            elevation_deg: 45.0,
739            intensity: 1.0,
740        }
741    }
742
743    /// Parse `AZIMUTH,ELEVATION,INTENSITY`. All three components are
744    /// required; intensity is clamped to `>= 0.0`.
745    pub fn parse(s: &str) -> Result<LightSpec, String> {
746        let parts: Vec<&str> = s.split([',', 'x']).collect();
747        if parts.len() != 3 {
748            return Err(format!(
749                "convert: -light: '{s}' must be 'AZIMUTH,ELEVATION,INTENSITY' (e.g. '45,30,1.0')"
750            ));
751        }
752        let az: f32 = parts[0]
753            .trim()
754            .parse()
755            .map_err(|_| format!("convert: -light: azimuth '{}' is not a number", parts[0]))?;
756        let el: f32 = parts[1]
757            .trim()
758            .parse()
759            .map_err(|_| format!("convert: -light: elevation '{}' is not a number", parts[1]))?;
760        let intensity: f32 = parts[2]
761            .trim()
762            .parse()
763            .map_err(|_| format!("convert: -light: intensity '{}' is not a number", parts[2]))?;
764        if !intensity.is_finite() || intensity < 0.0 {
765            return Err(format!(
766                "convert: -light: intensity {intensity} must be >= 0.0 and finite"
767            ));
768        }
769        Ok(LightSpec {
770            azimuth_deg: az,
771            elevation_deg: el,
772            intensity,
773        })
774    }
775}
776
777/// `-camera ELEVATION,AZIMUTH,DISTANCE` — camera override for the
778/// 3D→raster renderer.
779///
780/// `elevation` and `azimuth` are in degrees; `distance` is a positive
781/// multiplier of the scene bounding-sphere radius (`1.0` ≈ scene
782/// touches the framebuffer edge; the auto-framing default is `~1.2`).
783#[derive(Clone, Copy, Debug, PartialEq)]
784pub struct CameraSpec {
785    pub elevation_deg: f32,
786    pub azimuth_deg: f32,
787    pub distance: f32,
788}
789
790impl CameraSpec {
791    /// Parse `ELEVATION,AZIMUTH,DISTANCE`. All three components are
792    /// required; distance must be `> 0`.
793    pub fn parse(s: &str) -> Result<CameraSpec, String> {
794        let parts: Vec<&str> = s.split([',', 'x']).collect();
795        if parts.len() != 3 {
796            return Err(format!(
797                "convert: -camera: '{s}' must be 'ELEVATION,AZIMUTH,DISTANCE' (e.g. '20,30,1.5')"
798            ));
799        }
800        let el: f32 = parts[0]
801            .trim()
802            .parse()
803            .map_err(|_| format!("convert: -camera: elevation '{}' is not a number", parts[0]))?;
804        let az: f32 = parts[1]
805            .trim()
806            .parse()
807            .map_err(|_| format!("convert: -camera: azimuth '{}' is not a number", parts[1]))?;
808        let dist: f32 = parts[2]
809            .trim()
810            .parse()
811            .map_err(|_| format!("convert: -camera: distance '{}' is not a number", parts[2]))?;
812        if !dist.is_finite() || dist <= 0.0 {
813            return Err(format!(
814                "convert: -camera: distance {dist} must be > 0.0 and finite"
815            ));
816        }
817        Ok(CameraSpec {
818            elevation_deg: el,
819            azimuth_deg: az,
820            distance: dist,
821        })
822    }
823}
824
825/// Per-format encoder option flags forwarded to the 3D side-channel.
826///
827/// All fields default to `None` meaning "use the format crate's
828/// registry default" — i.e. the existing convert behaviour is
829/// unchanged when no `-foo-format` flag is supplied.
830#[derive(Clone, Debug, Default, PartialEq)]
831pub struct Mesh3DOptions {
832    /// `-stl-format ascii|binary`. `None` → registry default (binary).
833    pub stl_format: Option<StlFormatChoice>,
834    /// `-gltf-format glb|embedded|external`. `None` → infer from
835    /// output extension (`.glb` → Glb, `.gltf` → JsonEmbedded), which
836    /// is exactly what the registry's by-extension lookup already does.
837    pub gltf_format: Option<GltfFormatChoice>,
838    /// `-render flat|wireframe|gouraud|phong`. `None` → default
839    /// ([`Mesh3DRenderMode::Flat`]). Only consulted by the 3D→raster
840    /// side-channel; ignored on every other input/output combination.
841    pub render_mode: Option<Mesh3DRenderMode>,
842    /// `-light AZIMUTH,ELEVATION,INTENSITY`. `None` → renderer
843    /// default ([`LightSpec::default_light`]). Used by Gouraud / Phong
844    /// shading; Flat/Wireframe ignore the light entirely.
845    pub light: Option<LightSpec>,
846    /// `-camera ELEVATION,AZIMUTH,DISTANCE`. `None` → bbox-fit
847    /// auto-frame.
848    pub camera: Option<CameraSpec>,
849    /// `-projection orthographic|perspective`. `None` →
850    /// [`ProjectionMode::Perspective`].
851    pub projection: Option<ProjectionMode>,
852    /// `-fov DEGREES` — vertical field of view for perspective
853    /// projection. `None` → 60°. Ignored for orthographic projection.
854    /// Must be in `(0, 180)`.
855    pub fov_deg: Option<f32>,
856    /// `-bg COLOR` — background fill for the render canvas. `None` →
857    /// transparent black `[0, 0, 0, 0]`. Distinct from `-background`
858    /// (which is the canvas-fill colour for `-alpha remove` and the
859    /// PDF runner) so callers can keep the two paint colours separate.
860    pub bg: Option<[u8; 4]>,
861    /// `-aa N` — supersampling-anti-aliasing factor. The renderer
862    /// rasterises at `N × output_w` by `N × output_h` then box-filters
863    /// the framebuffer back down to the requested output. `None` or
864    /// `Some(1)` → no supersampling (every pixel is point-sampled,
865    /// matching the round-44 baseline). Values >= 2 trade memory and
866    /// CPU for cleaner triangle edges; 2× and 4× are typical. Hard
867    /// cap of 8 because at 8× a 1024² render is a 16M-pixel
868    /// framebuffer + an 8M f32 z-buffer (~80 MB) and that's already
869    /// further than most users want to push a software renderer.
870    pub aa: Option<u32>,
871}
872
873/// The parsed result of one `oxideav convert` invocation.
874#[derive(Clone, Debug)]
875pub struct ConvertPlan {
876    /// Input URI WITH any `[N]`/`[N-M]` page selector stripped.
877    /// Currently exactly one — IM's multi-input stack is a documented
878    /// follow-up.
879    pub input: String,
880    /// Page selector parsed from the input arg's `[…]` suffix, when
881    /// present. `None` means "all pages" for Scene-shaped inputs and
882    /// is ignored for raster inputs.
883    pub input_pages: Option<PageSelector>,
884    /// Chain of operations in source order.
885    pub ops: Vec<Op>,
886    /// Output path (literal). Empty string when `ping` is on and the
887    /// caller omitted it.
888    pub output: String,
889    /// Parsed printf template if `output` contains `%[0-9]*d`. Used by
890    /// the convert runner to fan out per-page when the input is a
891    /// Scene-shaped source (PDF) and the output codec doesn't natively
892    /// accept Scenes.
893    pub output_template: Option<PrintfTemplate>,
894    /// `-ping` mode — read only the headers, print one IM-format line
895    /// per "image" (page / video stream) to stdout, skip pixel decode
896    /// and any output write. Output positional becomes optional.
897    pub ping: bool,
898    /// `--probe` mode — decode the input far enough to extract
899    /// structural metadata (page count, mesh count, sample rate, …),
900    /// print a compact summary to stdout, and skip any output write.
901    /// Mutually exclusive with an output positional: `--probe in.gltf`
902    /// is the supported shape; `--probe in.gltf out.obj` errors at
903    /// the parser. The summary defaults to a pretty-printed
904    /// `key: value` block; pair with [`probe_json`](Self::probe_json)
905    /// for a single-line JSON object instead.
906    pub probe: bool,
907    /// `--json` mode — emit machine-readable JSON instead of the
908    /// pretty-printed summary. Today this only applies to `--probe`;
909    /// passing `--json` without `--probe` is a parser-level error
910    /// since there's nothing else for it to format.
911    pub probe_json: bool,
912    /// `--watch` mode (paired with `--probe`) — re-run the probe
913    /// whenever the input file's mtime changes. Each re-probe emits a
914    /// fresh summary; in JSON mode each summary is on its own line so
915    /// `convert --probe --json --watch in.png | jq` is well-formed
916    /// JSON-lines. Polls the input mtime once per second; the loop
917    /// runs forever and exits only on Ctrl+C / signal. Useful for
918    /// live-monitoring a render-in-progress.
919    pub probe_watch: bool,
920    /// Per-format encoder options for the 3D side-channel
921    /// (`-stl-format`, `-gltf-format`, …). `Default` = "use the
922    /// registry's default factory for each format" so callers who
923    /// don't pass any of these flags see no behaviour change.
924    pub mesh3d_options: Mesh3DOptions,
925}