skia-rs-path 0.2.7

Path geometry and operations for skia-rs
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
//! Path effects (dash, corner, discrete, etc.).
//!
//! Path effects modify how a path is stroked or filled. They can be applied
//! to create dashed lines, rounded corners, jittery edges, and more.

use crate::{
    flatten::{flatten_conic_adaptive, flatten_cubic_adaptive, flatten_quad_adaptive},
    Path, PathBuilder, PathElement,
};
use skia_rs_core::{Point, Scalar};
use std::sync::Arc;

/// A path effect that modifies how a path is stroked or filled.
///
/// Corresponds to Skia's `SkPathEffect`.
pub trait PathEffect: Send + Sync + std::fmt::Debug {
    /// Apply the effect to a path.
    fn apply(&self, path: &Path) -> Option<Path>;

    /// Get the kind of path effect for debugging.
    fn effect_kind(&self) -> PathEffectKind;
}

/// Kind of path effect (for debugging/inspection).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PathEffectKind {
    /// Dash effect.
    Dash,
    /// Corner rounding effect.
    Corner,
    /// Discrete/jitter effect.
    Discrete,
    /// 1D path effect (stamps a path along another).
    Path1D,
    /// 2D path effect (tiles a path in 2D).
    Path2D,
    /// Line 2D effect.
    Line2D,
    /// Trim effect.
    Trim,
    /// Composed effect (one after another).
    Compose,
    /// Sum effect (both applied, results combined).
    Sum,
}

/// A boxed path effect.
pub type PathEffectRef = Arc<dyn PathEffect>;

// =============================================================================
// Dash Effect
// =============================================================================

/// Convert a path with curves to a path containing only lines,
/// using adaptive tolerance for curve flattening. Used by DashEffect
/// so dash intervals can transition mid-curve.
fn flatten_path_to_lines(path: &Path, tolerance: Scalar) -> Path {
    let mut builder = PathBuilder::new();
    let mut current = Point::new(0.0, 0.0);
    let mut contour_start = Point::new(0.0, 0.0);
    let mut points: Vec<Point> = Vec::with_capacity(16);

    for elem in path.iter() {
        match elem {
            PathElement::Move(p) => {
                builder.move_to(p.x, p.y);
                current = p;
                contour_start = p;
            }
            PathElement::Line(p) => {
                builder.line_to(p.x, p.y);
                current = p;
            }
            PathElement::Quad(c, e) => {
                points.clear();
                flatten_quad_adaptive(&mut points, current, c, e, tolerance);
                for p in &points {
                    builder.line_to(p.x, p.y);
                }
                current = e;
            }
            PathElement::Cubic(c1, c2, e) => {
                points.clear();
                flatten_cubic_adaptive(&mut points, current, c1, c2, e, tolerance);
                for p in &points {
                    builder.line_to(p.x, p.y);
                }
                current = e;
            }
            PathElement::Conic(c, e, w) => {
                points.clear();
                flatten_conic_adaptive(&mut points, current, c, e, w, tolerance);
                for p in &points {
                    builder.line_to(p.x, p.y);
                }
                current = e;
            }
            PathElement::Close => {
                builder.close();
                current = contour_start;
            }
        }
    }

    builder.build()
}

/// Dash effect that creates dashed/dotted lines.
///
/// Corresponds to Skia's `SkDashPathEffect`.
#[derive(Debug, Clone)]
pub struct DashEffect {
    /// Dash intervals (on, off, on, off, ...).
    intervals: Vec<Scalar>,
    /// Phase offset into the dash pattern.
    phase: Scalar,
    /// Sum of all intervals (cached).
    interval_sum: Scalar,
}

impl DashEffect {
    /// Create a new dash effect.
    ///
    /// `intervals` must have an even number of entries (on/off pairs).
    /// If odd, the pattern is duplicated to make it even.
    pub fn new(intervals: Vec<Scalar>, phase: Scalar) -> Option<Self> {
        if intervals.is_empty() {
            return None;
        }

        // Ensure even number of intervals
        let intervals = if intervals.len() % 2 != 0 {
            let mut doubled = intervals.clone();
            doubled.extend(intervals.iter().cloned());
            doubled
        } else {
            intervals
        };

        // Validate intervals are positive
        for &interval in &intervals {
            if interval < 0.0 {
                return None;
            }
        }

        let interval_sum: Scalar = intervals.iter().sum();
        if interval_sum <= 0.0 {
            return None;
        }

        Some(Self {
            intervals,
            phase,
            interval_sum,
        })
    }

    /// Create a simple dash pattern (dash length, gap length).
    pub fn simple(dash: Scalar, gap: Scalar) -> Option<Self> {
        Self::new(vec![dash, gap], 0.0)
    }

    /// Create a dotted pattern.
    pub fn dotted(dot_size: Scalar, gap: Scalar) -> Option<Self> {
        Self::new(vec![dot_size, gap], 0.0)
    }

    /// Get the intervals.
    pub fn intervals(&self) -> &[Scalar] {
        &self.intervals
    }

    /// Get the phase.
    pub fn phase(&self) -> Scalar {
        self.phase
    }
}

impl PathEffect for DashEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        if path.is_empty() {
            return None;
        }

        // Pre-flatten curves to lines so dash logic can transition mid-curve.
        let flattened = flatten_path_to_lines(path, 0.5);
        let path = &flattened;

        let mut builder = PathBuilder::new();
        let mut current_pos = Point::zero();
        let mut contour_start = Point::zero();
        #[allow(unused_assignments)]
        let mut _distance_along_contour = 0.0_f32;

        // Adjust phase to be within the interval sum
        let mut phase = self.phase % self.interval_sum;
        if phase < 0.0 {
            phase += self.interval_sum;
        }

        // Find starting interval index and offset
        let (mut interval_idx, interval_offset) = {
            let mut accumulated = 0.0;
            let mut idx = 0;
            while accumulated + self.intervals[idx] <= phase {
                accumulated += self.intervals[idx];
                idx = (idx + 1) % self.intervals.len();
            }
            (idx, phase - accumulated)
        };

        let mut is_on = interval_idx % 2 == 0;
        let mut remaining_in_interval = self.intervals[interval_idx] - interval_offset;

        for element in path.iter() {
            match element {
                PathElement::Move(p) => {
                    current_pos = p;
                    contour_start = p;
                    _distance_along_contour = 0.0;
                    // Reset dash state for new contour
                    let mut accumulated = 0.0;
                    interval_idx = 0;
                    while accumulated + self.intervals[interval_idx] <= phase {
                        accumulated += self.intervals[interval_idx];
                        interval_idx = (interval_idx + 1) % self.intervals.len();
                    }
                    is_on = interval_idx % 2 == 0;
                    remaining_in_interval = self.intervals[interval_idx] - (phase - accumulated);
                    if is_on {
                        builder.move_to(p.x, p.y);
                    }
                }
                PathElement::Line(end) => {
                    let segment_length = current_pos.distance(&end);
                    let mut t = 0.0;

                    while t < 1.0 {
                        let remaining_segment = segment_length * (1.0 - t);

                        if remaining_in_interval >= remaining_segment {
                            // Finish this segment
                            if is_on {
                                builder.line_to(end.x, end.y);
                            }
                            remaining_in_interval -= remaining_segment;
                            t = 1.0;
                        } else {
                            // Partial segment
                            let dt = remaining_in_interval / segment_length;
                            let mid = Point::new(
                                current_pos.x + (end.x - current_pos.x) * (t + dt),
                                current_pos.y + (end.y - current_pos.y) * (t + dt),
                            );

                            if is_on {
                                builder.line_to(mid.x, mid.y);
                            }

                            // Move to next interval
                            interval_idx = (interval_idx + 1) % self.intervals.len();
                            is_on = interval_idx % 2 == 0;
                            remaining_in_interval = self.intervals[interval_idx];

                            if is_on {
                                builder.move_to(mid.x, mid.y);
                            }

                            t += dt;
                        }
                    }

                    current_pos = end;
                }
                PathElement::Close => {
                    // Handle closing line if needed
                    if current_pos != contour_start {
                        let segment_length = current_pos.distance(&contour_start);
                        if segment_length > 0.0 && is_on {
                            builder.line_to(contour_start.x, contour_start.y);
                        }
                    }
                }
                // For curves, we approximate with lines (simplified)
                PathElement::Quad(ctrl, end) => {
                    // Subdivide and treat as lines
                    let steps = 8;
                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = quadratic_point(current_pos, ctrl, end, t);
                        if is_on {
                            builder.line_to(p.x, p.y);
                        }
                    }
                    current_pos = end;
                }
                PathElement::Conic(ctrl, end, _weight) => {
                    // Approximate as quad
                    let steps = 8;
                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = quadratic_point(current_pos, ctrl, end, t);
                        if is_on {
                            builder.line_to(p.x, p.y);
                        }
                    }
                    current_pos = end;
                }
                PathElement::Cubic(ctrl1, ctrl2, end) => {
                    let steps = 12;
                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = cubic_point(current_pos, ctrl1, ctrl2, end, t);
                        if is_on {
                            builder.line_to(p.x, p.y);
                        }
                    }
                    current_pos = end;
                }
            }
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Dash
    }
}

// =============================================================================
// Corner Effect
// =============================================================================

/// Corner path effect that rounds corners.
///
/// Corresponds to Skia's `SkCornerPathEffect`.
#[derive(Debug, Clone, Copy)]
pub struct CornerEffect {
    /// Radius for corner rounding.
    radius: Scalar,
}

impl CornerEffect {
    /// Create a new corner effect.
    pub fn new(radius: Scalar) -> Option<Self> {
        if radius <= 0.0 {
            return None;
        }
        Some(Self { radius })
    }

    /// Get the radius.
    pub fn radius(&self) -> Scalar {
        self.radius
    }
}

impl PathEffect for CornerEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        if path.is_empty() {
            return None;
        }

        let mut builder = PathBuilder::new();
        let elements: Vec<_> = path.iter().collect();

        let mut i = 0;
        while i < elements.len() {
            match elements[i] {
                PathElement::Move(p) => {
                    builder.move_to(p.x, p.y);
                    i += 1;
                }
                PathElement::Line(end) => {
                    // Look ahead for corner
                    let prev_end = if i > 0 {
                        get_end_point(&elements[i - 1])
                    } else {
                        None
                    };

                    let next_start = if i + 1 < elements.len() {
                        get_end_point(&elements[i + 1])
                    } else {
                        None
                    };

                    if let (Some(start), Some(next)) = (prev_end, next_start) {
                        // Round the corner at 'end'
                        let v1 = Point::new(start.x - end.x, start.y - end.y);
                        let v2 = Point::new(next.x - end.x, next.y - end.y);

                        let len1 = v1.length();
                        let len2 = v2.length();

                        if len1 > 0.0 && len2 > 0.0 {
                            let radius = self.radius.min(len1 / 2.0).min(len2 / 2.0);

                            let t1 = Point::new(
                                end.x + v1.x / len1 * radius,
                                end.y + v1.y / len1 * radius,
                            );
                            let t2 = Point::new(
                                end.x + v2.x / len2 * radius,
                                end.y + v2.y / len2 * radius,
                            );

                            builder.line_to(t1.x, t1.y);
                            builder.quad_to(end.x, end.y, t2.x, t2.y);
                        } else {
                            builder.line_to(end.x, end.y);
                        }
                    } else {
                        builder.line_to(end.x, end.y);
                    }
                    i += 1;
                }
                PathElement::Quad(ctrl, end) => {
                    builder.quad_to(ctrl.x, ctrl.y, end.x, end.y);
                    i += 1;
                }
                PathElement::Conic(ctrl, end, w) => {
                    builder.conic_to(ctrl.x, ctrl.y, end.x, end.y, w);
                    i += 1;
                }
                PathElement::Cubic(ctrl1, ctrl2, end) => {
                    builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, end.x, end.y);
                    i += 1;
                }
                PathElement::Close => {
                    builder.close();
                    i += 1;
                }
            }
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Corner
    }
}

// =============================================================================
// Discrete Effect
// =============================================================================

/// Discrete path effect that adds random displacement (jitter).
///
/// Corresponds to Skia's `SkDiscretePathEffect`.
#[derive(Debug, Clone, Copy)]
pub struct DiscreteEffect {
    /// Segment length for subdividing the path.
    seg_length: Scalar,
    /// Maximum deviation from the original path.
    deviation: Scalar,
    /// Random seed.
    seed: u32,
}

impl DiscreteEffect {
    /// Create a new discrete effect.
    pub fn new(seg_length: Scalar, deviation: Scalar, seed: u32) -> Option<Self> {
        if seg_length <= 0.0 {
            return None;
        }
        Some(Self {
            seg_length,
            deviation,
            seed,
        })
    }

    /// Get the segment length.
    pub fn seg_length(&self) -> Scalar {
        self.seg_length
    }

    /// Get the deviation.
    pub fn deviation(&self) -> Scalar {
        self.deviation
    }

    /// Simple pseudo-random number generator.
    fn random(&self, seed: u32) -> Scalar {
        // Simple LCG
        let n = seed.wrapping_mul(1103515245).wrapping_add(12345);
        ((n >> 16) & 0x7FFF) as Scalar / 32767.0 * 2.0 - 1.0
    }
}

impl PathEffect for DiscreteEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        if path.is_empty() {
            return None;
        }

        let mut builder = PathBuilder::new();
        let mut current_pos = Point::zero();
        let mut seed = self.seed;

        for element in path.iter() {
            match element {
                PathElement::Move(p) => {
                    let dx = self.random(seed) * self.deviation;
                    seed = seed.wrapping_add(1);
                    let dy = self.random(seed) * self.deviation;
                    seed = seed.wrapping_add(1);
                    builder.move_to(p.x + dx, p.y + dy);
                    current_pos = p;
                }
                PathElement::Line(end) => {
                    let length = current_pos.distance(&end);
                    let num_segments = (length / self.seg_length).ceil() as usize;
                    let num_segments = num_segments.max(1);

                    for i in 1..=num_segments {
                        let t = i as Scalar / num_segments as Scalar;
                        let x = current_pos.x + (end.x - current_pos.x) * t;
                        let y = current_pos.y + (end.y - current_pos.y) * t;

                        let dx = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);
                        let dy = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);

                        builder.line_to(x + dx, y + dy);
                    }
                    current_pos = end;
                }
                PathElement::Close => {
                    builder.close();
                }
                // For curves, subdivide into lines first
                PathElement::Quad(ctrl, end) => {
                    let steps = (quadratic_length(current_pos, ctrl, end) / self.seg_length).ceil()
                        as usize;
                    let steps = steps.max(4);

                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = quadratic_point(current_pos, ctrl, end, t);

                        let dx = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);
                        let dy = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);

                        builder.line_to(p.x + dx, p.y + dy);
                    }
                    current_pos = end;
                }
                PathElement::Conic(ctrl, end, _w) => {
                    let steps = (quadratic_length(current_pos, ctrl, end) / self.seg_length).ceil()
                        as usize;
                    let steps = steps.max(4);

                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = quadratic_point(current_pos, ctrl, end, t);

                        let dx = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);
                        let dy = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);

                        builder.line_to(p.x + dx, p.y + dy);
                    }
                    current_pos = end;
                }
                PathElement::Cubic(ctrl1, ctrl2, end) => {
                    let steps = (cubic_length(current_pos, ctrl1, ctrl2, end) / self.seg_length)
                        .ceil() as usize;
                    let steps = steps.max(4);

                    for i in 1..=steps {
                        let t = i as Scalar / steps as Scalar;
                        let p = cubic_point(current_pos, ctrl1, ctrl2, end, t);

                        let dx = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);
                        let dy = self.random(seed) * self.deviation;
                        seed = seed.wrapping_add(1);

                        builder.line_to(p.x + dx, p.y + dy);
                    }
                    current_pos = end;
                }
            }
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Discrete
    }
}

// =============================================================================
// Trim Effect
// =============================================================================

/// Trim effect that shows only a portion of the path.
///
/// Corresponds to Skia's `SkTrimPathEffect`.
#[derive(Debug, Clone, Copy)]
pub struct TrimEffect {
    /// Start of the visible portion (0.0 - 1.0).
    start: Scalar,
    /// End of the visible portion (0.0 - 1.0).
    end: Scalar,
    /// Trim mode.
    mode: TrimMode,
}

/// Trim mode for path effects.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TrimMode {
    /// Normal trim (from start to end).
    #[default]
    Normal,
    /// Inverted trim (everything except start to end).
    Inverted,
}

impl TrimEffect {
    /// Create a new trim effect.
    pub fn new(start: Scalar, end: Scalar, mode: TrimMode) -> Option<Self> {
        if start < 0.0 || start > 1.0 || end < 0.0 || end > 1.0 {
            return None;
        }
        Some(Self { start, end, mode })
    }

    /// Get the start position.
    pub fn start(&self) -> Scalar {
        self.start
    }

    /// Get the end position.
    pub fn end(&self) -> Scalar {
        self.end
    }

    /// Get the trim mode.
    pub fn mode(&self) -> TrimMode {
        self.mode
    }
}

impl PathEffect for TrimEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        let measure = crate::measure::PathMeasure::new(path);
        let total = measure.length();
        if total <= 0.0 {
            return Some(path.clone());
        }

        let start_dist = self.start * total;
        let end_dist = self.end * total;

        match self.mode {
            TrimMode::Normal => {
                if start_dist >= end_dist {
                    return Some(Path::new());
                }
                measure.get_segment(start_dist, end_dist)
            }
            TrimMode::Inverted => {
                if start_dist >= end_dist {
                    return Some(path.clone());
                }
                let mut builder = PathBuilder::new();
                if start_dist > 0.0 {
                    if let Some(before) = measure.get_segment(0.0, start_dist) {
                        for elem in before.iter() {
                            match elem {
                                PathElement::Move(p) => {
                                    builder.move_to(p.x, p.y);
                                }
                                PathElement::Line(p) => {
                                    builder.line_to(p.x, p.y);
                                }
                                PathElement::Quad(p1, p2) => {
                                    builder.quad_to(p1.x, p1.y, p2.x, p2.y);
                                }
                                PathElement::Cubic(p1, p2, p3) => {
                                    builder.cubic_to(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
                                }
                                PathElement::Conic(p1, p2, w) => {
                                    builder.conic_to(p1.x, p1.y, p2.x, p2.y, w);
                                }
                                PathElement::Close => {
                                    builder.close();
                                }
                            }
                        }
                    }
                }
                if end_dist < total {
                    if let Some(after) = measure.get_segment(end_dist, total) {
                        for elem in after.iter() {
                            match elem {
                                PathElement::Move(p) => {
                                    builder.move_to(p.x, p.y);
                                }
                                PathElement::Line(p) => {
                                    builder.line_to(p.x, p.y);
                                }
                                PathElement::Quad(p1, p2) => {
                                    builder.quad_to(p1.x, p1.y, p2.x, p2.y);
                                }
                                PathElement::Cubic(p1, p2, p3) => {
                                    builder.cubic_to(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
                                }
                                PathElement::Conic(p1, p2, w) => {
                                    builder.conic_to(p1.x, p1.y, p2.x, p2.y, w);
                                }
                                PathElement::Close => {
                                    builder.close();
                                }
                            }
                        }
                    }
                }
                Some(builder.build())
            }
        }
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Trim
    }
}

// =============================================================================
// Compose Effect
// =============================================================================

/// Compose effect that applies one effect, then another.
///
/// Corresponds to Skia's `SkPathEffect::MakeCompose`.
#[derive(Debug)]
pub struct ComposeEffect {
    outer: PathEffectRef,
    inner: PathEffectRef,
}

impl ComposeEffect {
    /// Create a composed effect: outer(inner(path)).
    pub fn new(outer: PathEffectRef, inner: PathEffectRef) -> Self {
        Self { outer, inner }
    }
}

impl PathEffect for ComposeEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        let intermediate = self.inner.apply(path)?;
        self.outer.apply(&intermediate)
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Compose
    }
}

// =============================================================================
// Sum Effect
// =============================================================================

/// Sum effect that applies both effects and combines the results.
///
/// Corresponds to Skia's `SkPathEffect::MakeSum`.
#[derive(Debug)]
pub struct SumEffect {
    first: PathEffectRef,
    second: PathEffectRef,
}

impl SumEffect {
    /// Create a sum effect.
    pub fn new(first: PathEffectRef, second: PathEffectRef) -> Self {
        Self { first, second }
    }
}

impl PathEffect for SumEffect {
    fn apply(&self, path: &Path) -> Option<Path> {
        let path1 = self.first.apply(path);
        let path2 = self.second.apply(path);

        match (path1, path2) {
            (Some(p1), Some(p2)) => {
                // Combine the paths
                let mut builder = PathBuilder::new();
                builder.add_path(&p1);
                builder.add_path(&p2);
                Some(builder.build())
            }
            (Some(p), None) | (None, Some(p)) => Some(p),
            (None, None) => None,
        }
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Sum
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

fn get_end_point(element: &PathElement) -> Option<Point> {
    match element {
        PathElement::Move(p) => Some(*p),
        PathElement::Line(p) => Some(*p),
        PathElement::Quad(_, p) => Some(*p),
        PathElement::Conic(_, p, _) => Some(*p),
        PathElement::Cubic(_, _, p) => Some(*p),
        PathElement::Close => None,
    }
}

fn quadratic_point(p0: Point, p1: Point, p2: Point, t: Scalar) -> Point {
    let mt = 1.0 - t;
    Point::new(
        mt * mt * p0.x + 2.0 * mt * t * p1.x + t * t * p2.x,
        mt * mt * p0.y + 2.0 * mt * t * p1.y + t * t * p2.y,
    )
}

fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: Scalar) -> Point {
    let mt = 1.0 - t;
    let mt2 = mt * mt;
    let t2 = t * t;
    Point::new(
        mt2 * mt * p0.x + 3.0 * mt2 * t * p1.x + 3.0 * mt * t2 * p2.x + t2 * t * p3.x,
        mt2 * mt * p0.y + 3.0 * mt2 * t * p1.y + 3.0 * mt * t2 * p2.y + t2 * t * p3.y,
    )
}

fn quadratic_length(p0: Point, p1: Point, p2: Point) -> Scalar {
    // Approximate with chord + control polygon
    let chord = p0.distance(&p2);
    let polygon = p0.distance(&p1) + p1.distance(&p2);
    (chord + polygon) / 2.0
}

fn cubic_length(p0: Point, p1: Point, p2: Point, p3: Point) -> Scalar {
    // Approximate with chord + control polygon
    let chord = p0.distance(&p3);
    let polygon = p0.distance(&p1) + p1.distance(&p2) + p2.distance(&p3);
    (chord + polygon) / 2.0
}

// =============================================================================
// Path1D Effect
// =============================================================================

/// Style for how the stamped path is placed along the input path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Path1DStyle {
    /// Translate the path shape.
    #[default]
    Translate,
    /// Rotate the path shape to follow the path direction.
    Rotate,
    /// Morph the path shape to follow the path curvature.
    Morph,
}

/// 1D path effect that stamps a path along another path.
///
/// Corresponds to Skia's `SkPath1DPathEffect`.
#[derive(Debug, Clone)]
pub struct Path1DEffect {
    /// The path to stamp.
    path: Path,
    /// Distance between stamps (advance).
    advance: Scalar,
    /// Initial phase offset.
    phase: Scalar,
    /// How to place the stamped path.
    style: Path1DStyle,
}

impl Path1DEffect {
    /// Create a new 1D path effect.
    ///
    /// - `path`: The path to stamp along the input path.
    /// - `advance`: Distance between each stamp.
    /// - `phase`: Initial offset along the path.
    /// - `style`: How to orient the stamped path.
    pub fn new(path: Path, advance: Scalar, phase: Scalar, style: Path1DStyle) -> Option<Self> {
        if advance <= 0.0 || path.is_empty() {
            return None;
        }
        Some(Self {
            path,
            advance,
            phase,
            style,
        })
    }

    /// Get the stamped path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Get the advance distance.
    pub fn advance(&self) -> Scalar {
        self.advance
    }

    /// Get the phase.
    pub fn phase(&self) -> Scalar {
        self.phase
    }

    /// Get the style.
    pub fn style(&self) -> Path1DStyle {
        self.style
    }
}

impl PathEffect for Path1DEffect {
    fn apply(&self, src_path: &Path) -> Option<Path> {
        use crate::PathMeasure;

        if src_path.is_empty() {
            return None;
        }

        let mut builder = PathBuilder::new();
        let measure = PathMeasure::new(src_path);
        let length = measure.length();

        if length <= 0.0 {
            return None;
        }

        let mut distance = self.phase;
        while distance < length {
            // Get position and tangent at this distance
            let pos = measure.get_point_at(distance);
            let tangent = measure.get_tangent_at(distance);

            if let (Some(pos), Some(tangent)) = (pos, tangent) {
                let transform = match self.style {
                    Path1DStyle::Translate => skia_rs_core::Matrix::translate(pos.x, pos.y),
                    Path1DStyle::Rotate | Path1DStyle::Morph => {
                        let angle = tangent.y.atan2(tangent.x);
                        // First rotate, then translate
                        let rotation = skia_rs_core::Matrix::rotate(angle);
                        let translation = skia_rs_core::Matrix::translate(pos.x, pos.y);
                        translation.concat(&rotation)
                    }
                };

                // Transform and add the stamped path
                let transformed = self.path.transformed(&transform);
                builder.add_path(&transformed);
            }
            distance += self.advance;
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Path1D
    }
}

// =============================================================================
// Path2D Effect
// =============================================================================

/// 2D path effect that tiles a path in a 2D pattern.
///
/// Corresponds to Skia's `SkPath2DPathEffect`.
#[derive(Debug, Clone)]
pub struct Path2DEffect {
    /// The transformation matrix for the tile.
    matrix: skia_rs_core::Matrix,
    /// The path to tile.
    path: Path,
}

impl Path2DEffect {
    /// Create a new 2D path effect.
    ///
    /// - `matrix`: The matrix defining the tiling pattern.
    /// - `path`: The path to tile.
    pub fn new(matrix: skia_rs_core::Matrix, path: Path) -> Option<Self> {
        if path.is_empty() {
            return None;
        }
        Some(Self { matrix, path })
    }

    /// Get the matrix.
    pub fn matrix(&self) -> &skia_rs_core::Matrix {
        &self.matrix
    }

    /// Get the tiled path.
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl PathEffect for Path2DEffect {
    fn apply(&self, src_path: &Path) -> Option<Path> {
        if src_path.is_empty() {
            return None;
        }

        let bounds = src_path.bounds();
        if bounds.is_empty() {
            return None;
        }
        let mut builder = PathBuilder::new();

        // Compute the inverse matrix to find tile positions
        let inverse = self.matrix.invert()?;

        // Transform bounds to tile space
        let transformed_bounds = inverse.map_rect(&bounds);

        // Compute tile range
        let start_x = transformed_bounds.left.floor() as i32 - 1;
        let end_x = transformed_bounds.right.ceil() as i32 + 1;
        let start_y = transformed_bounds.top.floor() as i32 - 1;
        let end_y = transformed_bounds.bottom.ceil() as i32 + 1;

        // Limit iterations for safety
        let max_tiles = 1000;
        let mut tile_count = 0;

        for y in start_y..=end_y {
            for x in start_x..=end_x {
                if tile_count >= max_tiles {
                    break;
                }

                // Transform tile to world space
                let tile_offset = skia_rs_core::Matrix::translate(x as Scalar, y as Scalar);
                let tile_matrix = self.matrix.concat(&tile_offset);
                let transformed_path = self.path.transformed(&tile_matrix);

                builder.add_path(&transformed_path);
                tile_count += 1;
            }
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Path2D
    }
}

// =============================================================================
// Line2D Effect
// =============================================================================

/// 2D line effect that fills a region with parallel lines.
///
/// Corresponds to Skia's `SkLine2DPathEffect`.
#[derive(Debug, Clone, Copy)]
pub struct Line2DEffect {
    /// Line width.
    width: Scalar,
    /// The transformation matrix for the line pattern.
    matrix: skia_rs_core::Matrix,
}

impl Line2DEffect {
    /// Create a new 2D line effect.
    ///
    /// - `width`: The width of the lines.
    /// - `matrix`: The matrix defining the line pattern orientation and spacing.
    pub fn new(width: Scalar, matrix: skia_rs_core::Matrix) -> Option<Self> {
        if width <= 0.0 {
            return None;
        }
        Some(Self { width, matrix })
    }

    /// Get the line width.
    pub fn width(&self) -> Scalar {
        self.width
    }

    /// Get the matrix.
    pub fn matrix(&self) -> &skia_rs_core::Matrix {
        &self.matrix
    }
}

impl PathEffect for Line2DEffect {
    fn apply(&self, src_path: &Path) -> Option<Path> {
        if src_path.is_empty() {
            return None;
        }

        let bounds = src_path.bounds();
        if bounds.is_empty() {
            return None;
        }
        let mut builder = PathBuilder::new();

        // Compute the inverse matrix
        let inverse = self.matrix.invert()?;

        // Transform bounds to line space
        let transformed_bounds = inverse.map_rect(&bounds);

        // Generate horizontal lines in transformed space
        let start_y = transformed_bounds.top.floor() as i32 - 1;
        let end_y = transformed_bounds.bottom.ceil() as i32 + 1;

        // Limit iterations for safety
        let max_lines = 500;
        let mut line_count = 0;

        for y in start_y..=end_y {
            if line_count >= max_lines {
                break;
            }

            // Create a line from left to right
            let y_pos = y as Scalar;
            let p0 = Point::new(transformed_bounds.left - 10.0, y_pos);
            let p1 = Point::new(transformed_bounds.right + 10.0, y_pos);

            // Transform back to world space
            let world_p0 = self.matrix.map_point(p0);
            let world_p1 = self.matrix.map_point(p1);

            // Create a rectangle for the line (with width)
            let half_width = self.width / 2.0;
            let dx = world_p1.x - world_p0.x;
            let dy = world_p1.y - world_p0.y;
            let len = (dx * dx + dy * dy).sqrt();

            if len > 0.0 {
                let nx = -dy / len * half_width;
                let ny = dx / len * half_width;

                builder.move_to(world_p0.x + nx, world_p0.y + ny);
                builder.line_to(world_p1.x + nx, world_p1.y + ny);
                builder.line_to(world_p1.x - nx, world_p1.y - ny);
                builder.line_to(world_p0.x - nx, world_p0.y - ny);
                builder.close();
            }

            line_count += 1;
        }

        Some(builder.build())
    }

    fn effect_kind(&self) -> PathEffectKind {
        PathEffectKind::Line2D
    }
}

// =============================================================================
// Convenience Functions
// =============================================================================

/// Create a dash path effect.
pub fn make_dash(intervals: Vec<Scalar>, phase: Scalar) -> Option<PathEffectRef> {
    DashEffect::new(intervals, phase).map(|e| Arc::new(e) as PathEffectRef)
}

/// Create a corner path effect.
pub fn make_corner(radius: Scalar) -> Option<PathEffectRef> {
    CornerEffect::new(radius).map(|e| Arc::new(e) as PathEffectRef)
}

/// Create a discrete path effect.
pub fn make_discrete(seg_length: Scalar, deviation: Scalar, seed: u32) -> Option<PathEffectRef> {
    DiscreteEffect::new(seg_length, deviation, seed).map(|e| Arc::new(e) as PathEffectRef)
}

/// Create a trim path effect.
pub fn make_trim(start: Scalar, end: Scalar, mode: TrimMode) -> Option<PathEffectRef> {
    TrimEffect::new(start, end, mode).map(|e| Arc::new(e) as PathEffectRef)
}

/// Compose two path effects.
pub fn make_compose(outer: PathEffectRef, inner: PathEffectRef) -> PathEffectRef {
    Arc::new(ComposeEffect::new(outer, inner))
}

/// Sum two path effects.
pub fn make_sum(first: PathEffectRef, second: PathEffectRef) -> PathEffectRef {
    Arc::new(SumEffect::new(first, second))
}

/// Create a 1D path effect.
pub fn make_path_1d(
    path: Path,
    advance: Scalar,
    phase: Scalar,
    style: Path1DStyle,
) -> Option<PathEffectRef> {
    Path1DEffect::new(path, advance, phase, style).map(|e| Arc::new(e) as PathEffectRef)
}

/// Create a 2D path effect.
pub fn make_path_2d(matrix: skia_rs_core::Matrix, path: Path) -> Option<PathEffectRef> {
    Path2DEffect::new(matrix, path).map(|e| Arc::new(e) as PathEffectRef)
}

/// Create a 2D line effect.
pub fn make_line_2d(width: Scalar, matrix: skia_rs_core::Matrix) -> Option<PathEffectRef> {
    Line2DEffect::new(width, matrix).map(|e| Arc::new(e) as PathEffectRef)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dash_effect() {
        let dash = DashEffect::new(vec![10.0, 5.0], 0.0).unwrap();
        assert_eq!(dash.intervals().len(), 2);
        assert_eq!(dash.phase(), 0.0);
    }

    #[test]
    fn test_dash_odd_intervals() {
        let dash = DashEffect::new(vec![10.0, 5.0, 3.0], 0.0).unwrap();
        // Should be doubled to make even
        assert_eq!(dash.intervals().len(), 6);
    }

    #[test]
    fn test_dash_effect_on_curve_produces_dashes_along_curve() {
        // A long quadratic curve with a 10-on/10-off dash.
        // Dash transitions should occur along the curve, not just at endpoints.
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.quad_to(50.0, 100.0, 100.0, 0.0);
        let path = builder.build();

        let effect = DashEffect::new(vec![10.0, 10.0], 0.0).unwrap();
        let result = effect.apply(&path).unwrap();

        // Each dash starts with a Move. On a curved path with length ~140,
        // we should get multiple dashes (not just one at start and one at end).
        let moves = result.iter().filter(|e| matches!(e, PathElement::Move(_))).count();
        assert!(
            moves >= 3,
            "Expected at least 3 dashes on curved path (curve length ~140, dash period 20), got {}",
            moves
        );
    }

    #[test]
    fn test_corner_effect() {
        let corner = CornerEffect::new(5.0).unwrap();
        assert_eq!(corner.radius(), 5.0);
    }

    #[test]
    fn test_discrete_effect() {
        let discrete = DiscreteEffect::new(10.0, 5.0, 42).unwrap();
        assert_eq!(discrete.seg_length(), 10.0);
        assert_eq!(discrete.deviation(), 5.0);
    }

    #[test]
    fn test_make_functions() {
        assert!(make_dash(vec![10.0, 5.0], 0.0).is_some());
        assert!(make_corner(5.0).is_some());
        assert!(make_discrete(10.0, 5.0, 0).is_some());
        assert!(make_trim(0.0, 1.0, TrimMode::Normal).is_some());
    }

    #[test]
    fn test_compose_effect() {
        let dash = make_dash(vec![10.0, 5.0], 0.0).unwrap();
        let corner = make_corner(5.0).unwrap();
        let composed = make_compose(dash, corner);
        assert_eq!(composed.effect_kind(), PathEffectKind::Compose);
    }

    #[test]
    fn test_trim_effect_normal_extracts_subsegment() {
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(100.0, 0.0);
        let path = builder.build();

        let effect = TrimEffect::new(0.25, 0.75, TrimMode::Normal).unwrap();
        let result = effect.apply(&path).unwrap();

        let bounds = result.bounds();
        assert!(
            (bounds.left - 25.0).abs() < 0.5,
            "Trimmed left should be ~25, got {}",
            bounds.left
        );
        assert!(
            (bounds.right - 75.0).abs() < 0.5,
            "Trimmed right should be ~75, got {}",
            bounds.right
        );
    }

    #[test]
    fn test_trim_effect_inverted_keeps_outside_range() {
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(100.0, 0.0);
        let path = builder.build();

        let effect = TrimEffect::new(0.25, 0.75, TrimMode::Inverted).unwrap();
        let result = effect.apply(&path).unwrap();

        let bounds = result.bounds();
        assert!((bounds.left - 0.0).abs() < 0.5);
        assert!((bounds.right - 100.0).abs() < 0.5);
        // Should have at least 2 contours (before 25 and after 75)
        assert_eq!(
            result.contour_count(),
            2,
            "Inverted trim should produce two contours"
        );
    }
}