Skip to main content

ggplot_rs/geom/
segment.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::geom::arrow::{draw_heads, heads, Arrow};
5use crate::position::identity::PositionIdentity;
6use crate::position::Position;
7use crate::render::backend::{DrawBackend, LineEnd, LineStyle, Linetype};
8use crate::render::RenderError;
9use crate::scale::ScaleSet;
10use crate::stat::identity::StatIdentity;
11use crate::stat::Stat;
12use crate::theme::Theme;
13
14use super::{Geom, GeomParams};
15
16/// Segment geometry — line segments from (x, y) to (xend, yend).
17pub struct GeomSegment {
18    pub color: (u8, u8, u8),
19    pub width: f64,
20    pub alpha: f64,
21    /// An optional arrowhead drawn at the segment's end(s) — see
22    /// [`crate::geom::arrow::arrow`].
23    pub arrow: Option<Arrow>,
24    /// Line cap style (R grid's `lineend`).
25    pub lineend: LineEnd,
26}
27
28impl Default for GeomSegment {
29    fn default() -> Self {
30        GeomSegment {
31            color: (0, 0, 0),
32            width: 1.0,
33            alpha: 1.0,
34            arrow: None,
35            lineend: LineEnd::Butt,
36        }
37    }
38}
39
40impl GeomSegment {
41    /// Fixed stroke colour, used when no `color` aesthetic is mapped.
42    pub fn color(mut self, color: (u8, u8, u8)) -> Self {
43        self.color = color;
44        self
45    }
46
47    /// Sets `width` (the stroke width in pixels).
48    pub fn linewidth(mut self, width: f64) -> Self {
49        self.width = width;
50        self
51    }
52
53    /// Fixed opacity, used when no `alpha` aesthetic is mapped.
54    pub fn alpha(mut self, alpha: f64) -> Self {
55        self.alpha = alpha;
56        self
57    }
58
59    /// Draw an arrowhead at the end(s) — see [`arrow()`](crate::geom::arrow::arrow).
60    pub fn arrow(mut self, arrow: Arrow) -> Self {
61        self.arrow = Some(arrow);
62        self
63    }
64
65    /// Line cap style (R grid's `lineend`).
66    pub fn lineend(mut self, lineend: LineEnd) -> Self {
67        self.lineend = lineend;
68        self
69    }
70}
71
72impl Geom for GeomSegment {
73    fn draw(
74        &self,
75        data: &DataFrame,
76        coord: &dyn Coord,
77        scales: &ScaleSet,
78        _theme: &Theme,
79        backend: &mut dyn DrawBackend,
80    ) -> Result<(), RenderError> {
81        let x_col = data
82            .column("x")
83            .ok_or(RenderError::MissingAesthetic("x".into()))?;
84        let y_col = data
85            .column("y")
86            .ok_or(RenderError::MissingAesthetic("y".into()))?;
87        let xend_col = data
88            .column("xend")
89            .ok_or(RenderError::MissingAesthetic("xend".into()))?;
90        let yend_col = data
91            .column("yend")
92            .ok_or(RenderError::MissingAesthetic("yend".into()))?;
93        let color_col = data.column("color");
94        let linetype_col = data.column("linetype");
95        let alpha_col = data.column("alpha");
96        let linewidth_col = data.column("linewidth");
97
98        let plot_area = backend.plot_area();
99        let x_scale = scales.get(&Aesthetic::X);
100        let y_scale = scales.get(&Aesthetic::Y);
101
102        for i in 0..data.nrows() {
103            let nx1 = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
104            let ny1 = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
105            let nx2 = x_scale.map(|s| s.map(&xend_col[i])).unwrap_or(0.0);
106            let ny2 = y_scale.map(|s| s.map(&yend_col[i])).unwrap_or(0.0);
107
108            let (px1, py1) = coord.transform((nx1, ny1), &plot_area);
109            let (px2, py2) = coord.transform((nx2, ny2), &plot_area);
110
111            let line_color = color_col
112                .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[i]))
113                .unwrap_or(self.color);
114            let lt = linetype_col
115                .and_then(|lc| scales.map_linetype(&lc[i]))
116                .unwrap_or(Linetype::Solid);
117            let alpha = alpha_col
118                .and_then(|ac| scales.map_alpha(&ac[i]).or_else(|| ac[i].as_f64()))
119                .filter(|a| a.is_finite())
120                .unwrap_or(self.alpha);
121            let width = linewidth_col
122                .and_then(|lc| scales.map_linewidth(&lc[i]))
123                .unwrap_or(self.width);
124            super::set_row_extras(backend, data, i);
125
126            let path = [(px1, py1), (px2, py2)];
127            backend.draw_line(
128                &path,
129                &LineStyle {
130                    color: line_color,
131                    alpha,
132                    width,
133                    linetype: lt,
134                    lineend: self.lineend,
135                },
136            )?;
137
138            if let Some(arrow) = &self.arrow {
139                let hs = heads(&path, arrow, width);
140                draw_heads(backend, &hs, arrow, line_color, alpha, width)?;
141            }
142        }
143        super::clear_mark(backend);
144        super::clear_row_extras(backend);
145
146        Ok(())
147    }
148
149    fn required_aes(&self) -> Vec<Aesthetic> {
150        vec![Aesthetic::X, Aesthetic::Y, Aesthetic::Xend, Aesthetic::Yend]
151    }
152
153    fn default_stat(&self) -> Box<dyn Stat> {
154        Box::new(StatIdentity)
155    }
156    fn default_position(&self) -> Box<dyn Position> {
157        Box::new(PositionIdentity)
158    }
159    fn default_params(&self) -> GeomParams {
160        GeomParams::default()
161    }
162    fn name(&self) -> &str {
163        "segment"
164    }
165
166    fn consumes_tooltips(&self) -> bool {
167        true
168    }
169
170    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
171        if let (true, Some(ink)) = (self.color == (0, 0, 0), el.ink) {
172            self.color = ink;
173        }
174    }
175
176    fn set_series_color(&mut self, color: (u8, u8, u8)) {
177        self.color = color;
178    }
179}
180
181/// `geom_calendar`'s month outlines: segments styled at draw time by the
182/// theme's [`calendar_month_border`](Theme::calendar_month_border), so a theme
183/// set after the calendar still applies (a blank element hides them).
184pub(crate) struct GeomCalendarBorder;
185
186impl Geom for GeomCalendarBorder {
187    fn draw(
188        &self,
189        data: &DataFrame,
190        coord: &dyn Coord,
191        scales: &ScaleSet,
192        theme: &Theme,
193        backend: &mut dyn DrawBackend,
194    ) -> Result<(), RenderError> {
195        let el = &theme.calendar_month_border;
196        if !el.visible {
197            return Ok(());
198        }
199        GeomSegment {
200            color: el.color,
201            width: el.width,
202            alpha: 1.0,
203            ..Default::default()
204        }
205        .draw(data, coord, scales, theme, backend)
206    }
207
208    fn required_aes(&self) -> Vec<Aesthetic> {
209        GeomSegment::default().required_aes()
210    }
211    fn default_stat(&self) -> Box<dyn Stat> {
212        Box::new(StatIdentity)
213    }
214    fn default_position(&self) -> Box<dyn Position> {
215        Box::new(PositionIdentity)
216    }
217    fn default_params(&self) -> GeomParams {
218        GeomParams::default()
219    }
220    fn name(&self) -> &str {
221        "segment"
222    }
223
224    fn consumes_tooltips(&self) -> bool {
225        true
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use crate::data::Value;
232    use crate::geom::arrow::{arrow, ArrowType};
233    use crate::prelude::*;
234    use crate::render::backend::LineEnd;
235
236    fn plot() -> GGPlot {
237        GGPlot::new(vec![
238            ("x".into(), vec![Value::Float(0.0), Value::Float(0.2)]),
239            ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
240            ("xend".into(), vec![Value::Float(1.0), Value::Float(0.8)]),
241            ("yend".into(), vec![Value::Float(0.5), Value::Float(0.3)]),
242        ])
243        .aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
244    }
245
246    #[test]
247    fn arrow_closed_gives_one_tagged_polygon_per_row_with_fill_eq_stroke() {
248        let svg = plot()
249            .geom_segment_with(GeomSegment::default().arrow(arrow().closed()))
250            .render_svg_native_with_size(200, 200)
251            .unwrap();
252        let count = svg.matches("data-part=\"arrow\"").count();
253        assert_eq!(count, 2, "one arrowhead per row: {svg}");
254        assert!(svg.contains("aria-hidden=\"true\""));
255        // Each arrow mark is a polygon with fill == stroke.
256        for part in svg.split("<polygon").skip(1) {
257            if part.contains("data-part=\"arrow\"") {
258                let fill = part
259                    .split("fill=\"")
260                    .nth(1)
261                    .unwrap()
262                    .split('"')
263                    .next()
264                    .unwrap();
265                let stroke = part
266                    .split("stroke=\"")
267                    .nth(1)
268                    .unwrap()
269                    .split('"')
270                    .next()
271                    .unwrap();
272                assert_eq!(fill, stroke);
273            }
274        }
275    }
276
277    #[test]
278    fn arrow_open_uses_a_three_point_polyline_not_a_polygon() {
279        let a = arrow(); // ArrowType::Open is the default.
280        assert_eq!(a.kind, ArrowType::Open);
281        let svg = plot()
282            .geom_segment_with(GeomSegment::default().arrow(a))
283            .render_svg_native_with_size(200, 200)
284            .unwrap();
285        assert!(svg.contains("data-part=\"arrow\""));
286        assert!(!svg.contains("<polygon"));
287    }
288
289    #[test]
290    fn lineend_round_gives_stroke_linecap_round() {
291        let svg = plot()
292            .geom_segment_with(GeomSegment::default().lineend(LineEnd::Round))
293            .render_svg_native_with_size(200, 200)
294            .unwrap();
295        assert!(svg.contains("stroke-linecap=\"round\""));
296    }
297
298    #[test]
299    fn default_segment_output_has_no_linecap_or_arrow_marks() {
300        let svg = plot()
301            .geom_segment_with(GeomSegment::default())
302            .render_svg_native_with_size(200, 200)
303            .unwrap();
304        assert!(!svg.contains("stroke-linecap"));
305        assert!(!svg.contains("data-part"));
306    }
307
308    /// `.color()`/`.alpha()`/`.linewidth()` builders actually change the
309    /// rendered stroke, not just the struct's fields.
310    #[test]
311    fn color_alpha_and_linewidth_builders_change_the_rendered_stroke() {
312        let svg = plot()
313            .geom_segment_with(
314                GeomSegment::default()
315                    .color((10, 20, 30))
316                    .alpha(0.4)
317                    .linewidth(5.0),
318            )
319            .render_svg_native_with_size(200, 200)
320            .unwrap();
321        assert!(svg.contains("stroke=\"#0A141E\""));
322        assert!(svg.contains("stroke-opacity=\"0.400\""));
323        assert!(svg.contains("stroke-width=\"5.00\""));
324    }
325
326    /// `ScaleSet::ensure_scale` auto-creates a `ScaleLinewidthContinuous`
327    /// when `linewidth` is mapped without an explicit `.scale_linewidth(...)`
328    /// — the common case (most callers never configure the scale by hand).
329    #[test]
330    fn mapping_linewidth_without_an_explicit_scale_still_renders_a_range_of_widths() {
331        let svg = GGPlot::new(vec![
332            ("x".into(), vec![Value::Float(0.0), Value::Float(0.0)]),
333            ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
334            ("xend".into(), vec![Value::Float(1.0), Value::Float(1.0)]),
335            ("yend".into(), vec![Value::Float(0.5), Value::Float(0.3)]),
336            ("w".into(), vec![Value::Float(1.0), Value::Float(10.0)]),
337        ])
338        .aes(
339            Aes::new()
340                .x("x")
341                .y("y")
342                .xend("xend")
343                .yend("yend")
344                .linewidth("w"),
345        )
346        .geom_segment()
347        // No .scale_linewidth(...) call: ensure_scale must supply the
348        // default ScaleLinewidthContinuous (range 1.0..6.0).
349        .render_svg_native_with_size(200, 200)
350        .unwrap();
351
352        assert!(svg.contains("stroke-width=\"1.00\""));
353        assert!(svg.contains("stroke-width=\"6.00\""));
354    }
355}