Skip to main content

ggplot_rs/render/
plotters_backend.rs

1use std::collections::HashSet;
2use std::sync::{Mutex, OnceLock};
3
4use plotters::prelude::*;
5use plotters::style::FontStyle;
6
7use super::backend::{
8    DrawBackend, LineStyle, PointShape, PointStyle, RectStyle, TextAnchor, TextStyle,
9};
10use super::{Rect, RenderError};
11
12/// A font bundled into the binary so text renders in a headless container with
13/// no system fonts / fontconfig. DejaVu Sans (Bitstream Vera–derived license,
14/// freely redistributable) — broad glyph coverage keeps labels tofu-free.
15const SANS: &[u8] = include_bytes!("../../assets/fonts/DejaVuSans.ttf");
16const SANS_BOLD: &[u8] = include_bytes!("../../assets/fonts/DejaVuSans-Bold.ttf");
17const SANS_OBLIQUE: &[u8] = include_bytes!("../../assets/fonts/DejaVuSans-Oblique.ttf");
18const SERIF: &[u8] = include_bytes!("../../assets/fonts/DejaVuSerif.ttf");
19const SERIF_BOLD: &[u8] = include_bytes!("../../assets/fonts/DejaVuSerif-Bold.ttf");
20const SERIF_ITALIC: &[u8] = include_bytes!("../../assets/fonts/DejaVuSerif-Italic.ttf");
21const MONO: &[u8] = include_bytes!("../../assets/fonts/DejaVuSansMono.ttf");
22const MONO_BOLD: &[u8] = include_bytes!("../../assets/fonts/DejaVuSansMono-Bold.ttf");
23
24/// Pick the DejaVu face set (per style) that matches a requested family name, so
25/// `family = "serif"` / `"monospace"` render with real serif/mono glyphs — not
26/// just the SVG attribute — headlessly.
27fn faces_for(family: &str) -> [(FontStyle, &'static [u8]); 4] {
28    let f = family.to_lowercase();
29    if f.contains("mono") || f.contains("courier") {
30        [
31            (FontStyle::Normal, MONO),
32            (FontStyle::Bold, MONO_BOLD),
33            (FontStyle::Italic, MONO),
34            (FontStyle::Oblique, MONO),
35        ]
36    } else if f == "serif" || f.contains("times") || (f.contains("serif") && !f.contains("sans")) {
37        [
38            (FontStyle::Normal, SERIF),
39            (FontStyle::Bold, SERIF_BOLD),
40            (FontStyle::Italic, SERIF_ITALIC),
41            (FontStyle::Oblique, SERIF_ITALIC),
42        ]
43    } else {
44        [
45            (FontStyle::Normal, SANS),
46            (FontStyle::Bold, SANS_BOLD),
47            (FontStyle::Italic, SANS_OBLIQUE),
48            (FontStyle::Oblique, SANS_OBLIQUE),
49        ]
50    }
51}
52
53fn registered_families() -> &'static Mutex<HashSet<String>> {
54    static REGISTERED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
55    REGISTERED.get_or_init(|| Mutex::new(HashSet::new()))
56}
57
58/// Ensure the bundled font is registered under `family` (idempotent).
59///
60/// With plotters' `ab_glyph` backend there is no system-font lookup: every
61/// family used for layout must be registered first. We map *all* requested
62/// families to the one bundled font, so any family name lays out correctly
63/// headlessly; SVG output still carries the requested family name for browsers.
64fn ensure_font(family: &str) {
65    let mut set = registered_families().lock().unwrap();
66    if set.insert(family.to_string()) {
67        // Register the matching DejaVu family + face per style so serif/mono and
68        // bold/italic actually render (not just carry the SVG attribute).
69        for (style, bytes) in faces_for(family) {
70            // Ignore the result: a malformed font would surface as a draw error.
71            let _ = plotters::style::register_font(family, style, bytes);
72        }
73    }
74}
75
76/// Adapter from plotters' DrawingArea to our DrawBackend trait.
77pub struct PlottersAdapter<'a, DB: DrawingBackend> {
78    area: &'a DrawingArea<DB, plotters::coord::Shift>,
79    plot_area: Rect,
80    total_area: Rect,
81    /// #273: panel-corner boxes claimed so far this render pass — see
82    /// [`DrawBackend::corner_claims`]/[`DrawBackend::claim_corner_box`].
83    corner_claims: Vec<Rect>,
84    /// Clip lines / points / clip-flagged rects to the panel (data marks);
85    /// off while legends draw (#410), whose keys sit outside it.
86    clip: bool,
87    /// The renderer's clip groups ([`DrawBackend::begin_clip`]): a zoomed
88    /// panel's rect, which marks are clipped to while it's open (#493).
89    clips: Vec<Rect>,
90}
91
92impl<'a, DB: DrawingBackend> PlottersAdapter<'a, DB> {
93    pub fn new(area: &'a DrawingArea<DB, plotters::coord::Shift>, plot_area: Rect) -> Self {
94        let (w, h) = area.dim_in_pixel();
95        PlottersAdapter {
96            area,
97            plot_area,
98            total_area: Rect {
99                x: 0.0,
100                y: 0.0,
101                width: w as f64,
102                height: h as f64,
103            },
104            corner_claims: Vec::new(),
105            clip: true,
106            clips: Vec::new(),
107        }
108    }
109}
110
111fn to_rgba(color: (u8, u8, u8), alpha: f64) -> RGBAColor {
112    RGBAColor(color.0, color.1, color.2, alpha)
113}
114
115/// Clip a point to the given rectangle bounds. Returns None if fully outside.
116fn clip_point(x: f64, y: f64, rect: &Rect) -> (f64, f64) {
117    (
118        x.clamp(rect.x, rect.x + rect.width),
119        y.clamp(rect.y, rect.y + rect.height),
120    )
121}
122
123/// Check if a point is inside the rectangle (with small margin).
124fn point_in_rect(x: f64, y: f64, rect: &Rect) -> bool {
125    let margin = 2.0;
126    x >= rect.x - margin
127        && x <= rect.x + rect.width + margin
128        && y >= rect.y - margin
129        && y <= rect.y + rect.height + margin
130}
131
132/// Sutherland–Hodgman: `points` (a polygon) cut to `rect`.
133fn clip_polygon(points: &[(f64, f64)], rect: &Rect) -> Vec<(f64, f64)> {
134    let (x0, y0) = (rect.x, rect.y);
135    let (x1, y1) = (rect.x + rect.width, rect.y + rect.height);
136    // (inside?, intersection with the edge) per side
137    type Side = (fn(&(f64, f64), f64) -> bool, bool, f64);
138    let sides: [Side; 4] = [
139        (|p, v| p.0 >= v, true, x0),
140        (|p, v| p.0 <= v, true, x1),
141        (|p, v| p.1 >= v, false, y0),
142        (|p, v| p.1 <= v, false, y1),
143    ];
144    let mut out: Vec<(f64, f64)> = points.to_vec();
145    for (inside, vertical, v) in sides {
146        let input = std::mem::take(&mut out);
147        let Some(&last) = input.last() else {
148            break;
149        };
150        let cross = |a: (f64, f64), b: (f64, f64)| {
151            if vertical {
152                let t = (v - a.0) / (b.0 - a.0);
153                (v, a.1 + t * (b.1 - a.1))
154            } else {
155                let t = (v - a.1) / (b.1 - a.1);
156                (a.0 + t * (b.0 - a.0), v)
157            }
158        };
159        let mut prev = last;
160        for &cur in &input {
161            match (inside(&cur, v), inside(&prev, v)) {
162                (true, true) => out.push(cur),
163                (true, false) => {
164                    out.push(cross(prev, cur));
165                    out.push(cur);
166                }
167                (false, true) => out.push(cross(prev, cur)),
168                (false, false) => {}
169            }
170            prev = cur;
171        }
172    }
173    out
174}
175
176/// Cohen-Sutherland line clipping. Returns clipped line segment or None if fully outside.
177fn clip_line_segment(
178    mut x0: f64,
179    mut y0: f64,
180    mut x1: f64,
181    mut y1: f64,
182    rect: &Rect,
183) -> Option<((f64, f64), (f64, f64))> {
184    let xmin = rect.x;
185    let xmax = rect.x + rect.width;
186    let ymin = rect.y;
187    let ymax = rect.y + rect.height;
188
189    const INSIDE: u8 = 0;
190    const LEFT: u8 = 1;
191    const RIGHT: u8 = 2;
192    const BOTTOM: u8 = 4;
193    const TOP: u8 = 8;
194
195    let outcode = |x: f64, y: f64| -> u8 {
196        let mut code = INSIDE;
197        if x < xmin {
198            code |= LEFT;
199        } else if x > xmax {
200            code |= RIGHT;
201        }
202        if y < ymin {
203            code |= TOP;
204        } else if y > ymax {
205            code |= BOTTOM;
206        }
207        code
208    };
209
210    let mut code0 = outcode(x0, y0);
211    let mut code1 = outcode(x1, y1);
212
213    for _ in 0..20 {
214        if (code0 | code1) == 0 {
215            return Some(((x0, y0), (x1, y1)));
216        }
217        if (code0 & code1) != 0 {
218            return None;
219        }
220
221        let code_out = if code0 != 0 { code0 } else { code1 };
222        let (x, y);
223
224        if code_out & TOP != 0 {
225            x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0);
226            y = ymin;
227        } else if code_out & BOTTOM != 0 {
228            x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0);
229            y = ymax;
230        } else if code_out & RIGHT != 0 {
231            y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0);
232            x = xmax;
233        } else {
234            y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0);
235            x = xmin;
236        }
237
238        if code_out == code0 {
239            x0 = x;
240            y0 = y;
241            code0 = outcode(x0, y0);
242        } else {
243            x1 = x;
244            y1 = y;
245            code1 = outcode(x1, y1);
246        }
247    }
248
249    None
250}
251
252fn map_err<E: std::fmt::Debug>(e: E) -> RenderError {
253    RenderError::BackendError(format!("{:?}", e))
254}
255
256/// Segment a polyline according to a dash pattern, returning visible sub-paths.
257fn segment_dashed(points: &[(f64, f64)], pattern: &[(f64, f64)]) -> Vec<Vec<(f64, f64)>> {
258    if pattern.is_empty() || points.len() < 2 {
259        return vec![points.to_vec()];
260    }
261
262    let mut segments: Vec<Vec<(f64, f64)>> = Vec::new();
263    let mut current_seg: Vec<(f64, f64)> = Vec::new();
264    let mut drawing = true;
265    let mut pat_idx = 0;
266    let mut remaining_in_pat = pattern[0].0; // start with draw phase
267
268    for window in points.windows(2) {
269        let (x0, y0) = window[0];
270        let (x1, y1) = window[1];
271        let dx = x1 - x0;
272        let dy = y1 - y0;
273        let seg_len = (dx * dx + dy * dy).sqrt();
274        if seg_len < 0.001 {
275            continue;
276        }
277        let ux = dx / seg_len;
278        let uy = dy / seg_len;
279        let mut consumed = 0.0;
280
281        while consumed < seg_len - 0.001 {
282            let available = seg_len - consumed;
283            let step = remaining_in_pat.min(available);
284            let px = x0 + ux * (consumed + step);
285            let py = y0 + uy * (consumed + step);
286
287            if drawing {
288                if current_seg.is_empty() {
289                    current_seg.push((x0 + ux * consumed, y0 + uy * consumed));
290                }
291                current_seg.push((px, py));
292            }
293
294            consumed += step;
295            remaining_in_pat -= step;
296
297            if remaining_in_pat < 0.001 {
298                if drawing {
299                    if current_seg.len() >= 2 {
300                        segments.push(std::mem::take(&mut current_seg));
301                    } else {
302                        current_seg.clear();
303                    }
304                    drawing = false;
305                    remaining_in_pat = pattern[pat_idx].1; // gap
306                } else {
307                    drawing = true;
308                    pat_idx = (pat_idx + 1) % pattern.len();
309                    remaining_in_pat = pattern[pat_idx].0; // draw
310                }
311            }
312        }
313    }
314
315    if drawing && current_seg.len() >= 2 {
316        segments.push(current_seg);
317    }
318
319    segments
320}
321
322impl<DB: DrawingBackend> PlottersAdapter<'_, DB> {
323    /// The rect marks are clipped to: the panel, or the canvas when off.
324    fn clip_area(&self) -> Rect {
325        match (self.clip, self.clips.last()) {
326            (true, Some(r)) => r.clone(),
327            (true, None) => self.plot_area.clone(),
328            (false, _) => self.total_area.clone(),
329        }
330    }
331
332    /// The open clip group's rect, while clipping is on.
333    fn clip_group(&self) -> Option<Rect> {
334        self.clip.then(|| self.clips.last().cloned()).flatten()
335    }
336}
337
338impl<'a, DB: DrawingBackend> DrawBackend for PlottersAdapter<'a, DB> {
339    fn set_clipping(&mut self, on: bool) {
340        self.clip = on;
341    }
342
343    fn begin_clip(&mut self, rect: &Rect) {
344        self.clips.push(rect.clone());
345    }
346
347    fn end_clip(&mut self) {
348        self.clips.pop();
349    }
350
351    fn draw_circle(
352        &mut self,
353        center: (f64, f64),
354        radius: f64,
355        style: &PointStyle,
356    ) -> Result<(), RenderError> {
357        // Clip: skip points entirely outside the plot area
358        if !point_in_rect(center.0, center.1, &self.clip_area()) {
359            return Ok(());
360        }
361        let color = to_rgba(style.color, style.alpha);
362        if style.filled {
363            self.area
364                .draw(&Circle::new(
365                    (center.0 as i32, center.1 as i32),
366                    radius as i32,
367                    color.filled(),
368                ))
369                .map_err(map_err)?;
370        } else {
371            self.area
372                .draw(&Circle::new(
373                    (center.0 as i32, center.1 as i32),
374                    radius as i32,
375                    color.stroke_width(1),
376                ))
377                .map_err(map_err)?;
378        }
379        Ok(())
380    }
381
382    fn draw_line(&mut self, points: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
383        if points.len() < 2 {
384            return Ok(());
385        }
386        // Simulate sub-pixel line widths: render as 1px with reduced opacity
387        let (pixel_width, alpha) = if style.width >= 1.0 {
388            (style.width as u32, style.alpha)
389        } else if style.width > 0.0 {
390            (1, style.alpha * style.width)
391        } else {
392            (0, style.alpha)
393        };
394        let color = to_rgba(style.color, alpha);
395        let stroke = color.stroke_width(pixel_width);
396
397        let pattern = style.linetype.dash_pattern();
398        let sub_paths = segment_dashed(points, &pattern);
399
400        for path in &sub_paths {
401            for window in path.windows(2) {
402                // Clip each line segment to plot area
403                if let Some((p1, p2)) = clip_line_segment(
404                    window[0].0,
405                    window[0].1,
406                    window[1].0,
407                    window[1].1,
408                    &self.clip_area(),
409                ) {
410                    self.area
411                        .draw(&PathElement::new(
412                            vec![(p1.0 as i32, p1.1 as i32), (p2.0 as i32, p2.1 as i32)],
413                            stroke,
414                        ))
415                        .map_err(map_err)?;
416                }
417            }
418        }
419        Ok(())
420    }
421
422    fn draw_rect(
423        &mut self,
424        top_left: (f64, f64),
425        bottom_right: (f64, f64),
426        style: &RectStyle,
427    ) -> Result<(), RenderError> {
428        let (tl, br) = if style.clip {
429            // Clamp rect to plot area (data elements only)
430            let area = self.clip_area();
431            let clamped_tl = clip_point(top_left.0, top_left.1, &area);
432            let clamped_br = clip_point(bottom_right.0, bottom_right.1, &area);
433
434            // Skip if fully collapsed after clamping
435            if (clamped_tl.0 - clamped_br.0).abs() < 0.5
436                && (clamped_tl.1 - clamped_br.1).abs() < 0.5
437            {
438                // But don't skip if original rect was already small (it's a real data rect)
439                if (top_left.0 - bottom_right.0).abs() > 1.0
440                    || (top_left.1 - bottom_right.1).abs() > 1.0
441                {
442                    return Ok(());
443                }
444            }
445
446            (
447                (clamped_tl.0 as i32, clamped_tl.1 as i32),
448                (clamped_br.0 as i32, clamped_br.1 as i32),
449            )
450        } else {
451            // No clipping — backgrounds, strips, legends
452            (
453                (top_left.0 as i32, top_left.1 as i32),
454                (bottom_right.0 as i32, bottom_right.1 as i32),
455            )
456        };
457
458        if style.corner_radius > 0.0 {
459            // plotters has no native rounded-rect primitive: approximate with
460            // the same polygon the pixel backend uses. Note this clips the
461            // bounding box above, not each rounded corner individually — a
462            // rounded rect that straddles the clip edge gets a straight cut.
463            let pts = super::backend::rounded_rect_points(
464                tl.0 as f64,
465                tl.1 as f64,
466                br.0 as f64,
467                br.1 as f64,
468                style.corner_radius,
469            );
470            let int_pts: Vec<(i32, i32)> =
471                pts.iter().map(|(x, y)| (*x as i32, *y as i32)).collect();
472            if let Some(fill) = style.fill {
473                let fill_color = to_rgba(fill, style.alpha);
474                self.area
475                    .draw(&Polygon::new(int_pts.clone(), fill_color.filled()))
476                    .map_err(map_err)?;
477            }
478            if let Some(stroke) = style.stroke {
479                let stroke_color = to_rgba(stroke, style.alpha);
480                let width = if style.stroke_width > 0.0 {
481                    (style.stroke_width as u32).max(1)
482                } else {
483                    0
484                };
485                let mut loop_pts = int_pts;
486                if let Some(first) = loop_pts.first().copied() {
487                    loop_pts.push(first);
488                }
489                self.area
490                    .draw(&PathElement::new(
491                        loop_pts,
492                        stroke_color.stroke_width(width),
493                    ))
494                    .map_err(map_err)?;
495            }
496            return Ok(());
497        }
498
499        if let Some(fill) = style.fill {
500            let fill_color = to_rgba(fill, style.alpha);
501            self.area
502                .draw(&plotters::prelude::Rectangle::new(
503                    [tl, br],
504                    fill_color.filled(),
505                ))
506                .map_err(map_err)?;
507        }
508
509        if let Some(stroke) = style.stroke {
510            let stroke_color = to_rgba(stroke, style.alpha);
511            self.area
512                .draw(&plotters::prelude::Rectangle::new(
513                    [tl, br],
514                    stroke_color.stroke_width(if style.stroke_width > 0.0 {
515                        (style.stroke_width as u32).max(1)
516                    } else {
517                        0
518                    }),
519                ))
520                .map_err(map_err)?;
521        }
522
523        Ok(())
524    }
525
526    fn draw_text(
527        &mut self,
528        text: &str,
529        pos: (f64, f64),
530        style: &TextStyle,
531    ) -> Result<(), RenderError> {
532        let color = to_rgba(style.color, 1.0);
533        let family = style.family.as_deref().unwrap_or("sans-serif");
534        ensure_font(family);
535        let font_style = match style.face {
536            crate::render::backend::FontFace::Plain => FontStyle::Normal,
537            crate::render::backend::FontFace::Bold => FontStyle::Bold,
538            crate::render::backend::FontFace::Italic => FontStyle::Italic,
539        };
540        let angle_i = style.angle.round() as i32;
541
542        // #229: a text halo — this backend has no native stroke-text, so
543        // approximate the SVG `stroke`/`paint-order="stroke"` outline by
544        // drawing the same text at 8 offsets around the radius, in
545        // `bg_colour`, before the normal pass. `bg_colour: None` (the
546        // default) skips this entirely, so existing output is unchanged.
547        if let Some(bg) = style.bg_colour {
548            let r = if style.bg_r.is_finite() {
549                style.bg_r
550            } else {
551                0.0
552            };
553            if r > 0.0 {
554                let halo_color = to_rgba(bg, 1.0);
555                for i in 0..8 {
556                    let theta = i as f64 * std::f64::consts::FRAC_PI_4;
557                    let offset = (pos.0 + r * theta.cos(), pos.1 + r * theta.sin());
558                    self.draw_text_pass(
559                        text,
560                        offset,
561                        style.anchor.clone(),
562                        family,
563                        style.size,
564                        font_style,
565                        angle_i,
566                        halo_color,
567                    )?;
568                }
569            }
570        }
571
572        self.draw_text_pass(
573            text,
574            pos,
575            style.anchor.clone(),
576            family,
577            style.size,
578            font_style,
579            angle_i,
580            color,
581        )?;
582        Ok(())
583    }
584
585    /// Rich text (#413, #521): runs laid out with the bundled font's own
586    /// advance widths, so a bold or shifted run doesn't leave a gap.
587    fn draw_rich_text(
588        &mut self,
589        runs: &[crate::render::rich::RichRun],
590        pos: (f64, f64),
591        style: &TextStyle,
592    ) -> Result<(), RenderError> {
593        let family = style.family.as_deref().unwrap_or("sans-serif").to_string();
594        ensure_font(&family);
595        let area = self.area;
596        let placed = crate::render::rich::layout_runs(runs, pos, style, &|t, size, face| {
597            let font_style = match face {
598                crate::render::backend::FontFace::Plain => FontStyle::Normal,
599                crate::render::backend::FontFace::Bold => FontStyle::Bold,
600                crate::render::backend::FontFace::Italic => FontStyle::Italic,
601            };
602            let font = (family.as_str(), size, font_style).into_font();
603            area.estimate_text_size(t, &plotters::prelude::TextStyle::from(font))
604                .map(|(w, _)| w as f64)
605                .unwrap_or_else(|_| crate::render::text::text_width(t, size))
606        });
607        for (text, at, run_style) in placed {
608            self.draw_text(&text, at, &run_style)?;
609        }
610        Ok(())
611    }
612
613    fn draw_polygon(
614        &mut self,
615        points: &[(f64, f64)],
616        style: &RectStyle,
617    ) -> Result<(), RenderError> {
618        if points.len() < 3 {
619            return Ok(());
620        }
621        // #493: inside a clip group (a zoomed panel), the fill is cut to the
622        // panel and the outline drawn as clipped segments, so the cut adds
623        // no edge of its own.
624        if let Some(rect) = self.clip_group() {
625            let clipped = clip_polygon(points, &rect);
626            if let (Some(fill), true) = (style.fill, clipped.len() >= 3) {
627                let pts: Vec<(i32, i32)> = clipped
628                    .iter()
629                    .map(|(x, y)| (*x as i32, *y as i32))
630                    .collect();
631                self.area
632                    .draw(&Polygon::new(pts, to_rgba(fill, style.alpha).filled()))
633                    .map_err(map_err)?;
634            }
635            if let (Some(stroke), true) = (style.stroke, style.stroke_width > 0.0) {
636                let width = (style.stroke_width as u32).max(1);
637                let n = points.len();
638                for i in 0..n {
639                    let (a, b) = (points[i], points[(i + 1) % n]);
640                    if let Some((p, q)) = clip_line_segment(a.0, a.1, b.0, b.1, &rect) {
641                        self.area
642                            .draw(&PathElement::new(
643                                vec![(p.0 as i32, p.1 as i32), (q.0 as i32, q.1 as i32)],
644                                to_rgba(stroke, style.alpha).stroke_width(width),
645                            ))
646                            .map_err(map_err)?;
647                    }
648                }
649            }
650            return Ok(());
651        }
652        let int_points: Vec<(i32, i32)> =
653            points.iter().map(|(x, y)| (*x as i32, *y as i32)).collect();
654
655        if let Some(fill) = style.fill {
656            let fill_color = to_rgba(fill, style.alpha);
657            self.area
658                .draw(&Polygon::new(int_points.clone(), fill_color.filled()))
659                .map_err(map_err)?;
660        }
661        // Outline, as the native SVG backend draws it (it was never stroked
662        // here, so violins / polygons / notched boxes lost their border in
663        // PNG output).
664        if let (Some(stroke), true) = (style.stroke, style.stroke_width > 0.0) {
665            let mut pts = int_points;
666            pts.push(pts[0]);
667            let width = (style.stroke_width as u32).max(1);
668            self.area
669                .draw(&PathElement::new(
670                    pts,
671                    to_rgba(stroke, style.alpha).stroke_width(width),
672                ))
673                .map_err(map_err)?;
674        }
675
676        Ok(())
677    }
678
679    /// Even-odd fill across every ring at once (`geom_sf`'s polygon holes,
680    /// #178) — plotters' own `Polygon` element has no hole support, so the
681    /// fill is a per-pixel scanline (as the `canvas` backend's own
682    /// `fill_polygon_rings` does), then each ring is stroked the same way
683    /// (plotters' [`PathElement`], one closed path per ring).
684    fn draw_polygon_rings(
685        &mut self,
686        rings: &[Vec<(f64, f64)>],
687        style: &RectStyle,
688    ) -> Result<(), RenderError> {
689        if let Some(fill) = style.fill {
690            let color = to_rgba(fill, style.alpha);
691            let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);
692            for ring in rings {
693                if ring.len() < 3 {
694                    continue;
695                }
696                for p in ring {
697                    y0 = y0.min(p.1);
698                    y1 = y1.max(p.1);
699                }
700            }
701            if y0.is_finite() && y1.is_finite() {
702                let (y0, y1) = (y0.floor() as i32, y1.ceil() as i32);
703                for y in y0..=y1 {
704                    let yc = y as f64 + 0.5;
705                    let mut xs: Vec<f64> = Vec::new();
706                    for ring in rings {
707                        let n = ring.len();
708                        if n < 3 {
709                            continue;
710                        }
711                        for i in 0..n {
712                            let (ax, ay) = ring[i];
713                            let (bx, by) = ring[(i + 1) % n];
714                            if (ay <= yc && by > yc) || (by <= yc && ay > yc) {
715                                xs.push(ax + (yc - ay) / (by - ay) * (bx - ax));
716                            }
717                        }
718                    }
719                    xs.sort_by(|p, q| p.total_cmp(q));
720                    for span in xs.chunks(2) {
721                        if let [xa, xb] = span {
722                            for x in xa.round() as i32..=xb.round() as i32 {
723                                self.area.draw_pixel((x, y), &color).map_err(map_err)?;
724                            }
725                        }
726                    }
727                }
728            }
729        }
730        if let Some(stroke) = style.stroke {
731            let stroke_color = to_rgba(stroke, style.alpha);
732            let width = if style.stroke_width > 0.0 {
733                (style.stroke_width as u32).max(1)
734            } else {
735                0
736            };
737            if width > 0 {
738                for ring in rings {
739                    if ring.len() < 3 {
740                        continue;
741                    }
742                    let mut pts: Vec<(i32, i32)> =
743                        ring.iter().map(|(x, y)| (*x as i32, *y as i32)).collect();
744                    pts.push(pts[0]);
745                    self.area
746                        .draw(&PathElement::new(pts, stroke_color.stroke_width(width)))
747                        .map_err(map_err)?;
748                }
749            }
750        }
751        Ok(())
752    }
753
754    fn draw_shape(
755        &mut self,
756        center: (f64, f64),
757        radius: f64,
758        style: &PointStyle,
759    ) -> Result<(), RenderError> {
760        // Clip: skip shapes entirely outside the plot area
761        if !point_in_rect(center.0, center.1, &self.clip_area()) {
762            return Ok(());
763        }
764        let color = to_rgba(style.color, style.alpha);
765        let (cx, cy) = (center.0 as i32, center.1 as i32);
766        let r = radius as i32;
767
768        match style.shape {
769            PointShape::Circle => self.draw_circle(center, radius, style),
770            PointShape::Square => {
771                let tl = (cx - r, cy - r);
772                let br = (cx + r, cy + r);
773                if style.filled {
774                    self.area
775                        .draw(&plotters::prelude::Rectangle::new([tl, br], color.filled()))
776                        .map_err(map_err)?;
777                } else {
778                    self.area
779                        .draw(&plotters::prelude::Rectangle::new(
780                            [tl, br],
781                            color.stroke_width(1),
782                        ))
783                        .map_err(map_err)?;
784                }
785                Ok(())
786            }
787            PointShape::Triangle => {
788                let pts = vec![(cx, cy - r), (cx - r, cy + r), (cx + r, cy + r)];
789                if style.filled {
790                    self.area
791                        .draw(&Polygon::new(pts, color.filled()))
792                        .map_err(map_err)?;
793                } else {
794                    let outline = vec![
795                        (cx, cy - r),
796                        (cx - r, cy + r),
797                        (cx + r, cy + r),
798                        (cx, cy - r),
799                    ];
800                    self.area
801                        .draw(&PathElement::new(outline, color.stroke_width(1)))
802                        .map_err(map_err)?;
803                }
804                Ok(())
805            }
806            PointShape::Diamond => {
807                let pts = vec![(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)];
808                if style.filled {
809                    self.area
810                        .draw(&Polygon::new(pts, color.filled()))
811                        .map_err(map_err)?;
812                } else {
813                    let outline = vec![
814                        (cx, cy - r),
815                        (cx + r, cy),
816                        (cx, cy + r),
817                        (cx - r, cy),
818                        (cx, cy - r),
819                    ];
820                    self.area
821                        .draw(&PathElement::new(outline, color.stroke_width(1)))
822                        .map_err(map_err)?;
823                }
824                Ok(())
825            }
826            PointShape::Cross => {
827                // X shape
828                self.area
829                    .draw(&PathElement::new(
830                        vec![(cx - r, cy - r), (cx + r, cy + r)],
831                        color.stroke_width(1),
832                    ))
833                    .map_err(map_err)?;
834                self.area
835                    .draw(&PathElement::new(
836                        vec![(cx - r, cy + r), (cx + r, cy - r)],
837                        color.stroke_width(1),
838                    ))
839                    .map_err(map_err)?;
840                Ok(())
841            }
842            PointShape::Plus => {
843                // + shape
844                self.area
845                    .draw(&PathElement::new(
846                        vec![(cx - r, cy), (cx + r, cy)],
847                        color.stroke_width(1),
848                    ))
849                    .map_err(map_err)?;
850                self.area
851                    .draw(&PathElement::new(
852                        vec![(cx, cy - r), (cx, cy + r)],
853                        color.stroke_width(1),
854                    ))
855                    .map_err(map_err)?;
856                Ok(())
857            }
858        }
859    }
860
861    /// #325: the visible part, scaled, as one bitmap element (an `<image>`
862    /// in plotters' SVG output). Opaque: plotters bitmaps carry no alpha.
863    fn draw_image(
864        &mut self,
865        bytes: &[u8],
866        rect: &Rect,
867        clip: &Rect,
868        _alpha: f64,
869    ) -> Result<(), RenderError> {
870        let (w, h) = self.area.dim_in_pixel();
871        let Some((pos, img)) = crate::render::raster::decode_visible(bytes, rect, clip, w, h)
872        else {
873            return Ok(());
874        };
875        let rgb = image::DynamicImage::ImageRgba8(img).to_rgb8();
876        let element: plotters::element::BitMapElement<(i32, i32)> =
877            (pos, image::DynamicImage::ImageRgb8(rgb)).into();
878        self.area.draw(&element).map_err(map_err)?;
879        Ok(())
880    }
881
882    fn plot_area(&self) -> Rect {
883        self.plot_area.clone()
884    }
885
886    fn total_area(&self) -> Rect {
887        self.total_area.clone()
888    }
889
890    fn corner_claims(&self) -> Vec<Rect> {
891        self.corner_claims.clone()
892    }
893    fn claim_corner_box(&mut self, rect: Rect) {
894        self.corner_claims.push(rect);
895    }
896    fn clear_corner_claims(&mut self) {
897        self.corner_claims.clear();
898    }
899}
900
901impl<'a, DB: DrawingBackend> PlottersAdapter<'a, DB> {
902    /// One pass of `text` in `color` at `pos` — factored out of
903    /// `draw_text` so #229's halo can run it several times (once per
904    /// offset, in `bg_colour`) before the normal pass.
905    ///
906    /// (Kept in its own inherent `impl` block: a trait `impl` can't be
907    /// split across two blocks, so this can't live inside
908    /// `impl DrawBackend for PlottersAdapter` alongside the trait's own
909    /// methods.)
910    #[allow(clippy::too_many_arguments)]
911    fn draw_text_pass(
912        &mut self,
913        text: &str,
914        pos: (f64, f64),
915        anchor: TextAnchor,
916        family: &str,
917        size: f64,
918        font_style: FontStyle,
919        angle_i: i32,
920        color: RGBAColor,
921    ) -> Result<(), RenderError> {
922        // #521: the style goes in with the family — `FontDesc::style` keeps
923        // the regular face's glyph data, so bold / italic never showed.
924        let font = (family, size, font_style).into_font();
925
926        let pos_adj = match anchor {
927            TextAnchor::Start => plotters::style::text_anchor::Pos::new(
928                plotters::style::text_anchor::HPos::Left,
929                plotters::style::text_anchor::VPos::Center,
930            ),
931            TextAnchor::Middle => plotters::style::text_anchor::Pos::new(
932                plotters::style::text_anchor::HPos::Center,
933                plotters::style::text_anchor::VPos::Center,
934            ),
935            TextAnchor::End => plotters::style::text_anchor::Pos::new(
936                plotters::style::text_anchor::HPos::Right,
937                plotters::style::text_anchor::VPos::Center,
938            ),
939        };
940
941        if angle_i != 0 {
942            // #521: the anchor and the face apply along the rotated text, as
943            // in the SVG (`rotate(angle x y)` about the anchor point) —
944            // plotters places the anchor in the text's own frame, then
945            // rotates about `pos`.
946            let font_transform = match angle_i.rem_euclid(360) {
947                80..=100 => FontTransform::Rotate90,
948                170..=190 => FontTransform::Rotate180,
949                // 270° or -90° or 45° approximation (common ggplot2 x-axis rotation)
950                _ => FontTransform::Rotate270,
951            };
952
953            let text_style = plotters::prelude::TextStyle::from(font)
954                .color(&color)
955                .transform(font_transform)
956                .pos(pos_adj);
957
958            self.area
959                .draw_text(text, &text_style, (pos.0 as i32, pos.1 as i32))
960                .map_err(map_err)?;
961        } else {
962            let text_style = plotters::prelude::TextStyle::from(font)
963                .color(&color)
964                .pos(pos_adj);
965            self.area
966                .draw_text(text, &text_style, (pos.0 as i32, pos.1 as i32))
967                .map_err(map_err)?;
968        }
969
970        Ok(())
971    }
972}
973
974#[cfg(test)]
975mod clip_polygon_tests {
976    use super::*;
977
978    fn rect() -> Rect {
979        Rect {
980            x: 0.0,
981            y: 0.0,
982            width: 10.0,
983            height: 10.0,
984        }
985    }
986
987    /// #493: a polygon reaching past the panel is cut at its edge.
988    #[test]
989    fn cuts_a_polygon_at_the_rect() {
990        let tri = [(2.0, 2.0), (8.0, 2.0), (5.0, -6.0)];
991        let out = clip_polygon(&tri, &rect());
992        assert!(out.len() >= 3);
993        assert!(out
994            .iter()
995            .all(|&(x, y)| (0.0..=10.0).contains(&x) && (0.0..=10.0).contains(&y)));
996        assert!(out.iter().any(|&(_, y)| y == 0.0), "{out:?}");
997    }
998
999    #[test]
1000    fn keeps_an_inside_polygon_and_drops_an_outside_one() {
1001        let inside = [(1.0, 1.0), (4.0, 1.0), (4.0, 4.0)];
1002        assert_eq!(clip_polygon(&inside, &rect()), inside.to_vec());
1003        let outside = [(20.0, 20.0), (30.0, 20.0), (30.0, 30.0)];
1004        assert!(clip_polygon(&outside, &rect()).is_empty());
1005    }
1006}