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 set_series_color(&mut self, color: (u8, u8, u8)) {
167        self.color = color;
168    }
169}
170
171/// `geom_calendar`'s month outlines: segments styled at draw time by the
172/// theme's [`calendar_month_border`](Theme::calendar_month_border), so a theme
173/// set after the calendar still applies (a blank element hides them).
174pub(crate) struct GeomCalendarBorder;
175
176impl Geom for GeomCalendarBorder {
177    fn draw(
178        &self,
179        data: &DataFrame,
180        coord: &dyn Coord,
181        scales: &ScaleSet,
182        theme: &Theme,
183        backend: &mut dyn DrawBackend,
184    ) -> Result<(), RenderError> {
185        let el = &theme.calendar_month_border;
186        if !el.visible {
187            return Ok(());
188        }
189        GeomSegment {
190            color: el.color,
191            width: el.width,
192            alpha: 1.0,
193            ..Default::default()
194        }
195        .draw(data, coord, scales, theme, backend)
196    }
197
198    fn required_aes(&self) -> Vec<Aesthetic> {
199        GeomSegment::default().required_aes()
200    }
201    fn default_stat(&self) -> Box<dyn Stat> {
202        Box::new(StatIdentity)
203    }
204    fn default_position(&self) -> Box<dyn Position> {
205        Box::new(PositionIdentity)
206    }
207    fn default_params(&self) -> GeomParams {
208        GeomParams::default()
209    }
210    fn name(&self) -> &str {
211        "segment"
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use crate::data::Value;
218    use crate::geom::arrow::{arrow, ArrowType};
219    use crate::prelude::*;
220    use crate::render::backend::LineEnd;
221
222    fn plot() -> GGPlot {
223        GGPlot::new(vec![
224            ("x".into(), vec![Value::Float(0.0), Value::Float(0.2)]),
225            ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
226            ("xend".into(), vec![Value::Float(1.0), Value::Float(0.8)]),
227            ("yend".into(), vec![Value::Float(0.5), Value::Float(0.3)]),
228        ])
229        .aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
230    }
231
232    #[test]
233    fn arrow_closed_gives_one_tagged_polygon_per_row_with_fill_eq_stroke() {
234        let svg = plot()
235            .geom_segment_with(GeomSegment::default().arrow(arrow().closed()))
236            .render_svg_native_with_size(200, 200)
237            .unwrap();
238        let count = svg.matches("data-part=\"arrow\"").count();
239        assert_eq!(count, 2, "one arrowhead per row: {svg}");
240        assert!(svg.contains("aria-hidden=\"true\""));
241        // Each arrow mark is a polygon with fill == stroke.
242        for part in svg.split("<polygon").skip(1) {
243            if part.contains("data-part=\"arrow\"") {
244                let fill = part
245                    .split("fill=\"")
246                    .nth(1)
247                    .unwrap()
248                    .split('"')
249                    .next()
250                    .unwrap();
251                let stroke = part
252                    .split("stroke=\"")
253                    .nth(1)
254                    .unwrap()
255                    .split('"')
256                    .next()
257                    .unwrap();
258                assert_eq!(fill, stroke);
259            }
260        }
261    }
262
263    #[test]
264    fn arrow_open_uses_a_three_point_polyline_not_a_polygon() {
265        let a = arrow(); // ArrowType::Open is the default.
266        assert_eq!(a.kind, ArrowType::Open);
267        let svg = plot()
268            .geom_segment_with(GeomSegment::default().arrow(a))
269            .render_svg_native_with_size(200, 200)
270            .unwrap();
271        assert!(svg.contains("data-part=\"arrow\""));
272        assert!(!svg.contains("<polygon"));
273    }
274
275    #[test]
276    fn lineend_round_gives_stroke_linecap_round() {
277        let svg = plot()
278            .geom_segment_with(GeomSegment::default().lineend(LineEnd::Round))
279            .render_svg_native_with_size(200, 200)
280            .unwrap();
281        assert!(svg.contains("stroke-linecap=\"round\""));
282    }
283
284    #[test]
285    fn default_segment_output_has_no_linecap_or_arrow_marks() {
286        let svg = plot()
287            .geom_segment_with(GeomSegment::default())
288            .render_svg_native_with_size(200, 200)
289            .unwrap();
290        assert!(!svg.contains("stroke-linecap"));
291        assert!(!svg.contains("data-part"));
292    }
293
294    /// `.color()`/`.alpha()`/`.linewidth()` builders actually change the
295    /// rendered stroke, not just the struct's fields.
296    #[test]
297    fn color_alpha_and_linewidth_builders_change_the_rendered_stroke() {
298        let svg = plot()
299            .geom_segment_with(
300                GeomSegment::default()
301                    .color((10, 20, 30))
302                    .alpha(0.4)
303                    .linewidth(5.0),
304            )
305            .render_svg_native_with_size(200, 200)
306            .unwrap();
307        assert!(svg.contains("stroke=\"#0A141E\""));
308        assert!(svg.contains("stroke-opacity=\"0.400\""));
309        assert!(svg.contains("stroke-width=\"5.00\""));
310    }
311
312    /// `ScaleSet::ensure_scale` auto-creates a `ScaleLinewidthContinuous`
313    /// when `linewidth` is mapped without an explicit `.scale_linewidth(...)`
314    /// — the common case (most callers never configure the scale by hand).
315    #[test]
316    fn mapping_linewidth_without_an_explicit_scale_still_renders_a_range_of_widths() {
317        let svg = GGPlot::new(vec![
318            ("x".into(), vec![Value::Float(0.0), Value::Float(0.0)]),
319            ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
320            ("xend".into(), vec![Value::Float(1.0), Value::Float(1.0)]),
321            ("yend".into(), vec![Value::Float(0.5), Value::Float(0.3)]),
322            ("w".into(), vec![Value::Float(1.0), Value::Float(10.0)]),
323        ])
324        .aes(
325            Aes::new()
326                .x("x")
327                .y("y")
328                .xend("xend")
329                .yend("yend")
330                .linewidth("w"),
331        )
332        .geom_segment()
333        // No .scale_linewidth(...) call: ensure_scale must supply the
334        // default ScaleLinewidthContinuous (range 1.0..6.0).
335        .render_svg_native_with_size(200, 200)
336        .unwrap();
337
338        assert!(svg.contains("stroke-width=\"1.00\""));
339        assert!(svg.contains("stroke-width=\"6.00\""));
340    }
341}