Skip to main content

openreadout_preview/
annotate.rs

1//! The caller's annotations: points, boxes, outlines, arrows, text, lines and bands drawn on a
2//! preview, in the preview's own coordinates (full-resolution pixels on images, axis units on
3//! plots, wells on plates). Labels are placed so they do not cover each other, and sit on a
4//! paper pill (images) or carry a halo (plots), so they read on anything.
5
6use openreadout_core::{Error, Result};
7use openreadout_figure::{
8    Anchor, Baseline, Color, Face, Figure, LabelPlacer, Layer, Path, Pill, Rect, ScaleKind, Stroke,
9    TextStyle, Theme, arrow_parts,
10};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::{Frame, FramePanel, KeySlot, PlotPanel, PxRect};
15
16pub use openreadout_core::annotation::{Annotation, AnnotationType};
17
18/// An annotation as drawn: the request, plus where it landed in PNG pixels.
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
20pub struct DrawnAnnotation {
21    /// The annotation as given.
22    #[serde(flatten)]
23    pub annotation: Annotation,
24    /// The colour drawn, `#RRGGBB`.
25    pub drawn_color: String,
26    /// The mark's key points in PNG pixels: the point, the box corners, the vertices, the
27    /// arrow's tail and head, a line's or band's ends (one pair per card on a curve grid).
28    pub px: Vec<[f64; 2]>,
29    /// Where the label went, in PNG pixels.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub label_px: Option<PxRect>,
32    /// True when part of the mark lies outside what the picture shows (it is clipped).
33    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
34    pub outside: bool,
35}
36
37impl DrawnAnnotation {
38    /// Halve the pixel positions along with the raster.
39    pub(crate) fn halve(&mut self) {
40        for p in &mut self.px {
41            p[0] /= 2.0;
42            p[1] /= 2.0;
43        }
44        if let Some(r) = &mut self.label_px {
45            r.x /= 2.0;
46            r.y /= 2.0;
47            r.width /= 2.0;
48            r.height /= 2.0;
49        }
50    }
51}
52
53fn scale_name(k: ScaleKind) -> String {
54    match k {
55        ScaleKind::Linear => "linear".into(),
56        ScaleKind::Log => "log".into(),
57        ScaleKind::Asinh(_) => "asinh".into(),
58    }
59}
60
61/// The JSON description of a plot panel.
62pub(crate) fn plot_panel(p: &FramePanel) -> PlotPanel {
63    let pn = &p.panel;
64    let r = pn.rect;
65    PlotPanel {
66        plot_area: r.into(),
67        x: [pn.x.value(r.x), pn.x.value(r.right())],
68        y: [pn.y.value(r.bottom()), pn.y.value(r.y)],
69        x_scale: scale_name(pn.x.kind),
70        y_scale: scale_name(pn.y.kind),
71        channel: p.channel,
72        well: p.well.map(well_name),
73    }
74}
75
76/// `B3` for row 1, column 2 (zero-based); rows past Z continue AA, AB, …
77pub(crate) fn well_name((r, c): (u32, u32)) -> String {
78    format!("{}{}", row_name(r), c + 1)
79}
80
81/// `A` for row 0; rows past Z continue AA, AB, …
82pub(crate) fn row_name(r: u32) -> String {
83    if r < 26 {
84        char::from(b'A' + r as u8).to_string()
85    } else {
86        format!(
87            "{}{}",
88            char::from(b'A' + ((r / 26 - 1) % 26) as u8),
89            char::from(b'A' + (r % 26) as u8)
90        )
91    }
92}
93
94/// Parse `B3`, `b03`, `AA12` into zero-based (row, column).
95pub(crate) fn parse_well_name(s: &str) -> Option<(u32, u32)> {
96    let s = s.trim();
97    let letters: String = s.chars().take_while(char::is_ascii_alphabetic).collect();
98    let digits = &s[letters.len()..];
99    if letters.is_empty() || letters.len() > 2 || digits.is_empty() {
100        return None;
101    }
102    let up = letters.to_ascii_uppercase();
103    let b = up.as_bytes();
104    let row = if b.len() == 1 {
105        u32::from(b[0] - b'A')
106    } else {
107        (u32::from(b[0] - b'A') + 1) * 26 + u32::from(b[1] - b'A')
108    };
109    let col: u32 = digits.parse().ok()?;
110    (col >= 1).then(|| (row, col - 1))
111}
112
113fn resolve_color(c: Option<&str>, theme: &Theme) -> Result<Color> {
114    match c.map(str::trim) {
115        None | Some("" | "accent") => Ok(theme.accent),
116        Some("ink") => Ok(theme.ink),
117        Some("muted") => Ok(theme.muted),
118        Some("white") => Ok(Color::rgb(255, 255, 255)),
119        Some(s) => Color::parse(s).ok_or_else(|| {
120            Error::Usage(format!(
121                "annotation color '{s}': use accent, ink, muted, white or #RRGGBB"
122            ))
123        }),
124    }
125}
126
127/// A coordinate system the marks are drawn in: data → figure pixels, the area it covers, and
128/// whether labels sit on pills (images) or carry halos (plots).
129struct Space<'a> {
130    to_px: Box<dyn Fn(f64, f64) -> (f32, f32) + 'a>,
131    area: Rect,
132    on_image: bool,
133    /// For lines and bands: the data value at the area's edges is not needed, the area is.
134    x_only: Box<dyn Fn(f64) -> f32 + 'a>,
135    y_only: Box<dyn Fn(f64) -> f32 + 'a>,
136}
137
138fn image_space(plot: openreadout_core::Region, map: crate::rulers::Mapping) -> Space<'static> {
139    let (ox, oy) = (plot.x as f32, plot.y as f32);
140    let m = map;
141    let m2 = map;
142    let m3 = map;
143    Space {
144        to_px: Box::new(move |x, y| {
145            let (px, py) = m.px_of(x, y);
146            (ox + px as f32, oy + py as f32)
147        }),
148        area: Rect::new(ox, oy, plot.width as f32, plot.height as f32),
149        on_image: true,
150        x_only: Box::new(move |x| ox + m2.px_of(x, 0.0).0 as f32),
151        y_only: Box::new(move |y| oy + m3.px_of(0.0, y).1 as f32),
152    }
153}
154
155fn panel_space(p: &FramePanel) -> Space<'_> {
156    let pn = p.panel;
157    // values a log scale cannot place go far off the panel (and are clipped)
158    let far = |v: Option<f32>| v.unwrap_or(-1e5);
159    Space {
160        to_px: Box::new(move |x, y| (far(pn.x.px(x)), far(pn.y.px(y)))),
161        area: pn.rect,
162        on_image: false,
163        x_only: Box::new(move |x| far(pn.x.px(x))),
164        y_only: Box::new(move |y| far(pn.y.px(y))),
165    }
166}
167
168/// How labels look.
169struct Labels {
170    pill: Pill,
171    halo: TextStyle,
172    placer: LabelPlacer,
173}
174
175impl Labels {
176    /// Place and draw `text` near `(x, y)`; returns its box.
177    fn put(
178        &mut self,
179        fig: &mut Figure,
180        on_image: bool,
181        x: f32,
182        y: f32,
183        text: &str,
184        color: Color,
185        gap: f32,
186    ) -> Rect {
187        if on_image {
188            let (w, h) = self.pill.size(text);
189            let r = self.placer.place(x, y, w, h, gap);
190            // ink on a paper pill whatever the mark's colour: legible on any tissue
191            self.pill.draw(fig, r, text);
192            r
193        } else {
194            let st = self.halo.clone();
195            let b = st.bounds(0.0, 0.0, text);
196            let (w, h) = (b.w, b.h);
197            let r = self.placer.place(x, y, w, h, gap);
198            let mut s = st.align(Anchor::Start, Baseline::Top);
199            s.color = color;
200            fig.text(r.x, r.y + (h - b.h).max(0.0), text, &s);
201            r
202        }
203    }
204}
205
206/// Draw `anns` into `fig` over `frame`. Errors (usage) when an annotation lacks what its type
207/// needs or does not fit the preview kind.
208pub(crate) fn draw(
209    fig: &mut Figure,
210    frame: &Frame,
211    anns: &[Annotation],
212    theme: &Theme,
213    notes: &mut Vec<String>,
214) -> Result<Vec<DrawnAnnotation>> {
215    for a in anns {
216        a.check()?;
217        if a.facet.is_some() {
218            return Err(Error::Usage(
219                "annotation facet picks a small plot of openreadout_plot; previews place marks by channel (trace panels) or well (plate cards)".into(),
220            ));
221        }
222    }
223    let fs = theme.font_size;
224    let mut labels = Labels {
225        pill: Pill {
226            text: TextStyle::new(fs, Color::rgb(29, 31, 36)).face(Face::SansMedium),
227            fill: Color::rgb(247, 245, 240).alpha(0.92),
228            stroke: None,
229            pad: ((fs * 0.6).round(), (fs * 0.3).round()),
230        },
231        halo: TextStyle::new(fs, theme.accent)
232            .face(Face::SansMedium)
233            .halo(theme.paper, (fs * 0.2).max(2.0)),
234        placer: LabelPlacer::new(fig.rect().inset(2.0)),
235    };
236    // the preview's own labels (peaks) are part of the same set
237    if let Frame::Plots { taken, .. } = frame {
238        for r in taken {
239            labels.placer.reserve(*r);
240        }
241    }
242    let mut out = Vec::with_capacity(anns.len());
243    let mut outside_any = false;
244    let mut key_slot: Option<KeySlot> = None;
245    for a in anns {
246        let color = resolve_color(a.color.as_deref(), theme)?;
247        let mut d = DrawnAnnotation {
248            annotation: a.clone(),
249            drawn_color: color.to_hex(),
250            px: Vec::new(),
251            label_px: None,
252            outside: false,
253        };
254        let group = fig.open_group(
255            Layer::Annotation,
256            a.label.as_deref().unwrap_or(a.kind.name()),
257        );
258        match frame {
259            Frame::Image { plot_area, map } => {
260                if a.kind == AnnotationType::Well {
261                    return Err(Error::Usage(
262                        "annotation type well needs a plate preview; on images use point or box in full-resolution pixels".into(),
263                    ));
264                }
265                let sp = image_space(*plot_area, *map);
266                if out.is_empty() {
267                    // labels stay on the data
268                    labels.placer = LabelPlacer::new(sp.area.inset(2.0));
269                }
270                draw_one(fig, &sp, a, color, theme, &mut labels, &mut d);
271            }
272            Frame::Plots { panels, key, .. } => {
273                if a.kind == AnnotationType::Well {
274                    if panels.iter().any(|p| p.well.is_some()) {
275                        let w = a.well.as_deref().and_then(parse_well_name);
276                        if let Some(p) = panels.iter().find(|p| p.well == w) {
277                            let r = p.panel.rect.inset(-3.0);
278                            ring(fig, r, color, theme, false);
279                            d.px = vec![corner(r.x, r.y), corner(r.right(), r.bottom())];
280                            if let Some(l) = a.label.as_deref() {
281                                let b = labels.put(fig, false, r.right(), r.y, l, color, 2.0);
282                                d.label_px = Some(b.into());
283                            }
284                        } else {
285                            d.outside = true;
286                        }
287                        fig.close_group(group);
288                        out.push(d);
289                        continue;
290                    }
291                    return Err(Error::Usage(
292                        "annotation type well needs a plate preview".into(),
293                    ));
294                }
295                let targets: Vec<&FramePanel> = select_panels(panels, a)?;
296                for (i, p) in targets.iter().enumerate() {
297                    let sp = panel_space(p);
298                    // a label once (on the first card of a curve grid)
299                    let mut one = a.clone();
300                    if i > 0 {
301                        one.label = None;
302                    }
303                    let mut part = DrawnAnnotation {
304                        annotation: one.clone(),
305                        drawn_color: d.drawn_color.clone(),
306                        px: Vec::new(),
307                        label_px: None,
308                        outside: false,
309                    };
310                    let compact = targets.len() > 1;
311                    if compact {
312                        draw_compact(fig, &sp, &one, color, theme, &mut part);
313                    } else {
314                        draw_one(fig, &sp, &one, color, theme, &mut labels, &mut part);
315                    }
316                    d.px.extend(part.px);
317                    d.outside |= part.outside;
318                    if part.label_px.is_some() {
319                        d.label_px = part.label_px;
320                    }
321                }
322                if targets.len() > 1
323                    && let Some(l) = a.label.as_deref()
324                {
325                    // one label for the whole grid: an entry in the figure's key
326                    if key_slot.is_none() {
327                        key_slot = *key;
328                    }
329                    let entry = key_entry(fig, theme, &mut key_slot, a.kind, l, color);
330                    let b = entry.unwrap_or_else(|| {
331                        let r = targets[0].panel.rect;
332                        labels.put(fig, false, r.x, r.y, l, color, 2.0)
333                    });
334                    d.label_px = Some(b.into());
335                }
336            }
337            Frame::Wells(cells) => {
338                let w = a.well.as_deref().and_then(parse_well_name);
339                match (a.kind, w) {
340                    (AnnotationType::Well | AnnotationType::Point, Some(w)) => {
341                        if let Some((_, r)) = cells.iter().find(|(p, _)| *p == w) {
342                            let r = r.inset(-2.5);
343                            ring(fig, r, color, theme, true);
344                            d.px = vec![corner(r.x, r.y), corner(r.right(), r.bottom())];
345                            if let Some(l) = a.label.as_deref() {
346                                let b = labels.put(fig, false, r.right(), r.y, l, color, 3.0);
347                                d.label_px = Some(b.into());
348                            }
349                        } else {
350                            d.outside = true;
351                        }
352                    }
353                    _ => {
354                        return Err(Error::Usage(
355                            "plate heat maps take annotations of type well (with well, e.g. \"B3\")".into(),
356                        ));
357                    }
358                }
359            }
360        }
361        fig.close_group(group);
362        outside_any |= d.outside;
363        out.push(d);
364    }
365    if outside_any {
366        notes.push(
367            "some annotations lie partly outside what the picture shows and are clipped (see annotations[].outside)".into(),
368        );
369    }
370    Ok(out)
371}
372
373fn corner(x: f32, y: f32) -> [f64; 2] {
374    let q = |v: f32| (f64::from(v) * 100.0).round() / 100.0;
375    [q(x), q(y)]
376}
377
378fn select_panels<'a>(panels: &'a [FramePanel], a: &Annotation) -> Result<Vec<&'a FramePanel>> {
379    if let Some(w) = a.well.as_deref() {
380        let w = parse_well_name(w);
381        let v: Vec<&FramePanel> = panels
382            .iter()
383            .filter(|p| p.well.is_some() && p.well == w)
384            .collect();
385        if v.is_empty() {
386            return Err(Error::Usage(format!(
387                "annotation well {} is not on this plate",
388                a.well.as_deref().unwrap_or("")
389            )));
390        }
391        return Ok(v);
392    }
393    if let Some(c) = a.channel {
394        let v: Vec<&FramePanel> = panels.iter().filter(|p| p.channel == Some(c)).collect();
395        if v.is_empty() {
396            let have: Vec<String> = panels
397                .iter()
398                .filter_map(|p| p.channel.map(|c| c.to_string()))
399                .collect();
400            return Err(Error::Usage(format!(
401                "annotation channel {c} is not drawn here (panels show channel {})",
402                if have.is_empty() {
403                    "-".into()
404                } else {
405                    have.join(", ")
406                }
407            )));
408        }
409        return Ok(v);
410    }
411    // curve grids: every card; trace panels: the first
412    if panels.iter().any(|p| p.well.is_some()) {
413        Ok(panels.iter().collect())
414    } else {
415        Ok(panels.iter().take(1).collect())
416    }
417}
418
419/// Label an annotation drawn on every card of a grid as an entry of the figure's key: a swatch
420/// of the mark, then the label. Returns its box, or `None` when the key has no room.
421fn key_entry(
422    fig: &mut Figure,
423    theme: &Theme,
424    slot: &mut Option<KeySlot>,
425    kind: AnnotationType,
426    label: &str,
427    color: Color,
428) -> Option<Rect> {
429    let s = (*slot)?;
430    let fs = theme.font_size;
431    let st = TextStyle::new(fs, theme.ink).align(Anchor::Start, Baseline::Middle);
432    let sw = fs * 1.1;
433    let w = sw + fs * 0.4 + st.width(label);
434    if s.x + w > s.max_x {
435        return None;
436    }
437    let (x, y) = (s.x, s.y);
438    match kind {
439        AnnotationType::Vband | AnnotationType::Hband => {
440            fig.fill(Path::rect(x, y - fs * 0.45, sw, fs * 0.9), color.alpha(0.2));
441        }
442        AnnotationType::Vline | AnnotationType::Hline => {
443            fig.stroke(
444                Path::segment(x, y, x + sw, y),
445                Stroke::new(color, 1.5).dashed(3.0, 2.0),
446            );
447        }
448        _ => {
449            fig.fill(Path::circle(x + sw / 2.0, y, fs * 0.3), color);
450        }
451    }
452    let b = fig.text(x + sw + fs * 0.4, y, label, &st);
453    *slot = Some(KeySlot {
454        x: b.right() + fs * 1.2,
455        ..s
456    });
457    Some(Rect::new(x, y - fs * 0.6, b.right() - x, fs * 1.2))
458}
459
460/// A ring around a rectangle: a circle (`round`, for plate wells) or a rounded rectangle.
461fn ring(fig: &mut Figure, r: Rect, color: Color, theme: &Theme, round: bool) {
462    let w = (theme.line_width * 1.3).max(2.0);
463    let path = if round {
464        let (cx, cy) = r.center();
465        Path::circle(cx, cy, r.w.max(r.h) / 2.0)
466    } else {
467        Path::round_rect(r.x, r.y, r.w, r.h, (r.h.min(r.w) * 0.12).min(8.0))
468    };
469    fig.stroke(path, Stroke::new(color, w));
470}
471
472/// Draw on a small card of a curve grid: lines, bands, points only, no labels.
473fn draw_compact(
474    fig: &mut Figure,
475    sp: &Space<'_>,
476    a: &Annotation,
477    color: Color,
478    theme: &Theme,
479    d: &mut DrawnAnnotation,
480) {
481    let r = sp.area;
482    let clip = Some(r);
483    match a.kind {
484        AnnotationType::Vband => {
485            let (x0, x1) = (
486                (sp.x_only)(a.x.unwrap_or(0.0)),
487                (sp.x_only)(a.x2.unwrap_or(0.0)),
488            );
489            let (x0, x1) = (x0.min(x1).max(r.x), x0.max(x1).min(r.right()));
490            if x1 > x0 {
491                fig.shape(
492                    Path::rect(x0, r.y, x1 - x0, r.h),
493                    Some(color.alpha(0.16)),
494                    None,
495                    clip,
496                );
497            }
498            d.px.push(corner(x0, r.y));
499            d.px.push(corner(x1, r.bottom()));
500        }
501        AnnotationType::Hband => {
502            let (y0, y1) = (
503                (sp.y_only)(a.y.unwrap_or(0.0)),
504                (sp.y_only)(a.y2.unwrap_or(0.0)),
505            );
506            let (y0, y1) = (y0.min(y1).max(r.y), y0.max(y1).min(r.bottom()));
507            if y1 > y0 {
508                fig.shape(
509                    Path::rect(r.x, y0, r.w, y1 - y0),
510                    Some(color.alpha(0.16)),
511                    None,
512                    clip,
513                );
514            }
515            d.px.push(corner(r.x, y0));
516            d.px.push(corner(r.right(), y1));
517        }
518        AnnotationType::Vline => {
519            let x = (sp.x_only)(a.x.unwrap_or(0.0));
520            fig.shape(
521                Path::segment(x, r.y, x, r.bottom()),
522                None,
523                Some(Stroke::new(color, 1.0).dashed(3.0, 2.0)),
524                clip,
525            );
526            d.outside |= !(r.x..=r.right()).contains(&x);
527            d.px.push(corner(x, r.y));
528        }
529        AnnotationType::Hline => {
530            let y = (sp.y_only)(a.y.unwrap_or(0.0));
531            fig.shape(
532                Path::segment(r.x, y, r.right(), y),
533                None,
534                Some(Stroke::new(color, 1.0).dashed(3.0, 2.0)),
535                clip,
536            );
537            d.outside |= !(r.y..=r.bottom()).contains(&y);
538            d.px.push(corner(r.x, y));
539        }
540        _ => {
541            // other marks keep their shape, small
542            let mut quiet = Labels {
543                pill: Pill {
544                    text: TextStyle::new(1.0, color),
545                    fill: color,
546                    stroke: None,
547                    pad: (0.0, 0.0),
548                },
549                halo: TextStyle::new(theme.small_size(), color),
550                placer: LabelPlacer::new(r),
551            };
552            let mut one = a.clone();
553            one.label = None;
554            draw_one(fig, sp, &one, color, theme, &mut quiet, d);
555        }
556    }
557}
558
559/// Draw one annotation in `sp`.
560fn draw_one(
561    fig: &mut Figure,
562    sp: &Space<'_>,
563    a: &Annotation,
564    color: Color,
565    theme: &Theme,
566    labels: &mut Labels,
567    d: &mut DrawnAnnotation,
568) {
569    let r = sp.area;
570    let lw = (theme.line_width * 1.3).max(2.0);
571    let halo = if sp.on_image {
572        Color::rgb(255, 255, 255).alpha(0.7)
573    } else {
574        theme.paper.alpha(0.85)
575    };
576    let stroke_with_halo = |fig: &mut Figure, p: Path, closed_fill: Option<Color>| {
577        fig.shape(
578            p.clone(),
579            None,
580            Some(Stroke::new(halo, lw + 2.5).round()),
581            Some(r),
582        );
583        fig.shape(
584            p,
585            closed_fill,
586            Some(Stroke::new(color, lw).round()),
587            Some(r),
588        );
589    };
590    let fs = theme.font_size;
591    let inside = |x: f32, y: f32| r.inset(-0.5).contains(x, y);
592    let label = a.label.as_deref().filter(|l| !l.trim().is_empty());
593    match a.kind {
594        AnnotationType::Point => {
595            let (x, y) = (sp.to_px)(a.x.unwrap_or(0.0), a.y.unwrap_or(0.0));
596            d.outside = !inside(x, y);
597            d.px.push(corner(x, y));
598            let rad = (fs * 0.42).max(4.0);
599            if !d.outside {
600                if sp.on_image {
601                    // a ring with a white rim: visible on dark and bright tissue
602                    fig.stroke(
603                        Path::circle(x, y, rad),
604                        Stroke::new(Color::rgb(255, 255, 255).alpha(0.85), lw + 2.5),
605                    );
606                    fig.stroke(Path::circle(x, y, rad), Stroke::new(color, lw));
607                    fig.fill(Path::circle(x, y, (lw * 0.8).max(1.5)), color);
608                } else {
609                    fig.shape(
610                        Path::circle(x, y, rad * 0.75),
611                        Some(color),
612                        Some(Stroke::new(theme.paper, (lw * 0.6).max(1.2))),
613                        None,
614                    );
615                }
616                labels
617                    .placer
618                    .reserve(Rect::new(x - rad, y - rad, rad * 2.0, rad * 2.0));
619            }
620            if let Some(l) = label {
621                let b = labels.put(fig, sp.on_image, x, y, l, color, rad + 3.0);
622                d.label_px = Some(b.into());
623            }
624        }
625        AnnotationType::Text => {
626            let (x, y) = (sp.to_px)(a.x.unwrap_or(0.0), a.y.unwrap_or(0.0));
627            d.outside = !inside(x, y);
628            d.px.push(corner(x, y));
629            if let Some(l) = label {
630                let b = if sp.on_image {
631                    let (w, h) = labels.pill.size(l);
632                    let rr = Rect::new(x - w / 2.0, y - h / 2.0, w, h);
633                    labels.placer.reserve(rr);
634                    labels.pill.draw(fig, rr, l);
635                    rr
636                } else {
637                    let st = labels.halo.clone().align(Anchor::Middle, Baseline::Middle);
638                    let mut st = st;
639                    st.color = color;
640                    let b = fig.text(x, y, l, &st);
641                    labels.placer.reserve(b);
642                    b
643                };
644                d.label_px = Some(b.into());
645            }
646        }
647        AnnotationType::Box => {
648            let (x, y) = (a.x.unwrap_or(0.0), a.y.unwrap_or(0.0));
649            let (x2, y2) = (x + a.width.unwrap_or(0.0), y + a.height.unwrap_or(0.0));
650            let (p0x, p0y) = (sp.to_px)(x, y);
651            let (p1x, p1y) = (sp.to_px)(x2, y2);
652            let b = Rect::from_corners(p0x, p0y, p1x, p1y);
653            d.outside = !r.inset(-0.5).contains_rect(&b);
654            d.px.push(corner(b.x, b.y));
655            d.px.push(corner(b.right(), b.bottom()));
656            stroke_with_halo(fig, Path::rect(b.x, b.y, b.w.max(1.0), b.h.max(1.0)), None);
657            labels
658                .placer
659                .reserve(Rect::new(b.x - 2.0, b.y - 2.0, b.w + 4.0, 4.0));
660            if let Some(l) = label {
661                // above the top-left corner, else wherever it fits
662                let bb = labels.put(fig, sp.on_image, b.x, b.y, l, color, 4.0);
663                d.label_px = Some(bb.into());
664            }
665        }
666        AnnotationType::Polygon | AnnotationType::Line => {
667            let pts: Vec<(f32, f32)> = a.points.iter().map(|p| (sp.to_px)(p[0], p[1])).collect();
668            d.outside = pts.iter().any(|&(x, y)| !inside(x, y));
669            d.px = pts.iter().map(|&(x, y)| corner(x, y)).collect();
670            let path = if a.kind == AnnotationType::Polygon {
671                Path::polygon(pts.iter().copied())
672            } else {
673                Path::polyline(pts.iter().copied())
674            };
675            let fill = (a.kind == AnnotationType::Polygon).then(|| color.alpha(0.12));
676            stroke_with_halo(fig, path, fill);
677            if let Some(l) = label {
678                // next to the topmost vertex
679                let top = pts
680                    .iter()
681                    .copied()
682                    .min_by(|a, b| a.1.total_cmp(&b.1))
683                    .unwrap_or((r.x, r.y));
684                let bb = labels.put(fig, sp.on_image, top.0, top.1, l, color, 4.0);
685                d.label_px = Some(bb.into());
686            }
687        }
688        AnnotationType::Arrow => {
689            let (x0, y0) = (sp.to_px)(a.x.unwrap_or(0.0), a.y.unwrap_or(0.0));
690            let (x1, y1) = (sp.to_px)(a.x2.unwrap_or(0.0), a.y2.unwrap_or(0.0));
691            d.outside = !inside(x0, y0) || !inside(x1, y1);
692            d.px = vec![corner(x0, y0), corner(x1, y1)];
693            if let Some((shaft, head)) = arrow_parts(x0, y0, x1, y1, lw) {
694                let rim = Stroke::new(halo, 2.5).round();
695                fig.shape(
696                    shaft.clone(),
697                    None,
698                    Some(Stroke::new(halo, lw + 2.5).round()),
699                    Some(r),
700                );
701                fig.shape(head.clone(), None, Some(rim), Some(r));
702                fig.shape(shaft, None, Some(Stroke::new(color, lw).round()), Some(r));
703                fig.shape(head, Some(color), None, Some(r));
704            }
705            if let Some(l) = label {
706                // at the tail, on the side away from the head
707                let (dx, dy) = (x0 - x1, y0 - y1);
708                let n = (dx * dx + dy * dy).sqrt().max(1e-3);
709                let (ax, ay) = (x0 + dx / n * 4.0, y0 + dy / n * 4.0);
710                let bb = labels.put(fig, sp.on_image, ax, ay, l, color, 3.0);
711                d.label_px = Some(bb.into());
712            }
713        }
714        AnnotationType::Vline | AnnotationType::Hline => {
715            let vertical = a.kind == AnnotationType::Vline;
716            let (p0, p1) = if vertical {
717                let x = (sp.x_only)(a.x.unwrap_or(0.0));
718                ((x, r.y), (x, r.bottom()))
719            } else {
720                let y = (sp.y_only)(a.y.unwrap_or(0.0));
721                ((r.x, y), (r.right(), y))
722            };
723            d.outside = !inside(p0.0, p0.1);
724            d.px = vec![corner(p0.0, p0.1), corner(p1.0, p1.1)];
725            let path = Path::segment(p0.0, p0.1, p1.0, p1.1);
726            fig.shape(
727                path.clone(),
728                None,
729                Some(Stroke::new(halo, lw + 1.5)),
730                Some(r),
731            );
732            fig.shape(
733                path,
734                None,
735                Some(Stroke::new(color, lw * 0.75).dashed(lw * 3.0, lw * 2.0)),
736                Some(r),
737            );
738            if let Some(l) = label {
739                let (ax, ay) = if vertical {
740                    (p0.0, r.y + fs * 0.2)
741                } else {
742                    (r.right() - fs * 0.2, p0.1)
743                };
744                let bb = labels.put(fig, sp.on_image, ax, ay, l, color, 3.0);
745                d.label_px = Some(bb.into());
746            }
747        }
748        AnnotationType::Vband | AnnotationType::Hband => {
749            let vertical = a.kind == AnnotationType::Vband;
750            let b = if vertical {
751                let (x0, x1) = (
752                    (sp.x_only)(a.x.unwrap_or(0.0)),
753                    (sp.x_only)(a.x2.unwrap_or(0.0)),
754                );
755                Rect::from_corners(x0, r.y, x1, r.bottom())
756            } else {
757                let (y0, y1) = (
758                    (sp.y_only)(a.y.unwrap_or(0.0)),
759                    (sp.y_only)(a.y2.unwrap_or(0.0)),
760                );
761                Rect::from_corners(r.x, y0, r.right(), y1)
762            };
763            d.outside = !r.inset(-0.5).contains_rect(&b);
764            d.px = vec![corner(b.x, b.y), corner(b.right(), b.bottom())];
765            let fill = if sp.on_image {
766                color.alpha(0.2)
767            } else {
768                color.alpha(0.13)
769            };
770            fig.shape(
771                Path::rect(b.x, b.y, b.w.max(0.5), b.h.max(0.5)),
772                Some(fill),
773                None,
774                Some(r),
775            );
776            // thin edges keep a narrow band visible
777            let edge = Stroke::new(color.alpha(0.55), 1.0);
778            if vertical {
779                fig.shape(
780                    Path::segment(b.x, b.y, b.x, b.bottom()),
781                    None,
782                    Some(edge.clone()),
783                    Some(r),
784                );
785                fig.shape(
786                    Path::segment(b.right(), b.y, b.right(), b.bottom()),
787                    None,
788                    Some(edge),
789                    Some(r),
790                );
791            } else {
792                fig.shape(
793                    Path::segment(b.x, b.y, b.right(), b.y),
794                    None,
795                    Some(edge.clone()),
796                    Some(r),
797                );
798                fig.shape(
799                    Path::segment(b.x, b.bottom(), b.right(), b.bottom()),
800                    None,
801                    Some(edge),
802                    Some(r),
803                );
804            }
805            if let Some(l) = label {
806                let (cx, _) = b.center();
807                let (ax, ay) = if vertical {
808                    (cx, r.y + fs * 0.3)
809                } else {
810                    (r.right() - fs * 0.3, b.y)
811                };
812                let st = TextStyle::new(fs, color)
813                    .face(Face::SansMedium)
814                    .halo(theme.paper, (fs * 0.2).max(2.0));
815                let bb = if vertical {
816                    let s = st.align(Anchor::Middle, Baseline::Top);
817                    let tb = s.bounds(ax, ay, l);
818                    let tb = Rect::new(
819                        tb.x.clamp(r.x, (r.right() - tb.w).max(r.x)),
820                        tb.y,
821                        tb.w,
822                        tb.h,
823                    );
824                    fig.text(tb.x + tb.w / 2.0, ay, l, &s);
825                    tb
826                } else {
827                    labels.put(fig, sp.on_image, ax, ay, l, color, 3.0)
828                };
829                labels.placer.reserve(bb);
830                d.label_px = Some(bb.into());
831            }
832        }
833        AnnotationType::Well => {}
834    }
835}
836
837#[cfg(test)]
838mod tests {
839    use super::*;
840
841    #[test]
842    fn wells_round_trip() {
843        assert_eq!(well_name((1, 2)), "B3");
844        assert_eq!(parse_well_name("b03"), Some((1, 2)));
845        assert_eq!(parse_well_name("AF48"), Some((31, 47)));
846        assert_eq!(well_name((31, 47)), "AF48");
847        assert_eq!(parse_well_name("3B"), None);
848        assert_eq!(parse_well_name("B0"), None);
849    }
850
851    #[test]
852    fn annotations_parse_and_validate() {
853        let a: Annotation =
854            serde_json::from_str(r#"{"type":"point","x":10,"y":20,"label":"cell"}"#).unwrap();
855        assert!(a.check().is_ok());
856        let bad: Annotation = serde_json::from_str(r#"{"type":"box","x":1,"y":2}"#).unwrap();
857        assert!(bad.check().unwrap_err().to_string().contains("width"));
858        assert!(
859            serde_json::from_str::<Annotation>(r#"{"type":"point","x":1,"y":2,"caption":"x"}"#)
860                .is_err()
861        );
862        let t: Annotation = serde_json::from_str(r#"{"type":"text","x":1,"y":2}"#).unwrap();
863        assert!(t.check().is_err());
864        let w: Annotation = serde_json::from_str(r#"{"type":"well","well":"H12"}"#).unwrap();
865        assert!(w.check().is_ok());
866    }
867}