Skip to main content

openreadout_preview/
lib.rs

1//! Deterministic previews of `OpenReadout` datasets, drawn with the figure engine
2//! (`openreadout-figure`) and encoded as PNG, JPEG or SVG.
3//!
4//! - **Images**: one plane, a channel composite (additive, channel colours from the normalized
5//!   model) or a maximum-intensity projection over z or t, read from the pyramid level nearest the
6//!   requested size when the reader exposes levels, then resampled to the requested size (area
7//!   average; a small image is enlarged by repeating its pixels) and mapped to 8 bits
8//!   with a contrast rule (`auto`, `min-max`, `percentile:LO,HI`, `raw`). By default the picture
9//!   is framed by coordinate rulers in full-resolution pixels (and a scale bar when the pixel
10//!   size is known), and [`ImagePreview`] reports how PNG pixels map back to source pixels, so a
11//!   viewer can read coordinates off the image and ask for a `region` of it.
12//! - **Traces**: one sweep, one panel per channel (min/max envelope per pixel column, so spikes
13//!   survive any downsampling), with ticked axes in the trace's units (time, NMR chemical shift,
14//!   wavenumber, …). Spectra and chromatograms get their largest peaks labelled; current-clamp
15//!   sweeps can get their action potentials marked ([`Marks`]). qPCR curves are overlaid.
16//! - **Spectra**: one mass spectrum, as sticks (centroided) or a profile line, the largest peaks
17//!   labelled with their m/z.
18//! - **Plates**: a heat map of a multi-well plate table (columns named like wells `A1`…`P24`, or
19//!   `well` / `row` + `column` columns); a kinetic read becomes a grid of small growth curves in
20//!   plate positions, coloured by the plate layout's groups.
21//! - **Events**: flow cytometry events as a density plot of two parameters (or a histogram of
22//!   one).
23//!
24//! Callers can draw their own [`Annotation`]s on any preview (points, boxes, outlines, arrows,
25//! text, lines and bands), in full-resolution pixels on images and in axis units on plots;
26//! [`PreviewOutput::annotations`] says where each one landed.
27//!
28//! Every step uses fixed-order arithmetic and no threads, so the same request produces the same
29//! bytes on every run.
30//!
31//! # Example
32//!
33//! Previewing a file is [`render`] (read and draw) followed by [`finish`] (encode):
34//!
35//! ```no_run
36//! use openreadout_core::{Dataset, Result};
37//! use openreadout_preview::{Encoding, PreviewRequest, finish, render};
38//!
39//! fn png_preview(dataset: &mut dyn Dataset) -> Result<Vec<u8>> {
40//!     let info = dataset.info()?;
41//!     let mut request = PreviewRequest::default(); // image 0, channel 0, middle Z, 1024 px
42//!     request.max_size = 512;
43//!     let rendered = render(dataset, &info, &request)?;
44//!     let (output, png) = finish(&rendered, Encoding::Png, 90)?;
45//!     println!("{} x {} px, xxh3 {}", output.width, output.height, output.xxh3);
46//!     Ok(png)
47//! }
48//! ```
49//!
50//! The drawing and encoding layers work without a file:
51//!
52//! ```
53//! use openreadout_preview::{Encoding, Raster, encode};
54//!
55//! let mut raster = Raster::new(4, 2, [0, 0, 0]);
56//! raster.set(0, 0, [255, 255, 255]);
57//! let png = encode(&raster, Encoding::Png, 90)?;
58//! assert_eq!(&png[1..4], b"PNG");
59//! # Ok::<(), openreadout_core::Error>(())
60//! ```
61#![forbid(unsafe_code)]
62#![warn(missing_docs)]
63// Pixel and DCT arithmetic reads best with the conventional short names (x, y, w, h, r, g, b).
64#![allow(clippy::many_single_char_names)]
65
66mod annotate;
67pub mod color;
68mod diffraction;
69pub mod electrochem;
70mod electrophoresis;
71mod events;
72mod fft_inset;
73mod figure_frame;
74mod image;
75mod kinetic;
76mod lanes;
77mod marks;
78mod nmr;
79mod objects;
80mod options;
81mod overlay;
82mod plate;
83mod rulers;
84mod samples;
85mod sequencing;
86mod spectrum;
87mod tic;
88mod trace;
89mod volume;
90
91use std::path::{Path, PathBuf};
92use std::str::FromStr;
93
94use openreadout_core::model::FileInfo;
95use openreadout_core::reader::Dataset;
96use openreadout_core::{Error, Result};
97use schemars::JsonSchema;
98use serde::{Deserialize, Serialize};
99
100pub use annotate::{Annotation, AnnotationType, DrawnAnnotation};
101pub use electrophoresis::series_index_of;
102pub use openreadout_figure::{Figure, Raster};
103pub use options::PreviewOptions;
104pub use plate::{PlateGrid, plate_grid};
105pub use volume::View;
106
107/// Largest `max_size` accepted (pixels on the longer side).
108pub const MAX_PREVIEW_SIZE: u32 = 8192;
109/// Default `max_size`.
110pub const DEFAULT_PREVIEW_SIZE: u32 = 1024;
111/// Default JPEG quality.
112pub const DEFAULT_JPEG_QUALITY: u8 = 90;
113/// Default longest side of a [`thumbnail`].
114pub const DEFAULT_THUMBNAIL_SIZE: u32 = 384;
115/// Default budget of decoded pixel bytes a [`thumbnail`] may read (32 MiB).
116pub const DEFAULT_THUMBNAIL_READ_BYTES: u64 = 32 << 20;
117/// A file with both traces and spectra previews its first trace by default only when some trace
118/// has at least this many samples (a chromatogram of a real run); otherwise spectrum 0.
119pub const MIN_TRACE_SAMPLES_OVER_SPECTRUM: u64 = 100;
120
121/// How sample values map to display brightness.
122#[derive(Debug, Clone, Copy, PartialEq, Default)]
123#[non_exhaustive]
124pub enum Contrast {
125    /// `percentile:0.1,99.9` for most images; `raw` for 8-bit RGB (already display-ready).
126    #[default]
127    Auto,
128    /// Darkest sample → black, brightest → full colour.
129    MinMax,
130    /// The given percentiles of the (downsampled) samples → black and full colour.
131    Percentile(f64, f64),
132    /// The pixel type's full range (0–255 for uint8, 0–65535 for uint16, 0–1 for floats).
133    Raw,
134    /// A display window: values from `center - width / 2` (black) to `center + width / 2`
135    /// (white), in the image's values (Hounsfield units for CT).
136    Window(f64, f64),
137    /// The n-th display window the file stores (`images[].extra.windows`).
138    StoredWindow(usize),
139    /// Logarithmic: the given percentiles → black and full colour, brightness by the logarithm
140    /// of the value above the low one (diffraction images: faint spots and strong ones both
141    /// show).
142    Log(f64, f64),
143}
144
145/// Named CT display windows: `(name, center, width)` in Hounsfield units.
146pub const WINDOW_PRESETS: &[(&str, f64, f64)] = &[
147    ("soft-tissue", 40.0, 400.0),
148    ("brain", 40.0, 80.0),
149    ("subdural", 75.0, 215.0),
150    ("stroke", 40.0, 40.0),
151    ("bone", 400.0, 1800.0),
152    ("lung", -600.0, 1500.0),
153    ("mediastinum", 50.0, 350.0),
154    ("liver", 60.0, 150.0),
155];
156
157/// Percentiles of `log` contrast without numbers: the median (the background) and the 99.9th.
158pub const LOG_PERCENTILES: (f64, f64) = (50.0, 99.9);
159
160impl FromStr for Contrast {
161    type Err = Error;
162    fn from_str(s: &str) -> Result<Self> {
163        let s = s.trim().to_ascii_lowercase();
164        match s.as_str() {
165            "auto" => Ok(Contrast::Auto),
166            "min-max" | "minmax" => Ok(Contrast::MinMax),
167            "raw" => Ok(Contrast::Raw),
168            "log" => Ok(Contrast::Log(LOG_PERCENTILES.0, LOG_PERCENTILES.1)),
169            _ if s.starts_with("window") => {
170                let bad = || {
171                    let names: Vec<&str> = WINDOW_PRESETS.iter().map(|p| p.0).collect();
172                    Error::Usage(format!(
173                        "bad contrast '{s}': use window:CENTER,WIDTH (e.g. window:40,400), window:file (the file's own window; window:file:2 for the third), or a preset: window:{}",
174                        names.join(", window:")
175                    ))
176                };
177                let spec = s.strip_prefix("window:").ok_or_else(bad)?.trim();
178                if let Some(rest) = spec.strip_prefix("file") {
179                    let n = match rest.strip_prefix(':') {
180                        Some(n) => n.trim().parse().map_err(|_| bad())?,
181                        None if rest.is_empty() => 0,
182                        None => return Err(bad()),
183                    };
184                    return Ok(Contrast::StoredWindow(n));
185                }
186                if let Some((_, c, w)) = WINDOW_PRESETS
187                    .iter()
188                    .find(|p| p.0 == spec.replace('_', "-"))
189                {
190                    return Ok(Contrast::Window(*c, *w));
191                }
192                let (c, w) = spec.split_once(',').ok_or_else(bad)?;
193                let (c, w): (f64, f64) = (
194                    c.trim().parse().map_err(|_| bad())?,
195                    w.trim().parse().map_err(|_| bad())?,
196                );
197                if !c.is_finite() || !w.is_finite() || w <= 0.0 {
198                    return Err(bad());
199                }
200                Ok(Contrast::Window(c, w))
201            }
202            _ => {
203                let bad = || {
204                    Error::Usage(format!(
205                        "bad contrast '{s}': use auto, min-max, raw, percentile:LO,HI (e.g. percentile:1,99), log or log:LO,HI, or window:CENTER,WIDTH (window:brain, window:bone, ...)"
206                    ))
207                };
208                let (log, spec) = match s.strip_prefix("log:") {
209                    Some(rest) => (true, rest),
210                    None => (false, s.strip_prefix("percentile:").ok_or_else(bad)?),
211                };
212                let (a, b) = spec.split_once(',').ok_or_else(bad)?;
213                let (a, b): (f64, f64) = (
214                    a.trim().parse().map_err(|_| bad())?,
215                    b.trim().parse().map_err(|_| bad())?,
216                );
217                if !(0.0..=100.0).contains(&a) || !(0.0..=100.0).contains(&b) || a >= b {
218                    return Err(bad());
219                }
220                Ok(if log {
221                    Contrast::Log(a, b)
222                } else {
223                    Contrast::Percentile(a, b)
224                })
225            }
226        }
227    }
228}
229
230impl std::fmt::Display for Contrast {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        match self {
233            Contrast::Auto => f.write_str("auto"),
234            Contrast::MinMax => f.write_str("min-max"),
235            Contrast::Percentile(a, b) => write!(f, "percentile:{a},{b}"),
236            Contrast::Raw => f.write_str("raw"),
237            Contrast::Window(c, w) => write!(f, "window:{c},{w}"),
238            Contrast::StoredWindow(n) => write!(f, "window:file:{n}"),
239            Contrast::Log(a, b) => write!(f, "log:{a},{b}"),
240        }
241    }
242}
243
244/// Colour lookup for a single channel.
245#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
246#[serde(rename_all = "kebab-case")]
247#[non_exhaustive]
248pub enum Lut {
249    /// black to white
250    #[serde(alias = "grey")]
251    Gray,
252    /// black to the channel's colour
253    #[serde(alias = "channel-colour", alias = "color")]
254    ChannelColor,
255    /// white to black: dark marks on a light ground (diffraction images)
256    Inverted,
257}
258
259impl FromStr for Lut {
260    type Err = Error;
261    fn from_str(s: &str) -> Result<Self> {
262        match s.trim().to_ascii_lowercase().as_str() {
263            "gray" | "grey" => Ok(Lut::Gray),
264            "channel-color" | "channel-colour" | "color" => Ok(Lut::ChannelColor),
265            "inverted" => Ok(Lut::Inverted),
266            other => Err(Error::Usage(format!(
267                "bad lut '{other}': use gray, inverted or channel-color"
268            ))),
269        }
270    }
271}
272
273/// Axis of a projection (maximum or sum).
274#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
275#[serde(rename_all = "lowercase")]
276#[non_exhaustive]
277pub enum Axis {
278    /// along z (focal planes)
279    Z,
280    /// along t (time points)
281    T,
282}
283
284/// What frames an image preview.
285#[derive(
286    Debug,
287    Clone,
288    Copy,
289    PartialEq,
290    Eq,
291    Default,
292    serde::Deserialize,
293    serde::Serialize,
294    schemars::JsonSchema,
295)]
296#[serde(rename_all = "kebab-case")]
297#[non_exhaustive]
298pub enum Axes {
299    /// coordinate rulers in full-resolution pixels and a scale bar around the picture (default)
300    #[default]
301    Rulers,
302    /// rulers, plus faint grid lines over the data at the ruler ticks
303    Grid,
304    /// a figure for people: the picture with a scale bar, the title and the caption; no rulers
305    ScaleBar,
306    /// the bare downsampled plane
307    None,
308}
309
310impl Axes {
311    /// Set `axes`, `grid` and `figure` of a request.
312    pub fn apply(self, req: &mut PreviewRequest) {
313        req.axes = self != Axes::None;
314        req.grid = self == Axes::Grid;
315        req.figure = self == Axes::ScaleBar;
316    }
317}
318
319impl FromStr for Axes {
320    type Err = Error;
321    fn from_str(s: &str) -> Result<Self> {
322        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
323            "rulers" => Ok(Axes::Rulers),
324            "grid" => Ok(Axes::Grid),
325            "scale-bar" | "scalebar" => Ok(Axes::ScaleBar),
326            "none" => Ok(Axes::None),
327            other => Err(Error::Usage(format!(
328                "bad axes '{other}': use rulers, grid, scale-bar or none"
329            ))),
330        }
331    }
332}
333
334impl FromStr for Axis {
335    type Err = Error;
336    fn from_str(s: &str) -> Result<Self> {
337        match s.trim().to_ascii_lowercase().as_str() {
338            "z" => Ok(Axis::Z),
339            "t" => Ok(Axis::T),
340            other => Err(Error::Usage(format!(
341                "bad projection axis '{other}': use z or t"
342            ))),
343        }
344    }
345}
346
347/// Output encoding.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
349#[serde(rename_all = "lowercase")]
350#[non_exhaustive]
351pub enum Encoding {
352    /// lossless (default)
353    #[default]
354    Png,
355    /// lossy and smaller
356    #[serde(alias = "jpg")]
357    Jpeg,
358    /// vector: text stays text, image data is embedded as PNG
359    Svg,
360}
361
362impl Encoding {
363    /// The lowercase name (`png`, `jpeg`, `svg`).
364    pub fn as_str(self) -> &'static str {
365        match self {
366            Encoding::Png => "png",
367            Encoding::Jpeg => "jpeg",
368            Encoding::Svg => "svg",
369        }
370    }
371    /// The MIME type (`image/png`, `image/jpeg`, `image/svg+xml`).
372    pub fn mime(self) -> &'static str {
373        match self {
374            Encoding::Png => "image/png",
375            Encoding::Jpeg => "image/jpeg",
376            Encoding::Svg => "image/svg+xml",
377        }
378    }
379    /// The usual file extension (`png`, `jpg`, `svg`).
380    pub fn extension(self) -> &'static str {
381        match self {
382            Encoding::Png => "png",
383            Encoding::Jpeg => "jpg",
384            Encoding::Svg => "svg",
385        }
386    }
387    /// From a file name: `.jpg`/`.jpeg` → JPEG, `.svg` → SVG, anything else → PNG.
388    pub fn from_path(p: &Path) -> Self {
389        match p
390            .extension()
391            .and_then(|e| e.to_str())
392            .map(str::to_ascii_lowercase)
393            .as_deref()
394        {
395            Some("jpg" | "jpeg") => Encoding::Jpeg,
396            Some("svg") => Encoding::Svg,
397            _ => Encoding::Png,
398        }
399    }
400}
401
402impl FromStr for Encoding {
403    type Err = Error;
404    fn from_str(s: &str) -> Result<Self> {
405        match s.trim().to_ascii_lowercase().as_str() {
406            "png" => Ok(Encoding::Png),
407            "jpeg" | "jpg" => Ok(Encoding::Jpeg),
408            "svg" => Ok(Encoding::Svg),
409            other => Err(Error::Usage(format!(
410                "bad preview format '{other}': use png, jpeg or svg"
411            ))),
412        }
413    }
414}
415
416/// Marks drawn from the data itself.
417#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
418#[serde(rename_all = "lowercase")]
419#[non_exhaustive]
420pub enum Marks {
421    /// label the largest peaks of spectra and chromatograms (default)
422    #[default]
423    Auto,
424    /// label the largest peaks of any trace
425    Peaks,
426    /// mark the action potentials of current-clamp sweeps
427    Spikes,
428    /// images: outline and number the nuclei, cells or spots found (`stats` objects)
429    Objects,
430    /// gels and blots: box and number the lanes, draw their profiles and bands (`stats` lanes)
431    Lanes,
432    /// diffraction images: resolution rings and the beam centre (auto draws them when the
433    /// geometry is known)
434    Rings,
435    /// no marks
436    None,
437}
438
439impl FromStr for Marks {
440    type Err = Error;
441    fn from_str(s: &str) -> Result<Self> {
442        match s.trim().to_ascii_lowercase().as_str() {
443            "auto" => Ok(Marks::Auto),
444            "peaks" => Ok(Marks::Peaks),
445            "spikes" => Ok(Marks::Spikes),
446            "objects" => Ok(Marks::Objects),
447            "lanes" => Ok(Marks::Lanes),
448            "rings" => Ok(Marks::Rings),
449            "none" => Ok(Marks::None),
450            other => Err(Error::Usage(format!(
451                "bad marks '{other}': use auto, peaks, spikes, objects, lanes, rings or none"
452            ))),
453        }
454    }
455}
456
457/// What to render. `Default` previews image 0 (middle z, t 0, channel 0) at 1024 px.
458#[derive(Debug, Clone)]
459#[non_exhaustive]
460pub struct PreviewRequest {
461    /// Image index (default 0).
462    pub image: Option<u32>,
463    /// Plane selection (`c=1`, `z=3`, `t=0`, or a combined `c=0,1,z=2`); see [`split_select`].
464    pub select: Vec<String>,
465    /// Maximum-intensity projection axis.
466    pub mip: Option<Axis>,
467    /// Which plane of a volume to show (default: the stored planes, or for medical images the
468    /// anatomical plane they were acquired in, oriented the radiology way).
469    pub view: Option<View>,
470    /// Sum projection axis (the frames of a movie added up: its dose image).
471    pub sum: Option<Axis>,
472    /// Image preview: a power-spectrum (FFT) inset in the top-right corner.
473    pub fft: bool,
474    /// Blend all (or the selected) channels additively in their colours.
475    pub composite: bool,
476    /// Pyramid level (default: the level nearest `max_size`).
477    pub level: Option<u32>,
478    /// Only this rectangle of the image: in the pixel coordinates of `level` when a level is
479    /// given, else in full-resolution (level 0) coordinates, and the level is then chosen so
480    /// that the region renders at about `max_size`.
481    pub region: Option<openreadout_core::Region>,
482    /// Longest side of the output in pixels.
483    pub max_size: u32,
484    /// How sample values map to brightness.
485    pub contrast: Contrast,
486    /// Default: `gray` for one channel, `channel-color` for composites.
487    pub lut: Option<Lut>,
488    /// Trace preview: trace index (default 0).
489    pub trace: Option<u32>,
490    /// Trace preview: sweep (default 0).
491    pub sweep: Option<u32>,
492    /// Trace preview: channel indices (default: the first 8).
493    pub channels: Vec<u32>,
494    /// Trace preview: only this window of the x axis, `[a, b]` in its units (bp of a sized electropherogram, base positions of a Sanger read, minutes, ppm, …).
495    pub x_range: Option<[f64; 2]>,
496    /// Spectrum preview: run index (default 0).
497    pub run: Option<u32>,
498    /// Spectrum preview: zero-based spectrum index (default 0).
499    pub spectrum: Option<u64>,
500    /// Spectrum preview: instrument scan number instead of an index.
501    pub scan: Option<u64>,
502    /// Spectrum preview: the instrument's centroid list instead of the profile.
503    pub centroid: bool,
504    /// Plate or event preview: table index (default 0).
505    pub table: Option<u32>,
506    /// Table columns to draw: a plate's value column (long layout; default the first that is not
507    /// a position), or the x and y parameters of an event preview (one gives a histogram;
508    /// default FSC-A and SSC-A, else the first two).
509    pub columns: Vec<String>,
510    /// Marks drawn from the data (peak labels, action potentials, objects).
511    pub marks: Marks,
512    /// Image preview: how objects are found for `marks: objects` (setting it implies them).
513    pub objects: Option<openreadout_core::measure::ObjectsRequest>,
514    /// Image preview: how lanes are found for `marks: lanes` (setting it implies them).
515    pub lanes: Option<openreadout_core::measure::LanesRequest>,
516    /// The caller's own marks, drawn on top.
517    pub annotations: Vec<Annotation>,
518    /// Draw in the dark theme (light ink on a dark ground).
519    pub dark: bool,
520    /// Image preview: frame the picture with coordinate rulers (full-resolution pixels) and a
521    /// scale bar (default `true`); `false` gives the bare downsampled plane. `max_size` bounds
522    /// the whole picture, rulers included.
523    pub axes: bool,
524    /// Image preview: faint grid lines over the data at the ruler ticks (default `false`; only
525    /// with `axes`).
526    pub grid: bool,
527    /// Image preview: frame the picture as a figure for people instead of with rulers: a scale
528    /// bar under it, and `title` and `caption` (default `false`; only with `axes`).
529    pub figure: bool,
530    /// Image preview: a title above the picture (drawn with `figure`).
531    pub title: Option<String>,
532    /// Image preview: a caption under the picture (drawn with `figure`).
533    pub caption: Option<String>,
534    /// Image preview: refuse (an `unsupported` error) to read more than this many bytes of
535    /// decoded pixels in total, so a quick look never decodes a huge plane.
536    pub max_read_bytes: Option<u64>,
537}
538
539impl Default for PreviewRequest {
540    fn default() -> Self {
541        PreviewRequest {
542            image: None,
543            select: Vec::new(),
544            mip: None,
545            view: None,
546            sum: None,
547            fft: false,
548            composite: false,
549            level: None,
550            region: None,
551            max_size: DEFAULT_PREVIEW_SIZE,
552            contrast: Contrast::Auto,
553            lut: None,
554            trace: None,
555            sweep: None,
556            channels: Vec::new(),
557            x_range: None,
558            run: None,
559            spectrum: None,
560            scan: None,
561            centroid: false,
562            table: None,
563            columns: Vec::new(),
564            marks: Marks::Auto,
565            objects: None,
566            lanes: None,
567            annotations: Vec::new(),
568            dark: false,
569            axes: true,
570            grid: false,
571            figure: false,
572            title: None,
573            caption: None,
574            max_read_bytes: None,
575        }
576    }
577}
578
579/// An image preview, through a view of the volume when one applies ([`volume`]).
580fn render_image(
581    ds: &mut dyn Dataset,
582    info: &FileInfo,
583    req: &PreviewRequest,
584    out: &mut PreviewOutput,
585) -> Result<(Figure, Frame)> {
586    let image = req.image.unwrap_or(0);
587    let Some(im) = info.images.iter().find(|i| i.index == image) else {
588        return image::render(ds, info, req, out);
589    };
590    let Some(view) = volume::effective(info, im, req.view) else {
591        return image::render(ds, info, req, out);
592    };
593    let sel = openreadout_core::select::Selection::parse(&split_select(&req.select))?;
594    let mut req = req.clone();
595    let select_z = sel.z.first().copied();
596    if view == View::Orthogonal {
597        // the z selection places the crosshair; the composite itself is one plane
598        let join = |a: &str, v: &[u32]| {
599            (!v.is_empty()).then(|| {
600                format!(
601                    "{a}={}",
602                    v.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
603                )
604            })
605        };
606        req.select = [join("c", &sel.c), join("t", &sel.t)]
607            .into_iter()
608            .flatten()
609            .collect();
610        if req.mip.is_some() {
611            return Err(Error::Usage(
612                "an orthogonal view shows three slices; project with view axial, coronal or sagittal and mip z".into(),
613            ));
614        }
615        if req.axes && !req.figure {
616            // rulers would count composite pixels; frame it as a figure with a scale bar
617            req.figure = true;
618            req.grid = false;
619            out.notes
620                .push("orthogonal views are framed with a scale bar, not rulers".into());
621        }
622    }
623    let (mut vds, vim, marks, notes) = volume::ViewDataset::new(ds, info, image, view, select_z)?;
624    out.notes.extend(notes);
625    let slices = vim.size_z;
626    let mut vinfo = info.clone();
627    if let Some(slot) = vinfo.images.iter_mut().find(|i| i.index == image) {
628        *slot = vim;
629    }
630    let (mut figure, frame) = image::render(&mut vds, &vinfo, &req, out)?;
631    // the view's own marks (panel names, crosshairs), under the caller's annotations
632    if !marks.is_empty() {
633        let theme = theme(&req);
634        annotate::draw(&mut figure, &frame, &marks, &theme, &mut Vec::new())?;
635    }
636    let drawn = (figure, frame);
637    if let Some(p) = out.image.as_mut() {
638        p.view = Some(
639            match vds.view() {
640                View::Axial => "axial",
641                View::Coronal => "coronal",
642                View::Sagittal => "sagittal",
643                View::Orthogonal => "orthogonal",
644                View::Xz => "xz",
645                View::Yz => "yz",
646                View::Native => "native",
647            }
648            .into(),
649        );
650        p.crosshair = vds.point();
651        p.view_slices = Some(slices);
652    }
653    if req.view.is_none() {
654        out.notes.push(format!(
655            "shown as a radiological {} view (view: native shows the stored orientation)",
656            out.image
657                .as_ref()
658                .and_then(|p| p.view.clone())
659                .unwrap_or_default()
660        ));
661    }
662    let _ = vds.ortho_step();
663    Ok(drawn)
664}
665
666/// The theme a request draws in, sized for its `max_size`.
667pub(crate) fn theme(req: &PreviewRequest) -> openreadout_figure::Theme {
668    let t = if req.dark {
669        openreadout_figure::Theme::dark()
670    } else {
671        openreadout_figure::Theme::light()
672    };
673    t.for_size(req.max_size as f32)
674}
675
676/// One channel of an image preview.
677#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
678pub struct PreviewChannel {
679    /// C index.
680    pub index: u32,
681    /// Channel name, if recorded.
682    #[serde(skip_serializing_if = "Option::is_none")]
683    pub name: Option<String>,
684    /// Display colour `#RRGGBB` (`#FFFFFF` with the gray LUT).
685    pub color: String,
686    /// Where the colour came from: `file` (`channels[].color`), `wavelength`, `palette` or `lut`.
687    pub color_source: String,
688    /// Sample value shown as black.
689    pub display_min: f64,
690    /// Sample value shown at full brightness.
691    pub display_max: f64,
692}
693
694/// A point in full-resolution (level 0) source pixel coordinates.
695#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
696pub struct SourcePoint {
697    /// Column (may be fractional on a downsampled pyramid level).
698    pub x: f64,
699    /// Row.
700    pub y: f64,
701}
702
703/// The scale bar drawn under an image preview.
704#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
705pub struct ScaleBar {
706    /// Length as labelled (e.g. `50`).
707    pub length: f64,
708    /// Unit of the label: `nm`, `µm` or `mm`.
709    pub unit: String,
710    /// Length in µm.
711    pub length_um: f64,
712    /// Length in PNG pixels.
713    pub pixels: u32,
714}
715
716/// Details of an image preview.
717///
718/// PNG pixel `(px, py)` inside `plot_area` shows full-resolution source pixel
719/// `x = source_origin.x + (px - plot_area.x) * source_per_pixel`,
720/// `y = source_origin.y + (py - plot_area.y) * source_per_pixel_y` (left/top edges of the PNG
721/// pixel), whatever pyramid level, downsample or region was drawn; the ruler labels use the same
722/// numbers, so a `region` read off them can be passed straight back.
723#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
724pub struct ImagePreview {
725    /// Image index.
726    pub image: u32,
727    /// Pyramid level read (0 = full resolution).
728    pub level: u32,
729    /// Plane size at that level.
730    pub source_width: u32,
731    /// Plane height at that level.
732    pub source_height: u32,
733    /// The rectangle drawn, in the pixel coordinates of `level`, when a region was asked for.
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub region: Option<openreadout_core::Region>,
736    /// Pixels of the plane at `level` per drawn pixel, horizontally: above 1 when the plane was
737    /// made smaller (an area average), below 1 when it was enlarged (each source pixel drawn as
738    /// a square), 1 when drawn as is.
739    pub downsample: f64,
740    /// Channels, z-planes and time points used.
741    pub c: Vec<u32>,
742    /// Z indices used.
743    pub z: Vec<u32>,
744    /// Time indices used.
745    pub t: Vec<u32>,
746    /// `max-z` or `max-t` for a maximum-intensity projection, `sum-z` or `sum-t` for a sum.
747    #[serde(skip_serializing_if = "Option::is_none")]
748    pub projection: Option<String>,
749    /// True when channels were blended into one colour image.
750    pub composite: bool,
751    /// True when the planes are RGB (samples_per_pixel 3).
752    pub rgb: bool,
753    /// Contrast rule applied (`auto` resolved to what it did, e.g. `percentile:0.1,99.9`).
754    pub contrast: String,
755    /// `gray`, `inverted`, `channel-color` or `rgb`.
756    pub lut: String,
757    /// One entry per channel drawn.
758    pub channels: Vec<PreviewChannel>,
759    /// True when the picture is framed by coordinate rulers (labelled in full-resolution
760    /// pixels), with a scale bar when the pixel size is known.
761    #[serde(default)]
762    pub axes: bool,
763    /// True when grid lines were drawn over the data at the ruler ticks.
764    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
765    pub grid: bool,
766    /// The data's rectangle inside the PNG, in PNG pixels (the whole PNG without rulers).
767    #[serde(default)]
768    pub plot_area: openreadout_core::Region,
769    /// Full-resolution source coordinate of the plot area's top-left corner.
770    #[serde(default)]
771    pub source_origin: SourcePoint,
772    /// Full-resolution source pixels per PNG pixel, horizontally (pyramid level scale ×
773    /// `downsample`).
774    #[serde(default)]
775    pub source_per_pixel: f64,
776    /// Full-resolution source pixels per PNG pixel, vertically (equal to `source_per_pixel` up
777    /// to the rounding of pyramid level sizes).
778    #[serde(default)]
779    pub source_per_pixel_y: f64,
780    /// The full-resolution (level 0) rectangle the plot area shows: pass it, or a part of it,
781    /// back as `region` to zoom.
782    #[serde(default)]
783    pub full_res_region: openreadout_core::Region,
784    /// Where the power-spectrum inset is drawn (`fft`), in PNG pixels.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub fft_inset: Option<openreadout_core::Region>,
787    /// The scale bar drawn, when the physical pixel size is known.
788    #[serde(default, skip_serializing_if = "Option::is_none")]
789    pub scale_bar: Option<ScaleBar>,
790    /// The plane of the volume shown, when it is not the stored planes: `axial`, `coronal`,
791    /// `sagittal`, `orthogonal`, `xz` or `yz`. Rulers, regions and annotations then count the
792    /// pixels of that view.
793    #[serde(default, skip_serializing_if = "Option::is_none")]
794    pub view: Option<String>,
795    /// Orthogonal views: the voxel (x, y, z of the stored planes) the three planes cross at.
796    #[serde(default, skip_serializing_if = "Option::is_none")]
797    pub crosshair: Option<[u32; 3]>,
798    /// With a view: how many slices it has (the range of `z`).
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub view_slices: Option<u32>,
801}
802
803impl ImagePreview {
804    /// How to turn a pixel of a picture without rulers into full-resolution coordinates, for
805    /// a `region`: its pixels are not source pixels once the plane is scaled or framed.
806    pub fn pixel_mapping(&self) -> String {
807        let n = |v: f64| {
808            let s = format!("{v:.3}");
809            s.trim_end_matches('0').trim_end_matches('.').to_string()
810        };
811        let term = |origin: f64, edge: u32, per: f64, p: &str| {
812            let at = if edge == 0 {
813                p.to_string()
814            } else {
815                format!("({p} − {edge})")
816            };
817            if origin == 0.0 {
818                format!("{at} × {}", n(per))
819            } else {
820                format!("{} + {at} × {}", n(origin), n(per))
821            }
822        };
823        format!(
824            "this picture has no rulers: picture pixel (px, py) is full-res x = {}, y = {}",
825            term(
826                self.source_origin.x,
827                self.plot_area.x,
828                self.source_per_pixel,
829                "px"
830            ),
831            term(
832                self.source_origin.y,
833                self.plot_area.y,
834                self.source_per_pixel_y,
835                "py"
836            ),
837        )
838    }
839
840    /// Update the pixel mapping for a raster halved by [`Raster::half`].
841    fn halve(&mut self) {
842        let (plot, origin, per) = rulers::halve(
843            self.plot_area,
844            self.source_origin,
845            (self.source_per_pixel, self.source_per_pixel_y),
846        );
847        self.plot_area = plot;
848        self.source_origin = origin;
849        (self.source_per_pixel, self.source_per_pixel_y) = per;
850        if let Some(b) = &mut self.scale_bar {
851            b.pixels = b.pixels.div_ceil(2);
852        }
853    }
854}
855
856/// One channel of a trace preview.
857#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
858pub struct TracePreviewChannel {
859    /// Channel index.
860    pub index: u32,
861    /// Channel name.
862    pub name: String,
863    /// Physical unit of the samples.
864    #[serde(skip_serializing_if = "Option::is_none")]
865    pub unit: Option<String>,
866    /// Line colour `#RRGGBB`.
867    pub color: String,
868    /// Bottom of the panel's y axis.
869    #[serde(skip_serializing_if = "Option::is_none")]
870    pub min: Option<f64>,
871    /// Top of the panel's y axis.
872    #[serde(skip_serializing_if = "Option::is_none")]
873    pub max: Option<f64>,
874}
875
876/// The horizontal axis of a trace or spectrum preview.
877#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
878pub struct XAxis {
879    /// `time`, `chemical_shift`, `mz`, `sample`, … (the reader's `extra.axis.quantity` when set).
880    pub quantity: String,
881    /// `s`, `min`, `ppm`, `m/z`, … (empty for sample indices).
882    pub unit: String,
883    /// Value at the left edge.
884    pub first: f64,
885    /// Value at the right edge (smaller than `first` for NMR chemical shift, which runs right to left).
886    pub last: f64,
887}
888
889/// Details of a trace preview.
890#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
891pub struct TracePreview {
892    /// Trace index.
893    pub trace: u32,
894    /// Sweep index.
895    pub sweep: u32,
896    /// Samples per second.
897    pub sample_rate_hz: f64,
898    /// Samples in the sweep.
899    pub sweep_sample_count: u64,
900    /// Samples drawn (from the start of the sweep).
901    pub sample_count: u64,
902    /// True when the sweep is longer than the samples drawn.
903    pub truncated: bool,
904    /// Label of the horizontal axis, when known.
905    #[serde(skip_serializing_if = "Option::is_none")]
906    pub x_axis: Option<XAxis>,
907    /// One panel per channel, top to bottom (one shared panel for overlays).
908    pub channels: Vec<TracePreviewChannel>,
909}
910
911/// Details of a mass-spectrum preview.
912#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
913pub struct SpectrumPreview {
914    /// Run index.
915    pub run: u32,
916    /// Zero-based spectrum index.
917    pub index: u64,
918    /// Scan number as the instrument counts it.
919    pub scan_number: u64,
920    /// MS level (1 = full scan, 2 = fragment scan, ...).
921    pub ms_level: u32,
922    /// Retention time in seconds; null when the file states none.
923    pub rt_s: Option<f64>,
924    /// `sticks` (centroided) or `profile` (a line through the points).
925    pub style: String,
926    /// Points in the spectrum.
927    pub point_count: u64,
928    /// m/z range of the x axis.
929    pub x_axis: XAxis,
930    /// Largest intensity.
931    #[serde(skip_serializing_if = "Option::is_none")]
932    pub max_intensity: Option<f64>,
933    /// Precursor m/z of a fragment (MS2+) scan.
934    #[serde(skip_serializing_if = "Option::is_none")]
935    pub precursor_mz: Option<f64>,
936}
937
938/// Details of a chromatogram preview of a mass-spectrometry run (its first look).
939#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
940pub struct ChromatogramPreview {
941    /// Run index.
942    pub run: u32,
943    /// `tic` (the total ion current each scan header records) or `bpc` (base-peak intensity).
944    pub signal: String,
945    /// MS1 scans drawn.
946    pub ms1_scans: u64,
947    /// Scans in the run (all MS levels).
948    pub scans: u64,
949    /// Retention time of the tallest point, minutes.
950    pub apex_rt_min: f64,
951    /// Its intensity.
952    pub apex_intensity: f64,
953}
954
955/// One layout group of a plate preview (a SoftMax Pro group, a sample name, …).
956#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
957pub struct PlateGroup {
958    /// Group name as the file records it.
959    pub name: String,
960    /// Colour it is drawn in, `#RRGGBB`.
961    pub color: String,
962    /// Wells in the group.
963    pub wells: u32,
964    /// True for blank wells (drawn faint).
965    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
966    pub blank: bool,
967}
968
969/// Details of a plate preview.
970#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
971pub struct PlatePreview {
972    /// Table index.
973    pub table: u32,
974    /// `wide` (one column per well) or `long` (`well` or `row` + `column` columns).
975    pub layout: String,
976    /// `heatmap` (one value per well) or `curves` (a kinetic read, one small plot per well).
977    pub view: String,
978    /// Plate geometry, e.g. 8 × 12.
979    pub rows: u32,
980    /// Plate columns (e.g. 12 for a 96-well plate).
981    pub columns: u32,
982    /// Wells with a finite value.
983    pub wells: u32,
984    /// What each cell shows (a column name, or `mean of N rows`).
985    pub value: String,
986    /// Heat map: value at the light end of the colour scale; curves: bottom of every card's y
987    /// axis.
988    #[serde(skip_serializing_if = "Option::is_none")]
989    pub min: Option<f64>,
990    /// Heat map: value at the dark end of the colour scale; curves: top of every card's y axis.
991    #[serde(skip_serializing_if = "Option::is_none")]
992    pub max: Option<f64>,
993    /// Curves: the time axis every card shares, in `time_unit`.
994    #[serde(default, skip_serializing_if = "Option::is_none")]
995    pub time: Option<[f64; 2]>,
996    /// Curves: `s`, `min` or `h`.
997    #[serde(default, skip_serializing_if = "Option::is_none")]
998    pub time_unit: Option<String>,
999    /// The layout field the colours follow (e.g. `SoftMax group`).
1000    #[serde(default, skip_serializing_if = "Option::is_none")]
1001    pub grouped_by: Option<String>,
1002    /// The groups, in the order of the key.
1003    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1004    pub groups: Vec<PlateGroup>,
1005}
1006
1007/// Details of an event (flow cytometry) preview.
1008#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1009pub struct EventsPreview {
1010    /// Table index.
1011    pub table: u32,
1012    /// Parameter on the x axis.
1013    pub x: String,
1014    /// Parameter on the y axis (absent for a histogram).
1015    #[serde(default, skip_serializing_if = "Option::is_none")]
1016    pub y: Option<String>,
1017    /// Events drawn.
1018    pub events: u64,
1019    /// Events in the table.
1020    pub total_events: u64,
1021    /// `linear` or `asinh` (each axis, x first).
1022    pub scales: Vec<String>,
1023}
1024
1025/// One plot panel inside the picture, for mapping PNG pixels to data values and back: the
1026/// value at the panel's left edge is `x[0]`, at its right edge `x[1]`, at its bottom `y[0]`
1027/// and at its top `y[1]`, along the scale named in `x_scale` / `y_scale`.
1028#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1029pub struct PlotPanel {
1030    /// The panel's rectangle in PNG pixels.
1031    pub plot_area: PxRect,
1032    /// Values at the left and right edges.
1033    pub x: [f64; 2],
1034    /// Values at the bottom and top edges.
1035    pub y: [f64; 2],
1036    /// `linear`, `log` or `asinh`.
1037    pub x_scale: String,
1038    /// `linear`, `log` or `asinh`.
1039    pub y_scale: String,
1040    /// Trace previews: the channel drawn in this panel.
1041    #[serde(default, skip_serializing_if = "Option::is_none")]
1042    pub channel: Option<u32>,
1043    /// Plate curve previews: the well of this card.
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    pub well: Option<String>,
1046}
1047
1048/// A rectangle in PNG pixels (fractional).
1049#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
1050pub struct PxRect {
1051    /// Left edge.
1052    pub x: f64,
1053    /// Top edge.
1054    pub y: f64,
1055    /// Width.
1056    pub width: f64,
1057    /// Height.
1058    pub height: f64,
1059}
1060
1061impl From<openreadout_figure::Rect> for PxRect {
1062    fn from(r: openreadout_figure::Rect) -> Self {
1063        let q = |v: f32| (f64::from(v) * 100.0).round() / 100.0;
1064        PxRect {
1065            x: q(r.x),
1066            y: q(r.y),
1067            width: q(r.w),
1068            height: q(r.h),
1069        }
1070    }
1071}
1072
1073/// A mark drawn from the data: a labelled peak or a detected action potential.
1074#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1075pub struct DataMark {
1076    /// `peak`, `spike`, `resolution_ring` (x: resolution in Å, y: radius in full-resolution
1077    /// pixels) or `beam_center` (x, y: full-resolution pixels).
1078    pub kind: String,
1079    /// Position along the x axis, in its unit.
1080    pub x: f64,
1081    /// Value there, in the panel's unit.
1082    pub y: f64,
1083    /// The label drawn (e.g. the m/z or ppm), if any.
1084    #[serde(default, skip_serializing_if = "Option::is_none")]
1085    pub label: Option<String>,
1086    /// Trace previews: the channel.
1087    #[serde(default, skip_serializing_if = "Option::is_none")]
1088    pub channel: Option<u32>,
1089}
1090
1091/// Output of `preview`: what was rendered, and where it went.
1092#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1093pub struct PreviewOutput {
1094    /// The input file.
1095    pub path: String,
1096    /// Format id of the input file.
1097    pub format: String,
1098    /// `image`, `trace`, `chromatogram`, `spectrum`, `plate` or `events`.
1099    pub kind: String,
1100    /// The written file (CLI); absent when the preview is returned inline (MCP image content).
1101    #[serde(skip_serializing_if = "Option::is_none")]
1102    pub output: Option<String>,
1103    /// `png`, `jpeg` or `svg`.
1104    pub encoding: String,
1105    /// Image width in pixels.
1106    pub width: u32,
1107    /// Image height in pixels.
1108    pub height: u32,
1109    /// Size of the encoded image.
1110    pub bytes: u64,
1111    /// xxh3-128 of the encoded bytes, 32 hex chars (identical across runs for the same request).
1112    pub xxh3: String,
1113    /// True once a written file was read back and matched.
1114    pub verified: bool,
1115    /// Present for image previews.
1116    #[serde(skip_serializing_if = "Option::is_none")]
1117    pub image: Option<ImagePreview>,
1118    /// Present for trace previews.
1119    #[serde(skip_serializing_if = "Option::is_none")]
1120    pub trace: Option<TracePreview>,
1121    /// Present for spectrum previews.
1122    #[serde(skip_serializing_if = "Option::is_none")]
1123    pub spectrum: Option<SpectrumPreview>,
1124    /// Present for chromatogram previews (a mass-spectrometry run's total-ion chromatogram).
1125    #[serde(default, skip_serializing_if = "Option::is_none")]
1126    pub chromatogram: Option<ChromatogramPreview>,
1127    /// Present for plate previews.
1128    #[serde(skip_serializing_if = "Option::is_none")]
1129    pub plate: Option<PlatePreview>,
1130    /// Present for event previews.
1131    #[serde(skip_serializing_if = "Option::is_none")]
1132    pub events: Option<EventsPreview>,
1133    /// Plot panels (traces, spectra, plate curves, events): where each sits in the picture and
1134    /// the data range it shows.
1135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1136    pub panels: Vec<PlotPanel>,
1137    /// Marks drawn from the data (labelled peaks, action potentials).
1138    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1139    pub marks: Vec<DataMark>,
1140    /// `marks: objects`: the objects counted in the area shown, as `stats` objects (the first
1141    /// 20 listed).
1142    #[serde(default, skip_serializing_if = "Option::is_none")]
1143    #[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
1144    pub objects: Option<openreadout_core::measure::Objects>,
1145    /// `marks: lanes`: the lanes and bands found in the area shown, as `stats` lanes.
1146    #[serde(default, skip_serializing_if = "Option::is_none")]
1147    #[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
1148    pub lanes: Option<openreadout_core::measure::Lanes>,
1149    /// The caller's annotations as drawn: each as given, plus where it landed in PNG pixels.
1150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1151    pub annotations: Vec<DrawnAnnotation>,
1152    /// Anything the caller should know (fallbacks, caps, implied options).
1153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1154    pub notes: Vec<String>,
1155    /// What to do next with the picture (look at it; zoom with a region read off the rulers).
1156    #[serde(default, skip_serializing_if = "Option::is_none")]
1157    pub hint: Option<String>,
1158    /// How to save this picture to a file (MCP: the openreadout_export call).
1159    #[serde(default, skip_serializing_if = "Option::is_none")]
1160    pub save: Option<String>,
1161}
1162
1163impl PreviewOutput {
1164    /// Halve the recorded geometry along with the raster.
1165    fn halved(&mut self) {
1166        if let Some(im) = &mut self.image {
1167            im.halve();
1168        }
1169        let h = |r: &mut PxRect| {
1170            r.x /= 2.0;
1171            r.y /= 2.0;
1172            r.width /= 2.0;
1173            r.height /= 2.0;
1174        };
1175        for p in &mut self.panels {
1176            h(&mut p.plot_area);
1177        }
1178        for a in &mut self.annotations {
1179            a.halve();
1180        }
1181    }
1182}
1183
1184/// How figure pixels relate to data: what the annotations are placed in.
1185#[derive(Debug, Clone)]
1186pub(crate) enum Frame {
1187    /// An image: the plot area and the full-resolution mapping.
1188    Image {
1189        plot_area: openreadout_core::Region,
1190        map: rulers::Mapping,
1191    },
1192    /// Plot panels, each with the channel or well it shows, and where the figure's key may
1193    /// take more entries (a plate grid's annotations are labelled there).
1194    Plots {
1195        panels: Vec<FramePanel>,
1196        key: Option<KeySlot>,
1197        /// Labels the preview drew itself (peak labels), which the caller's labels keep off.
1198        taken: Vec<openreadout_figure::Rect>,
1199    },
1200    /// A plate heat map: each well's cell.
1201    Wells(Vec<((u32, u32), openreadout_figure::Rect)>),
1202}
1203
1204impl Frame {
1205    /// Plot panels without a key.
1206    pub(crate) fn plots(panels: Vec<FramePanel>) -> Frame {
1207        Frame::Plots {
1208            panels,
1209            key: None,
1210            taken: Vec::new(),
1211        }
1212    }
1213
1214    /// Plot panels whose own labels occupy `taken`.
1215    pub(crate) fn plots_labelled(
1216        panels: Vec<FramePanel>,
1217        taken: &[openreadout_figure::Rect],
1218    ) -> Frame {
1219        Frame::Plots {
1220            panels,
1221            key: None,
1222            taken: taken.to_vec(),
1223        }
1224    }
1225}
1226
1227/// Room at the end of a figure's key row: the next entry starts at `x`, centred on `y`, and
1228/// must end before `max_x`.
1229#[derive(Debug, Clone, Copy, PartialEq)]
1230pub(crate) struct KeySlot {
1231    pub x: f32,
1232    pub y: f32,
1233    pub max_x: f32,
1234}
1235
1236/// A plot panel and what it shows.
1237#[derive(Debug, Clone)]
1238pub(crate) struct FramePanel {
1239    pub panel: openreadout_figure::Panel,
1240    pub channel: Option<u32>,
1241    pub well: Option<(u32, u32)>,
1242}
1243
1244impl FramePanel {
1245    pub(crate) fn new(panel: openreadout_figure::Panel) -> Self {
1246        FramePanel {
1247            panel,
1248            channel: None,
1249            well: None,
1250        }
1251    }
1252}
1253
1254/// A rendered preview before encoding.
1255#[derive(Debug, Clone)]
1256pub struct Rendered {
1257    /// The rendered pixels.
1258    pub canvas: Raster,
1259    /// The figure the pixels were rendered from (for SVG output).
1260    pub figure: Figure,
1261    /// What was rendered (without the encoding fields filled in).
1262    pub output: PreviewOutput,
1263}
1264
1265impl Rendered {
1266    /// Give this picture the pixels of `big`, the same image read at `scale` times the size,
1267    /// so that saving it at `scale` draws a sharper version of this picture: type, lines,
1268    /// outlines and labels keep their size relative to the image, and the image has real
1269    /// pixels. Returns false (and changes nothing) when `big` has no image of about that size.
1270    pub fn take_pixels(&mut self, big: &Rendered, scale: f32) -> bool {
1271        use openreadout_figure::Item;
1272        fn largest(f: &Figure) -> Option<usize> {
1273            f.items
1274                .iter()
1275                .enumerate()
1276                .filter_map(|(i, it)| match it {
1277                    Item::Image { rect, .. } => Some((i, rect.w * rect.h)),
1278                    _ => None,
1279                })
1280                .max_by(|a, b| a.1.total_cmp(&b.1))
1281                .map(|x| x.0)
1282        }
1283        let (Some(i), Some(j)) = (largest(&self.figure), largest(&big.figure)) else {
1284            return false;
1285        };
1286        let Item::Image { raster, .. } = &big.figure.items[j] else {
1287            return false;
1288        };
1289        let raster = raster.clone();
1290        let Item::Image {
1291            rect,
1292            raster: mine,
1293            smooth,
1294        } = &mut self.figure.items[i]
1295        else {
1296            return false;
1297        };
1298        // the same region (the same shape), with more pixels than this picture shows. The
1299        // larger picture's frame does not grow in proportion, so its image is near, not exactly
1300        // at, `scale` times the size; it is then resampled smoothly to the saved size.
1301        let (w, h) = (raster.width as f32, raster.height as f32);
1302        let same_shape = (w / h - rect.w / rect.h).abs() <= 0.02 * rect.w / rect.h;
1303        if !same_shape || w <= mine.width as f32 {
1304            return false;
1305        }
1306        if (w - rect.w * scale).abs() > 1.0 {
1307            *smooth = true;
1308        }
1309        *mine = raster;
1310        true
1311    }
1312}
1313
1314/// Split combined selections: `["c=0,1,z=2"]` → `["c=0,1", "z=2"]` (a comma followed by
1315/// `axis=` starts a new selection). Plain repeatable `c=0` arguments pass through.
1316pub fn split_select(args: &[String]) -> Vec<String> {
1317    let mut out: Vec<String> = Vec::new();
1318    for a in args {
1319        let mut cur = String::new();
1320        for part in a.split(',') {
1321            if part.contains('=') && !cur.is_empty() {
1322                out.push(std::mem::take(&mut cur));
1323            }
1324            if !cur.is_empty() {
1325                cur.push(',');
1326            }
1327            cur.push_str(part.trim());
1328        }
1329        if !cur.is_empty() {
1330            out.push(cur);
1331        }
1332    }
1333    out
1334}
1335
1336/// Which kind of preview a request asks for.
1337fn kind(info: &FileInfo, req: &PreviewRequest) -> Result<&'static str> {
1338    if req.table.is_some() || !req.columns.is_empty() {
1339        return Ok(if events::is_events(info, req.table.unwrap_or(0)) {
1340            "events"
1341        } else {
1342            "plate"
1343        });
1344    }
1345    if req.trace.is_some()
1346        || req.sweep.is_some()
1347        || !req.channels.is_empty()
1348        || req.x_range.is_some()
1349    {
1350        return Ok("trace");
1351    }
1352    if req.run.is_some() || req.spectrum.is_some() || req.scan.is_some() || req.centroid {
1353        return Ok("spectrum");
1354    }
1355    // Mass-spectrometry files also carry chromatograms (TIC, BPC) as traces: prefer them when
1356    // they are long enough to show a run, else a spectrum says more.
1357    let short_traces = info
1358        .traces
1359        .iter()
1360        .all(|t| t.sample_count < MIN_TRACE_SAMPLES_OVER_SPECTRUM);
1361    if !info.images.is_empty() {
1362        Ok("image")
1363    } else if !info.traces.is_empty() && (!short_traces || info.spectra.is_empty()) {
1364        Ok("trace")
1365    } else if !info.spectra.is_empty() {
1366        Ok("spectrum")
1367    } else if !info.tables.is_empty() {
1368        Ok(if events::is_events(info, 0) {
1369            "events"
1370        } else {
1371            "plate"
1372        })
1373    } else {
1374        Err(Error::unsupported(
1375            "preview",
1376            format!("preview of a {} file", info.format.name),
1377            "This file holds no images, traces, spectra or tables to draw; see `openreadout info`.",
1378        ))
1379    }
1380}
1381
1382/// Most annotations one picture takes.
1383pub const MAX_ANNOTATIONS: usize = 500;
1384/// Most trace channels one picture draws.
1385pub const MAX_CHANNELS: usize = 64;
1386/// Longest title, in characters.
1387pub const MAX_TITLE_CHARS: usize = 300;
1388/// Longest caption, in characters.
1389pub const MAX_CAPTION_CHARS: usize = 2000;
1390
1391/// Refuse requests too large to draw: many annotations or channels, long titles and captions.
1392fn check_limits(req: &PreviewRequest) -> Result<()> {
1393    if req.max_size < 16 || req.max_size > MAX_PREVIEW_SIZE {
1394        return Err(Error::Usage(format!(
1395            "max size {} is out of range: use 16 to {MAX_PREVIEW_SIZE}",
1396            req.max_size
1397        )));
1398    }
1399    let over = |what: &str, n: usize, max: usize, how: &str| {
1400        Err(Error::Usage(format!(
1401            "{n} {what} are over the limit of {max}; {how}"
1402        )))
1403    };
1404    if req.annotations.len() > MAX_ANNOTATIONS {
1405        return over(
1406            "annotations",
1407            req.annotations.len(),
1408            MAX_ANNOTATIONS,
1409            "mark the most telling ones, or zoom in with region and annotate each part",
1410        );
1411    }
1412    let mut channels = req.channels.clone();
1413    channels.sort_unstable();
1414    channels.dedup();
1415    if channels.len() > MAX_CHANNELS {
1416        return over(
1417            "channels",
1418            channels.len(),
1419            MAX_CHANNELS,
1420            "draw fewer channels per picture",
1421        );
1422    }
1423    for (what, text, max) in [
1424        ("title", &req.title, MAX_TITLE_CHARS),
1425        ("caption", &req.caption, MAX_CAPTION_CHARS),
1426    ] {
1427        let n = text.as_deref().map_or(0, |t| t.chars().count());
1428        if n > max {
1429            return Err(Error::Usage(format!(
1430                "a {what} of {n} characters is over the limit of {max}; shorten it, and give the full text in your reply"
1431            )));
1432        }
1433    }
1434    Ok(())
1435}
1436
1437/// Render a preview (no encoding yet).
1438pub fn render(ds: &mut dyn Dataset, info: &FileInfo, req: &PreviewRequest) -> Result<Rendered> {
1439    check_limits(req)?;
1440    let k = kind(info, req)?;
1441    let mut out = PreviewOutput {
1442        path: info.path.clone(),
1443        format: info.format.id.clone(),
1444        kind: k.into(),
1445        ..PreviewOutput::default()
1446    };
1447    let objects_req = (k == "image")
1448        .then(|| objects::show_counted_channel(info, req, &mut out.notes))
1449        .flatten();
1450    let req = objects_req.as_ref().unwrap_or(req);
1451    // An NMR data set shows its spectrum unless the caller picked a trace, sweep or channel.
1452    let nmr_default = k == "trace"
1453        && info.format.family == "nmr"
1454        && req.trace.is_none()
1455        && req.sweep.is_none()
1456        && req.channels.is_empty();
1457    // A sequencing data set shows its own view (run quality, a read's squiggle, read lengths)
1458    // unless the caller picked a table, a trace other than a nanopore read, or channels.
1459    let seq_default = info.format.family == "sequencing"
1460        && req.table.is_none()
1461        && req.columns.is_empty()
1462        && req.channels.is_empty()
1463        && req.trace.is_none_or(|t| t == 0);
1464    let mut drawn = if nmr_default {
1465        nmr::render(ds, info, req, &mut out)
1466    } else if seq_default {
1467        sequencing::render(ds, info, req, &mut out)
1468    } else {
1469        None
1470    };
1471    // A Sanger read or a sized fragment run shows its chromatogram or electropherogram.
1472    if drawn.is_none() && k == "trace" && info.format.family == "electrophoresis" {
1473        drawn = electrophoresis::render(ds, info, req, &mut out)?;
1474    }
1475    // A mass-spectrometry run shows its chromatogram unless a spectrum was asked for.
1476    if drawn.is_none()
1477        && k == "spectrum"
1478        && req.run.is_none()
1479        && req.spectrum.is_none()
1480        && req.scan.is_none()
1481        && !req.centroid
1482    {
1483        drawn = tic::render(ds, info, req, &mut out)?;
1484        if drawn.is_some() {
1485            out.kind = "chromatogram".into();
1486        }
1487    }
1488    if drawn.is_none() && samples::applies(info, req) {
1489        drawn = Some(samples::render(ds, info, req, &mut out)?);
1490        out.kind = "samples".into();
1491    }
1492    let (mut figure, frame) = match (k, drawn) {
1493        (_, Some(drawn)) => drawn,
1494        ("image", _) => render_image(ds, info, req, &mut out)?,
1495        ("trace", _) if electrochem::is_voltammetry(info, req) => {
1496            electrochem::render(ds, info, req, &mut out)?
1497        }
1498        ("trace", _) => trace::render(ds, info, req, &mut out)?,
1499        ("spectrum", _) => spectrum::render(ds, info, req, &mut out)?,
1500        ("events", _) => events::render(ds, info, req, &mut out)?,
1501        _ => plate::render(ds, info, req, &mut out)?,
1502    };
1503    if out.kind != "image" && (req.title.is_some() || req.caption.is_some()) {
1504        out.notes.push(
1505            "title and caption are drawn on image previews; openreadout_plot titles and captions plots"
1506                .into(),
1507        );
1508    }
1509    if let Frame::Plots { panels, .. } = &frame {
1510        out.panels = panels.iter().map(annotate::plot_panel).collect();
1511    }
1512    if k == "image" && (req.marks == Marks::Objects || req.objects.is_some()) {
1513        objects::draw(ds, info, req, &frame, &mut figure, &mut out)?;
1514    }
1515    if k == "image" && (req.marks == Marks::Lanes || req.lanes.is_some()) {
1516        lanes::draw(ds, info, req, &frame, &mut figure, &mut out);
1517    }
1518    if !req.annotations.is_empty() {
1519        let theme = theme(req);
1520        out.annotations = annotate::draw(
1521            &mut figure,
1522            &frame,
1523            &req.annotations,
1524            &theme,
1525            &mut out.notes,
1526        )?;
1527    }
1528    figure.title = Some(title(&out));
1529    let mut canvas = figure.to_raster(1.0);
1530    // Plots and heat maps have a minimum legible layout; below it, shrink to honour `max_size`.
1531    while canvas.width.max(canvas.height) > req.max_size {
1532        canvas = canvas.half();
1533        out.halved();
1534        out.notes.push(format!(
1535            "layout larger than max size {}; halved to {}x{}",
1536            req.max_size, canvas.width, canvas.height
1537        ));
1538    }
1539    Ok(Rendered {
1540        canvas,
1541        figure,
1542        output: out,
1543    })
1544}
1545
1546/// A one-line description of the picture (the SVG title).
1547fn title(o: &PreviewOutput) -> String {
1548    let name = Path::new(&o.path)
1549        .file_name()
1550        .map_or_else(|| o.path.clone(), |n| n.to_string_lossy().to_string());
1551    format!("{} preview of {name}", o.kind)
1552}
1553
1554/// Encode a raster as PNG (8-bit greyscale when every pixel is grey, else RGB) or JPEG. SVG
1555/// needs the figure: use [`finish`].
1556pub fn encode(c: &Raster, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
1557    match encoding {
1558        Encoding::Jpeg => c.to_jpeg(jpeg_quality),
1559        Encoding::Png => c.to_png(),
1560        Encoding::Svg => Err(Error::Usage(
1561            "SVG is drawn from the figure, not a raster; use finish()".into(),
1562        )),
1563    }
1564}
1565
1566/// Encode a figure at its own size: PNG, JPEG or SVG.
1567pub fn encode_figure(f: &Figure, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
1568    match encoding {
1569        Encoding::Svg => Ok(f.to_svg().into_bytes()),
1570        e => encode(&f.to_raster(1.0), e, jpeg_quality),
1571    }
1572}
1573
1574fn xxh3_hex(b: &[u8]) -> String {
1575    format!("{:032x}", xxhash_rust::xxh3::xxh3_128(b))
1576}
1577
1578/// Encode a rendered preview and fill in the size, encoding and hash.
1579pub fn finish(
1580    r: &Rendered,
1581    encoding: Encoding,
1582    jpeg_quality: u8,
1583) -> Result<(PreviewOutput, Vec<u8>)> {
1584    let bytes = match encoding {
1585        Encoding::Svg => r.figure.to_svg().into_bytes(),
1586        e => encode(&r.canvas, e, jpeg_quality)?,
1587    };
1588    let mut out = r.output.clone();
1589    out.encoding = encoding.as_str().into();
1590    out.width = r.canvas.width;
1591    out.height = r.canvas.height;
1592    out.bytes = bytes.len() as u64;
1593    out.xxh3 = xxh3_hex(&bytes);
1594    Ok((out, bytes))
1595}
1596
1597/// Encode within a byte budget (for inline MCP image content): the requested encoding first,
1598/// then JPEG at quality 85, then halving the image until it fits. `encoding` in the output
1599/// says when the image became a JPEG. Halving adds one note, worded for the person looking
1600/// at the picture.
1601pub fn finish_within(
1602    r: &Rendered,
1603    encoding: Encoding,
1604    jpeg_quality: u8,
1605    max_bytes: usize,
1606) -> Result<(PreviewOutput, Vec<u8>)> {
1607    let (mut out, mut bytes) = finish(r, encoding, jpeg_quality)?;
1608    if bytes.len() <= max_bytes {
1609        return Ok((out, bytes));
1610    }
1611    let mut cur = r.clone();
1612    let mut enc = encoding;
1613    if enc != Encoding::Jpeg {
1614        enc = Encoding::Jpeg;
1615        (out, bytes) = finish(&cur, enc, 85)?;
1616    }
1617    let mut halved = false;
1618    while bytes.len() > max_bytes && cur.canvas.width.max(cur.canvas.height) > 32 {
1619        cur.canvas = cur.canvas.half();
1620        cur.output.halved();
1621        (out, bytes) = finish(&cur, enc, 85)?;
1622        halved = true;
1623    }
1624    if halved {
1625        out.notes.push(format!(
1626            "shown at reduced resolution ({}x{} px); preview a region for full detail",
1627            cur.canvas.width, cur.canvas.height
1628        ));
1629    }
1630    Ok((out, bytes))
1631}
1632
1633/// A small look at a file's first image for a summary ("auto-screenshot"): channel 0 (or a
1634/// composite of 2–4 channels), middle z, t 0, from the smallest pyramid level that still covers
1635/// `max_size`, with rulers. Fails (`unsupported`) instead of decoding more than `max_read_bytes`
1636/// of pixels, and on any read error: the caller skips the thumbnail and points to [`render`]
1637/// with a region or level.
1638pub fn thumbnail(
1639    ds: &mut dyn Dataset,
1640    info: &FileInfo,
1641    max_size: u32,
1642    max_read_bytes: u64,
1643) -> Result<Rendered> {
1644    let im = info.images.first().ok_or_else(|| {
1645        Error::unsupported(
1646            "preview",
1647            "thumbnail of a file without images",
1648            "Use `preview` for traces, spectra and plates.",
1649        )
1650    })?;
1651    let mut req = PreviewRequest {
1652        image: Some(im.index),
1653        max_size,
1654        max_read_bytes: Some(max_read_bytes),
1655        composite: im.samples_per_pixel != 3 && (2..=4).contains(&im.size_c),
1656        ..PreviewRequest::default()
1657    };
1658    match render(ds, info, &req) {
1659        // a composite reads one plane per channel: one channel may still fit the budget
1660        Err(Error::Unsupported { .. }) if req.composite => {
1661            req.composite = false;
1662            render(ds, info, &req)
1663        }
1664        other => other,
1665    }
1666}
1667
1668/// Default output path: `<input stem>.preview.<png|jpg|svg>` next to the input.
1669pub fn default_output(input: &Path, encoding: Encoding) -> PathBuf {
1670    let stem = input
1671        .file_stem()
1672        .map_or_else(|| "preview".into(), |s| s.to_string_lossy().to_string());
1673    input.with_file_name(format!("{stem}.preview.{}", encoding.extension()))
1674}
1675
1676/// Write `bytes` to `output` through a temporary file that is read back and compared before it is
1677/// renamed into place. Refuses to replace an existing file unless `overwrite`, and refuses to
1678/// write over the input however its path is spelled. Returns `true` (verified).
1679pub fn write_verified(input: &Path, output: &Path, bytes: &[u8], overwrite: bool) -> Result<bool> {
1680    openreadout_core::output::write_verified(output, bytes, overwrite, &[input])?;
1681    Ok(true)
1682}
1683
1684#[cfg(test)]
1685mod tests {
1686    use super::*;
1687
1688    /// Saving at a larger scale keeps the picture as drawn and takes only the image's pixels
1689    /// from the larger reading, so type and outlines grow with the save.
1690    #[test]
1691    fn a_scaled_save_takes_only_the_pixels() {
1692        use std::sync::Arc;
1693        let picture = |w: u32, h: u32, rect: openreadout_figure::Rect| {
1694            let mut figure = Figure::new(rect.w + 20.0, rect.h + 20.0, None);
1695            figure.image(rect, Arc::new(Raster::new(w, h, [9, 9, 9])), false);
1696            figure.text(
1697                5.0,
1698                5.0,
1699                "12 nuclei",
1700                &openreadout_figure::TextStyle::new(12.0, openreadout_figure::Color::rgb(0, 0, 0)),
1701            );
1702            Rendered {
1703                canvas: Raster::new(1, 1, [0, 0, 0]),
1704                figure,
1705                output: PreviewOutput::default(),
1706            }
1707        };
1708        let mut small = picture(
1709            100,
1710            50,
1711            openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
1712        );
1713        let big = picture(
1714            300,
1715            150,
1716            openreadout_figure::Rect::new(10.0, 10.0, 300.0, 150.0),
1717        );
1718        assert!(small.take_pixels(&big, 3.0));
1719        assert_eq!(small.figure.width, 120.0, "the layout stays the small one");
1720        let sizes: Vec<(u32, u32)> = small
1721            .figure
1722            .items
1723            .iter()
1724            .filter_map(|i| match i {
1725                openreadout_figure::Item::Image { raster, .. } => {
1726                    Some((raster.width, raster.height))
1727                }
1728                _ => None,
1729            })
1730            .collect();
1731        assert_eq!(sizes, vec![(300, 150)]);
1732        let mut other = picture(
1733            100,
1734            50,
1735            openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
1736        );
1737        assert!(!other.take_pixels(
1738            &picture(
1739                120,
1740                50,
1741                openreadout_figure::Rect::new(0.0, 0.0, 120.0, 50.0)
1742            ),
1743            3.0
1744        ));
1745    }
1746
1747    #[test]
1748    fn parses_options() {
1749        assert_eq!("auto".parse::<Contrast>().unwrap(), Contrast::Auto);
1750        assert_eq!(
1751            "percentile:1,99".parse::<Contrast>().unwrap(),
1752            Contrast::Percentile(1.0, 99.0)
1753        );
1754        assert!("percentile:99,1".parse::<Contrast>().is_err());
1755        assert!("bright".parse::<Contrast>().is_err());
1756        assert_eq!("channel-color".parse::<Lut>().unwrap(), Lut::ChannelColor);
1757        assert_eq!("Z".parse::<Axis>().unwrap(), Axis::Z);
1758        assert_eq!("spikes".parse::<Marks>().unwrap(), Marks::Spikes);
1759        assert_eq!(Encoding::from_path(Path::new("a.JPG")), Encoding::Jpeg);
1760        assert_eq!(Encoding::from_path(Path::new("a.svg")), Encoding::Svg);
1761        assert_eq!(Encoding::from_path(Path::new("a")), Encoding::Png);
1762    }
1763
1764    #[test]
1765    fn splits_combined_selection() {
1766        assert_eq!(
1767            split_select(&["c=0,1,z=2".into(), "t=3".into()]),
1768            vec!["c=0,1", "z=2", "t=3"]
1769        );
1770        assert_eq!(split_select(&["z=1-3".into()]), vec!["z=1-3"]);
1771    }
1772}