1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! # Path iterators
//!
//! Composable tools to iterate over paths.
//!
//! ## Overview
//!
//! TODO
//!
//! ## Example
//!
//! TODO
//!

use std::iter;

use core::{ PathEvent, SvgEvent, FlattenedEvent, PathState };
use core::math::*;
use bezier::{
    QuadraticBezierSegment, CubicBezierSegment,
    QuadraticFlatteningIter, CubicFlatteningIter
};

/// Convenience for algorithms which prefer to iterate over segments directly rather than
/// path events.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Segment {
    Line(Point, Point),
    QuadraticBezier(Point, Point, Point),
    CubicBezier(Point, Point, Point, Point),
}

/// An extension to the common Iterator interface, that adds information which is useful when
/// chaining path-specific iterators.
pub trait PathIterator : Iterator<Item=PathEvent> + Sized {
    /// The returned structure exposes the current position, the first position in the current
    /// sub-path, and the position of the last control point.
    fn get_state(&self) -> &PathState;

    /// Returns an iterator that turns curves into line segments.
    fn flattened(self, tolerance: f32) -> FlatteningIter<Self> { FlatteningIter::new(tolerance, self) }

    /// Returns an iterator of SVG events.
    fn svg_iter(self) -> iter::Map<Self, fn(PathEvent)->SvgEvent> {
        self.map(path_to_svg_event)
    }
}

/// An extension to the common Iterator interface, that adds information which is useful when
/// chaining path-specific iterators.
pub trait SvgIterator : Iterator<Item=SvgEvent> + Sized {
    /// The returned structure exposes the current position, the first position in the current
    /// sub-path, and the position of the last control point.
    fn get_state(&self) -> &PathState;

    /// Returns an iterator of FlattenedEvents, turning curves into sequences of line segments.
    fn flattened(self, tolerance: f32) -> FlatteningIter<SvgToPathIter<Self>> { self.path_iter().flattened(tolerance) }

    /// Returns an iterator of path events.
    fn path_iter(self) -> SvgToPathIter<Self> { SvgToPathIter::new(self) }
}

/// An extension to the common Iterator interface, that adds information which is useful when
/// chaining path-specific iterators.
pub trait FlattenedIterator : Iterator<Item=FlattenedEvent> + Sized {
    /// The returned structure exposes the current position, the first position in the current
    /// sub-path, and the position of the last control point.
    fn get_state(&self) -> &PathState;

    /// Returns an iterator of path events.
    fn path_iter(self) -> iter::Map<Self, fn(FlattenedEvent)->PathEvent> {
        self.map(flattened_to_path_event)
    }

    /// Returns an iterator of svg events.
    fn svg_iter(self) -> iter::Map<Self, fn(FlattenedEvent)->SvgEvent> {
        self.map(flattened_to_svg_event)
    }
}

/// Consumes an iterator of path events and yields segments.
pub struct SegmentIterator<PathIt> {
    it: PathIt,
    state: PathState,
    in_sub_path: bool,
}

impl<'l, PathIt:'l+Iterator<Item=PathEvent>> SegmentIterator<PathIt> {
    /// Constructor.
    pub fn new(it: PathIt) -> Self {
        SegmentIterator {
            it: it,
            state: PathState::new(),
            in_sub_path: false,
        }
    }

    fn close(&mut self) -> Option<Segment> {
        let first = self.state.first;
        self.state.close();
        self.in_sub_path = false;
        if first != self.state.current {
            Some(Segment::Line(first, self.state.current))
        } else {
            self.next()
        }
    }
}

impl<'l, PathIt:'l+Iterator<Item=PathEvent>> Iterator
for SegmentIterator<PathIt> {
    type Item = Segment;
    fn next(&mut self) -> Option<Segment> {
        return match self.it.next() {
            Some(PathEvent::MoveTo(to)) => {
                let first = self.state.first;
                self.state.move_to(to);
                if self.in_sub_path && first != self.state.current {
                    Some(Segment::Line(first, self.state.current))
                } else {
                    self.in_sub_path = true;
                    self.next()
                }
            }
            Some(PathEvent::LineTo(to)) => {
                self.in_sub_path = true;
                let from = self.state.current;
                self.state.line_to(to);
                Some(Segment::Line(from, to))
            }
            Some(PathEvent::QuadraticTo(ctrl, to)) => {
                self.in_sub_path = true;
                let from = self.state.current;
                self.state.curve_to(ctrl, to);
                Some(Segment::QuadraticBezier(from, ctrl, to))
            }
            Some(PathEvent::CubicTo(ctrl1, ctrl2, to)) => {
                self.in_sub_path = true;
                let from = self.state.current;
                self.state.curve_to(ctrl2, to);
                Some(Segment::CubicBezier(from, ctrl1, ctrl2, to))
            }
            Some(PathEvent::Close) => { self.close() }
            None => { None }
        };
    }
}

pub struct SvgToPathIter<SvgIter> {
    it: SvgIter,
}

impl<SvgIter> SvgToPathIter<SvgIter> {
    pub fn new(it: SvgIter) -> Self { SvgToPathIter { it: it } }
}

impl<SvgIter> PathIterator for SvgToPathIter<SvgIter>
where SvgIter : SvgIterator {
    fn get_state(&self) -> &PathState { self.it.get_state() }
}

impl<SvgIter> Iterator for SvgToPathIter<SvgIter>
where SvgIter: SvgIterator {
    type Item = PathEvent;
    fn next(&mut self) -> Option<PathEvent> {
        return match self.it.next() {
            Some(svg_evt) => { Some(self.get_state().svg_to_path_event(svg_evt)) }
            None => { None }
        }
    }
}

/// An iterator that consumes an PathIterator and yields FlattenedEvents.
pub struct FlatteningIter<Iter> {
    it: Iter,
    current_curve: TmpFlatteningIter,
    tolerance: f32,
}

enum TmpFlatteningIter {
    Quadratic(QuadraticFlatteningIter),
    Cubic(CubicFlatteningIter),
    None,
}

impl<Iter: PathIterator> FlatteningIter<Iter> {
    /// Create the iterator.
    pub fn new(tolerance: f32, it: Iter) -> Self {
        FlatteningIter {
            it: it,
            current_curve: TmpFlatteningIter::None,
            tolerance: tolerance,
        }
    }
}

impl<Iter> FlattenedIterator for FlatteningIter<Iter>
where Iter : PathIterator {
    fn get_state(&self) -> &PathState { self.it.get_state() }
}

impl<Iter> Iterator for FlatteningIter<Iter>
where Iter: PathIterator {
    type Item = FlattenedEvent;
    fn next(&mut self) -> Option<FlattenedEvent> {
        match self.current_curve {
            TmpFlatteningIter::Quadratic(ref mut it) => {
                if let Some(point) = it.next() {
                    return Some(FlattenedEvent::LineTo(point));
                }
            }
            TmpFlatteningIter::Cubic(ref mut it) => {
                if let Some(point) = it.next() {
                    return Some(FlattenedEvent::LineTo(point));
                }
            }
            _ => {}
        }
        self.current_curve = TmpFlatteningIter::None;
        let current = self.get_state().current;
        return match self.it.next() {
            Some(PathEvent::MoveTo(to)) => { Some(FlattenedEvent::MoveTo(to)) }
            Some(PathEvent::LineTo(to)) => { Some(FlattenedEvent::LineTo(to)) }
            Some(PathEvent::Close) => { Some(FlattenedEvent::Close) }
            Some(PathEvent::QuadraticTo(ctrl, to)) => {
                self.current_curve = TmpFlatteningIter::Quadratic(
                    QuadraticBezierSegment {
                        from: current, ctrl: ctrl, to: to
                    }.flattening_iter(self.tolerance)
                );
                return self.next();
            }
            Some(PathEvent::CubicTo(ctrl1, ctrl2, to)) => {
                self.current_curve = TmpFlatteningIter::Cubic(
                    CubicBezierSegment {
                        from: current, ctrl1: ctrl1, ctrl2: ctrl2, to: to
                    }.flattening_iter(self.tolerance)
                );
                return self.next();
            }
            None => { None }
        }
    }
}

/// An adapater iterator that implements SvgIterator on top of an Iterator<Item=SvgEvent>.
pub struct PathStateSvgIter<Iter> {
    it: Iter,
    state: PathState,
}

impl<Iter: Iterator<Item=SvgEvent>> PathStateSvgIter<Iter> {
    pub fn new(it: Iter) -> Self { PathStateSvgIter { it: it, state: PathState::new() } }
}

impl<Iter> SvgIterator for PathStateSvgIter<Iter>
where Iter: Iterator<Item=SvgEvent> {
    fn get_state(&self) -> &PathState { &self.state }
}

impl<Iter: Iterator<Item=SvgEvent>> Iterator for PathStateSvgIter<Iter> {
    type Item = SvgEvent;
    fn next(&mut self) -> Option<SvgEvent> {
        let next = self.it.next();
        if let Some(evt) = next {
            self.state.svg_event(evt);
        }
        return next;
    }
}

/// An adapater iterator that implements PathIterator on top of an Iterator<Item=PatheEvent>.
pub struct PathStateIter<Iter> {
    it: Iter,
    state: PathState,
}

impl<Iter: Iterator<Item=PathEvent>> PathStateIter<Iter> {
  pub fn new(it: Iter) -> Self { PathStateIter { it: it, state: PathState::new() } }
}

impl<Iter> PathIterator for PathStateIter<Iter>
where Iter : Iterator<Item=PathEvent> {
    fn get_state(&self) -> &PathState { &self.state }
}

impl<Iter: Iterator<Item=PathEvent>> Iterator for PathStateIter<Iter> {
    type Item = PathEvent;
    fn next(&mut self) -> Option<PathEvent> {
        let next = self.it.next();
        if let Some(evt) = next {
            self.state.path_event(evt);
        }
        return next;
    }
}

fn flattened_to_path_event(evt: FlattenedEvent) -> PathEvent { evt.to_path_event() }
fn flattened_to_svg_event(evt: FlattenedEvent) -> SvgEvent { evt.to_svg_event() }
fn path_to_svg_event(evt: PathEvent) -> SvgEvent { evt.to_svg_event() }

/*
#[test]
fn test_svg_to_flattened_iter() {
    let mut it = PathStateSvgIter::new(
        [
            SvgEvent::MoveTo(point(1.0, 1.0)),
            SvgEvent::LineTo(point(2.0, 2.0)),
            SvgEvent::LineTo(point(3.0, 3.0)),
            SvgEvent::MoveTo(point(0.0, 0.0)),
            SvgEvent::QuadraticTo(point(1.0, 0.0), point(1.0, 1.0)),
            SvgEvent::MoveTo(point(10.0, 10.0)),
            SvgEvent::CubicTo(point(11.0, 10.0), point(11.0, 11.0), point(11.0, 11.0)),
        ].iter()
    ).flattened(0.05);

    assert_eq!(it.next(), FlattenedEvent::MoveTo(point(1.0, 1.0)));
    assert_eq!(it.next(), FlattenedEvent::LineTo(point(2.0, 2.0)));
    assert_eq!(it.next(), FlattenedEvent::LineTo(point(3.0, 3.0)));
    assert_eq!(it.next(), FlattenedEvent::MoveTo(point(0.0, 0.0)));

    // Flattened quadratic curve.
    loop {
        let evt = it.next();
        if evt == Some(FlattenedEvent::MoveTo(point(10.0, 10.0))) {
            break;
        }
        if let Some(FlattenedEvent::MoveTo(to)) = evt {
            // ok
        } else {
            panic!("Expected a MoveTo event, got {:?}", evt);
        }
    }

    // Flattened cubic curve.
    loop {
        let evt = it.next();
        if evt.is_none() {
            break;
        }
        if let Some(FlattenedEvent::MoveTo(to)) = evt {
            // ok
        } else {
            panic!("Expected a MoveTo event, got {:?}", evt);
        }
    }
}
*/