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