ribir_painter 0.4.0-alpha.65

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
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
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
use std::ops::{Deref, DerefMut};

use ribir_algo::Resource;
use ribir_types::{Angle, DeviceRect, Point, Rect, Size, Transform, Vector};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;

pub use crate::FontFaceId as FaceId;
use crate::{
  Brush, Color, GlyphRasterSource, PixelImage, Svg, TextDrawPayload,
  color::{ColorFilterMatrix, LinearGradient, RadialGradient},
  filter::{Filter, FilterLayer, FilterOp},
  path::*,
  path_builder::PathBuilder,
};
/// The Painter provides you the ability to render 2D elements on a
/// two-dimensional canvas.
///
/// The coordinate (0, 0) is positioned at the upper-left corner of the canvas.
/// X-axis values progress toward the right edge of the canvas, while Y-axis
/// values increase towards the bottom edge of the canvas.
pub struct Painter {
  init_state: PainterState,
  state_stack: Vec<PainterState>,
  commands: Vec<PaintCommand>,
  path_builder: PathBuilder,
}

pub struct PainterResult<'a>(&'a mut Vec<PaintCommand>);

/// `PainterBackend` use to draw textures for every frame, All `draw_commands`
/// will called between `begin_frame` and `end_frame`
///
/// -- begin_frame()
///
///  +--> draw_commands --+
///  ^                    V
///  +----------<---------+
///                       
///
///
/// -+ end_frame()
///                       
pub trait PainterBackend {
  type Texture;

  /// Start a new frame, and clear the frame with `surface` color before draw.
  fn begin_frame(&mut self, surface: Color);

  /// Paint `commands` to the `output` Texture.  This may be called more than
  /// once during a frame.
  ///
  /// ## Undefined Behavior
  ///
  /// You should guarantee the output be same one in the same frame, otherwise
  /// it may cause undefined behavior.
  fn draw_commands(
    &mut self, viewport: DeviceRect, commands: &[PaintCommand], global_matrix: &Transform,
    output: &mut Self::Texture, glyph_provider: &dyn GlyphRasterSource,
  );
  /// A frame end.
  fn end_frame(&mut self);
}

/// A text drawing command carrying deferred glyph data.
///
/// The actual rasterization of glyphs is deferred to the rendering backend,
/// which can determine the optimal physical pixel size based on the display
/// scale factor and the current transform.
#[derive(Debug, Clone)]
pub struct TextCommand {
  /// The bounding box for visibility culling.
  pub paint_bounds: Rect,
  /// The transform at time of emission.
  pub transform: Transform,
  /// The shaped text payload to render.
  pub payload: Resource<TextDrawPayload>,
  /// The fallback brush used for runs that don't override their own brush.
  pub default_brush: CommandBrush,
  /// The active color filter applied to overridden run brushes.
  pub color_filter: ColorMatrix,
}

/// The enum of path types, which can be either shared or owned. This suggests
/// that if the path is shared among multiple commands, it can be cached for
/// efficiency.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaintPath {
  Share(Resource<Path>),
  Own(Path),
  PixelImage(Resource<PixelImage>),
}

/// The action to apply to the path, such as fill color, image, gradient, etc.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaintPathAction {
  Paint {
    brush: CommandBrush,
    /// The style to paint the path.
    painting_style: PaintingStyle,
  },

  Clip,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CommandBrush {
  Color(Color),
  Image { img: Resource<PixelImage>, color_filter: ColorMatrix },
  Radial(Resource<RadialGradient>),
  Linear(Resource<LinearGradient>),
}

#[repr(u32)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)]
pub enum SpreadMethod {
  #[default]
  Pad,
  Reflect,
  Repeat,
}

/// A path and its geometry information are friendly to paint and cache.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathCommand {
  /// The path to painting, and its axis is relative to the `bounds`.
  pub path: PaintPath,
  /// The bounds after path applied transform.
  pub paint_bounds: Rect,
  // The transform need to apply to the path.
  pub transform: Transform,
  // The action to apply to the path.
  pub action: PaintPathAction,
}

/// Explain the method for rendering shapes and paths, including filling or
/// stroking them.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub enum PaintingStyle {
  /// Fill the path.
  #[default]
  Fill,
  /// Stroke path with line width.
  Stroke(StrokeOptions),
}

/// Define the default method for the painter to render paths, including filling
/// or stroking them.
#[derive(Debug, Clone, Copy, Default)]
pub enum PathStyle {
  #[default]
  Fill,
  Stroke,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaintCommand {
  Path(PathCommand),
  PopClip,
  /// A Bundle of paint commands that can be assumed as a single command, that
  /// means the backend can cache it.
  Bundle {
    transform: Transform,
    color_filter: ColorMatrix,
    /// the bounds of the bundle commands. This is the union of all paint
    /// command
    bounds: Rect,
    cmds: Resource<Box<[PaintCommand]>>,
  },

  Filter {
    /// the path area to apply the filter.
    path: PaintPath,

    /// the transform to apply to the path.
    transform: Transform,

    /// the bounds of the path.
    filter_bounds: Rect,

    /// the filter primitive to apply.
    filters: Vec<FilterLayer>,
  },

  /// A deferred text drawing command. The backend resolves the physical pixel
  /// size and rasterizes glyphs via the injected `GlyphRasterSource`.
  ///
  /// This variant is skipped during serialization because text payloads contain
  /// shared resources and backend-specific runtime state.
  #[serde(skip)]
  Text(TextCommand),
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ColorMatrix {
  Opacity(f32),
  Matrix(ColorFilterMatrix),
}

impl From<ColorFilterMatrix> for ColorMatrix {
  fn from(m: ColorFilterMatrix) -> Self { ColorMatrix::Matrix(m) }
}

impl Default for ColorMatrix {
  fn default() -> Self { ColorMatrix::Opacity(1.) }
}

impl ColorMatrix {
  pub fn identity() -> Self { ColorMatrix::Opacity(1.) }

  pub fn from_opacity(a: f32) -> Self { ColorMatrix::Opacity(a) }

  pub fn from_matrix(m: ColorFilterMatrix) -> Self { ColorMatrix::Matrix(m) }

  fn apply_alpha(&mut self, alpha: f32) {
    match self {
      ColorMatrix::Opacity(a) => {
        *a *= alpha;
      }
      ColorMatrix::Matrix(matrix) => {
        matrix.apply_alpha(alpha);
      }
    };
  }

  fn apply_color_filter(&mut self, mut matrix: ColorFilterMatrix) {
    let v = match self {
      ColorMatrix::Opacity(a) => {
        matrix.apply_alpha(*a);
        ColorMatrix::Matrix(matrix)
      }
      ColorMatrix::Matrix(m) => ColorMatrix::Matrix(m.chains(&matrix)),
    };
    *self = v;
  }

  pub fn chains(&mut self, next: &ColorMatrix) {
    match next {
      ColorMatrix::Opacity(a) => self.apply_alpha(*a),
      ColorMatrix::Matrix(m) => self.apply_color_filter(*m),
    }
  }

  pub fn apply_to(&self, color: &Color) -> Color {
    match self {
      ColorMatrix::Opacity(a) => color.apply_alpha(*a),
      ColorMatrix::Matrix(m) => m.apply_to(color),
    }
  }

  fn is_transparent(&self) -> bool {
    match self {
      ColorMatrix::Opacity(a) => *a == 0.,
      ColorMatrix::Matrix(m) => m.is_transparent(),
    }
  }

  pub fn to_matrix(&self) -> ColorFilterMatrix {
    match self {
      ColorMatrix::Opacity(a) => ColorFilterMatrix::only_alpha(*a),
      ColorMatrix::Matrix(m) => *m,
    }
  }
}

#[derive(Clone)]
struct PainterState {
  /// The line width use to stroke path.
  stroke_options: StrokeOptions,
  stroke_brush: Brush,
  fill_brush: Brush,
  style: PathStyle,
  transform: Transform,
  color_filter: ColorMatrix,
  clip_cnt: usize,
  /// The visible boundary of the painter in visual axis, not care about the
  /// transform.
  bounds: Rect,

  filters: SmallVec<[FilterState; 0]>,
}

#[derive(Clone)]
struct FilterState {
  filter: Filter,
  filter_start_idx: usize,
  color_filter: ColorMatrix,
  transform: Transform,
}

impl PainterState {
  fn new(bounds: Rect) -> PainterState {
    PainterState {
      bounds,
      stroke_options: <_>::default(),
      stroke_brush: Color::BLACK.into(),
      fill_brush: Color::GRAY.into(),
      transform: Transform::identity(),
      clip_cnt: 0,
      color_filter: ColorMatrix::Opacity(1.),
      style: PathStyle::Fill,
      filters: SmallVec::new(),
    }
  }
}

impl Painter {
  pub fn new(viewport: Rect) -> Self {
    assert!(viewport.is_finite(), "viewport must be finite!");
    let init_state = PainterState::new(viewport);
    Self {
      state_stack: vec![init_state.clone()],
      init_state,
      commands: vec![],
      path_builder: Path::builder(),
    }
  }

  /// Creates an isolated state snapshot for atomic drawing operations.
  ///
  /// The forked painter maintains complete isolation from the original:
  /// - Captures cloned copy of the current rendering state
  /// - Maintains independent command buffer and path builder
  ///
  /// When merged back:
  /// - Inherits original state at fork time (immune to original's state
  ///   changes)
  /// - Transfers recorded commands without state contamination
  ///
  /// # Example
  /// ```
  /// use ribir_painter::*;
  /// use ribir_types::*;
  ///
  /// let mut painter = Painter::new(Rect::from_size(Size::splat(512.)));
  /// let mut overlay = painter.fork(); // Capture initial clear state
  ///
  /// // Overlay draws in original state context
  /// overlay
  ///   .rect(&Rect::from_size(Size::splat(200.)), true)
  ///   .fill();
  ///
  /// // Original painter changes state
  /// painter
  ///   .set_fill_brush(Color::RED)
  ///   .circle(Point::splat(100.), 50., true)
  ///   .fill();
  ///
  /// // Merge preserves overlay's commands with original fork-time state
  /// painter.merge(&mut overlay);
  /// ```
  pub fn fork(&self) -> Self {
    let init_state = self.current_state().clone();
    Painter {
      state_stack: vec![init_state.clone()],
      init_state,
      commands: vec![],
      path_builder: Path::builder(),
    }
  }

  /// Merges commands from a forked painter while preserving state isolation
  ///
  /// # Behavior
  /// - Transfers all drawing commands via buffer swapping (O(1) for Vec
  ///   storage)
  /// - Maintains original painter's current rendering state
  /// - Leaves forked painter with empty command buffer post-merge
  /// - Preserves both painters' path builders and state stacks
  pub fn merge(&mut self, forked: &mut Painter) { self.commands.append(forked.finish().0); }

  /// Change the default brush and text style of the painter, and then reset
  /// the painter state.
  pub fn set_init_state(&mut self, brush: Brush) {
    self.init_state.fill_brush = brush.clone();
    self.init_state.stroke_brush = brush;
    self.reset();
  }

  pub fn viewport(&self) -> &Rect { &self.init_state.bounds }

  /// Change the bounds of the painter can draw.But it won't take effect until
  /// the next time you call [`Painter::reset`]!.
  pub fn set_viewport(&mut self, bounds: Rect) { self.init_state.bounds = bounds; }

  pub fn intersection_paint_bounds(&self, rect: &Rect) -> Option<Rect> {
    self.paint_bounds().intersection(rect)
  }

  pub fn intersect_paint_bounds(&self, rect: &Rect) -> bool { self.paint_bounds().intersects(rect) }

  /// Returns the visible boundary of the painter in current state.
  pub fn paint_bounds(&self) -> Rect {
    let s = self.current_state();
    s.transform
      .inverse()
      .map_or_else(Rect::zero, |t| t.outer_transformed_rect(&s.bounds))
  }

  #[inline]
  // Finish the painter and return to the original state.
  pub fn finish(&mut self) -> PainterResult<'_> {
    self
      .state_stack
      .insert(0, self.init_state.clone());
    while self.state_stack.len() > 1 {
      self.restore();
    }
    PainterResult(&mut self.commands)
  }

  /// Saves the entire state and return a guard to auto restore the state when
  /// if drop.
  #[must_use]
  pub fn save_guard(&mut self) -> PainterGuard<'_> {
    self.save();
    PainterGuard(self)
  }

  /// Saves the entire state of the canvas by pushing the current drawing state
  /// onto a stack.
  pub fn save(&mut self) -> &mut Self {
    let mut new_state = self.current_state().clone();

    new_state.filters = SmallVec::new();

    self.state_stack.push(new_state);
    self
  }

  /// Restores the most recently saved canvas state by popping the top entry in
  /// the drawing state stack. If there is no saved state, this method does
  /// nothing.
  #[inline]
  pub fn restore(&mut self) {
    let state = self
      .state_stack
      .pop()
      .expect("Must have one state in stack!");

    let clip_cnt = state.clip_cnt;
    self.push_n_pop_cmd(clip_cnt - self.current_state().clip_cnt);

    // If the current state has filters set via [`Painter::filter`], the commands
    // drawn since the last save will be bundled and a filter command will be
    // generated to apply the filters to the bundled content.
    for filter in state.filters.into_iter().rev() {
      self.generate_filter_bundle(
        filter.transform,
        filter.filter_start_idx,
        filter.color_filter,
        filter.filter.into_layers(),
      );
    }
  }

  pub fn reset(&mut self) {
    self.fill_all_pop_clips();
    self.commands.clear();
    self.state_stack.clear();
    self.state_stack.push(self.init_state.clone());
  }

  /// Return the brush used to stroke paths.
  #[inline]
  pub fn stroke_brush(&self) -> &Brush { &self.current_state().stroke_brush }

  /// Set the brush used to stroke paths.
  #[inline]
  pub fn set_stroke_brush(&mut self, brush: impl Into<Brush>) -> &mut Self {
    self.current_state_mut().stroke_brush = brush.into();
    self
  }

  /// Return the brush used to fill shapes.
  #[inline]
  pub fn fill_brush(&self) -> &Brush { &self.current_state().fill_brush }

  /// Set the brush used to fill shapes.
  #[inline]
  pub fn set_fill_brush(&mut self, brush: impl Into<Brush>) -> &mut Self {
    self.current_state_mut().fill_brush = brush.into();
    self
  }

  /// return the style for drawing the path.
  pub fn style(&self) -> PathStyle { self.current_state().style }

  /// Define the default style for drawing the path.
  pub fn set_style(&mut self, style: PathStyle) -> &mut Self {
    self.current_state_mut().style = style;
    self
  }

  pub fn apply_alpha(&mut self, alpha: f32) -> &mut Self {
    self
      .current_state_mut()
      .color_filter
      .apply_alpha(alpha);
    self
  }

  pub fn is_transparent(&self) -> bool { self.current_state().color_filter.is_transparent() }

  pub fn current_color_filter(&self) -> &ColorMatrix { &self.current_state().color_filter }

  #[inline]
  pub fn set_strokes(&mut self, strokes: StrokeOptions) -> &mut Self {
    self.current_state_mut().stroke_options = strokes;
    self
  }

  /// Return the line width of the stroke pen.
  #[inline]
  pub fn line_width(&self) -> f32 { self.stroke_options().width }

  /// Set the line width of the stroke pen with `line_width`
  #[inline]
  pub fn set_line_width(&mut self, line_width: f32) -> &mut Self {
    self.current_state_mut().stroke_options.width = line_width;
    self
  }

  #[inline]
  pub fn line_join(&self) -> LineJoin { self.stroke_options().line_join }

  #[inline]
  pub fn set_line_join(&mut self, line_join: LineJoin) -> &mut Self {
    self.current_state_mut().stroke_options.line_join = line_join;
    self
  }

  #[inline]
  pub fn line_cap(&mut self) -> LineCap { self.stroke_options().line_cap }

  #[inline]
  pub fn set_line_cap(&mut self, line_cap: LineCap) -> &mut Self {
    self.current_state_mut().stroke_options.line_cap = line_cap;
    self
  }

  #[inline]
  pub fn miter_limit(&self) -> f32 { self.stroke_options().miter_limit }

  #[inline]
  pub fn set_miter_limit(&mut self, miter_limit: f32) -> &mut Self {
    self
      .current_state_mut()
      .stroke_options
      .miter_limit = miter_limit;
    self
  }

  /// Return the current transformation matrix being applied to the layer.
  #[inline]
  pub fn transform(&self) -> &Transform { &self.current_state().transform }

  #[inline]
  fn color_filter(&self) -> &ColorMatrix { &self.current_state().color_filter }

  /// Resets (overrides) the current transformation to the identity matrix, and
  /// then invokes a transformation described by the arguments of this method.
  /// This lets you scale, rotate, translate (move), and skew the context.
  #[inline]
  pub fn set_transform(&mut self, transform: Transform) -> &mut Self {
    self.current_state_mut().transform = transform;
    self
  }

  /// Apply this matrix to all subsequent paint commands。
  pub fn apply_transform(&mut self, transform: &Transform) -> &mut Self {
    let t = transform.then(self.transform());
    self.set_transform(t);
    self
  }

  pub fn clip(&mut self, path: PaintPath) -> &mut Self {
    invisible_return!(self);
    let p_bounds = path.bounds(None);
    if locatable_bounds(&p_bounds) {
      let intersect = self.intersection_paint_bounds(&p_bounds);
      let s = self.current_state_mut();
      if let Some(bounds) = intersect {
        s.bounds = s.transform.outer_transformed_rect(&bounds);
        let cmd = PathCommand::new(path, PaintPathAction::Clip, s.transform);
        self.commands.push(PaintCommand::Path(cmd));
        self.current_state_mut().clip_cnt += 1;
      } else {
        s.bounds = Rect::zero();
      }
    }

    self
  }

  /// Fill a path with fill brush.
  pub fn fill_path(&mut self, path: PaintPath) -> &mut Self {
    self.inner_draw_path(path, PathStyle::Fill)
  }

  /// Draw a path with the default style.
  pub fn draw_path(&mut self, path: PaintPath) -> &mut Self {
    self.inner_draw_path(path, self.current_state().style)
  }

  /// Outlines the current path with the current brush and `StrokeOptions`.
  pub fn stroke_path(&mut self, path: PaintPath) -> &mut Self {
    self.inner_draw_path(path, PathStyle::Stroke)
  }

  /// Strokes (outlines) the current path with the current brush and line width.
  pub fn stroke(&mut self) -> &mut Self {
    let builder = std::mem::take(&mut self.path_builder);
    self.stroke_path(builder.build().into())
  }

  /// Fill the current path with current brush.
  pub fn fill(&mut self) -> &mut Self {
    let builder = std::mem::take(&mut self.path_builder);
    self.fill_path(builder.build().into())
  }

  fn apply_color_matrix(&mut self, matrix: ColorFilterMatrix) -> &mut Self {
    self
      .current_state_mut()
      .color_filter
      .apply_color_filter(matrix);
    self
  }

  /// Draw the current path with the current paint style and brush.
  pub fn draw(&mut self) -> &mut Self {
    let builder = std::mem::take(&mut self.path_builder);
    self.draw_path(builder.build().into())
  }

  /// Adds a translation transformation to the current matrix by moving the
  /// canvas and its origin x units horizontally and y units vertically on the
  /// grid.
  ///
  /// * `x` - Distance to move in the horizontal direction. Positive values are
  ///   to the right, and negative to the left.
  /// * `y` - Distance to move in the vertical direction. Positive values are
  ///   down, and negative are up.
  pub fn translate(&mut self, x: f32, y: f32) -> &mut Self {
    let t = self.transform().pre_translate(Vector::new(x, y));
    self.set_transform(t);
    self
  }

  pub fn scale(&mut self, x: f32, y: f32) -> &mut Self {
    let t = self.transform().pre_scale(x, y);
    self.set_transform(t);
    self
  }

  /// Starts a new path by emptying the list of sub-paths.
  /// Call this method when you want to create a new path.
  #[inline]
  pub fn begin_path(&mut self, at: Point) -> &mut Self {
    self.path_builder.begin_path(at);
    self
  }

  /// Tell the painter the sub-path is finished.
  #[inline]
  pub fn end_path(&mut self, close: bool) -> &mut Self {
    self.path_builder.end_path(close);
    self
  }

  /// Connects the last point in the current sub-path to the specified (x, y)
  /// coordinates with a straight line.
  #[inline]
  pub fn line_to(&mut self, to: Point) -> &mut Self {
    self.path_builder.line_to(to);
    self
  }

  /// Adds a cubic Bezier curve to the current path.
  #[inline]
  pub fn bezier_curve_to(&mut self, ctrl1: Point, ctrl2: Point, to: Point) -> &mut Self {
    self
      .path_builder
      .bezier_curve_to(ctrl1, ctrl2, to);
    self
  }

  /// Adds a quadratic Bézier curve to the current path.
  #[inline]
  pub fn quadratic_curve_to(&mut self, ctrl: Point, to: Point) -> &mut Self {
    self.path_builder.quadratic_curve_to(ctrl, to);
    self
  }

  /// adds a circular arc to the current sub-path, using the given control
  /// points and radius. The arc is automatically connected to the path's latest
  /// point with a straight line, if necessary for the specified
  #[inline]
  pub fn arc_to(
    &mut self, center: Point, radius: f32, start_angle: Angle, end_angle: Angle,
  ) -> &mut Self {
    self
      .path_builder
      .arc_to(center, radius, start_angle, end_angle);
    self
  }

  /// The ellipse_to() method creates an elliptical arc centered at `center`
  /// with the `radius`. The path starts at startAngle and ends at endAngle, and
  /// travels in the direction given by anticlockwise (defaulting to
  /// clockwise).
  #[inline]
  pub fn ellipse_to(
    &mut self, center: Point, radius: Vector, start_angle: Angle, end_angle: Angle,
  ) -> &mut Self {
    self
      .path_builder
      .ellipse_to(center, radius, start_angle, end_angle);
    self
  }

  /// Adds a sub-path containing a rectangle.
  ///
  /// There must be no sub-path in progress when this method is called.
  /// No sub-path is in progress after the method is called.
  ///
  /// # Parameters
  /// * `rect` - The rectangle to add to the path
  /// * `is_positive` - If true, adds the rectangle with positive winding
  ///   (normal fill). If false, adds the rectangle with negative winding (can
  ///   be used to exclude area).
  #[inline]
  pub fn rect(&mut self, rect: &Rect, is_positive: bool) -> &mut Self {
    self.path_builder.rect(rect, is_positive);
    self
  }

  /// Adds a sub-path containing a circle.
  ///
  /// There must be no sub-path in progress when this method is called.
  /// No sub-path is in progress after the method is called.
  ///
  /// # Parameters
  /// * `center` - The center point of the circle
  /// * `radius` - The radius of the circle
  /// * `is_positive` - If true, adds the circle with positive winding (normal
  ///   fill). If false, adds the circle with negative winding (can be used to
  ///   exclude area).
  #[inline]
  pub fn circle(&mut self, center: Point, radius: f32, is_positive: bool) -> &mut Self {
    self
      .path_builder
      .circle(center, radius, is_positive);
    self
  }

  /// Adds a sub-path containing an ellipse.
  ///
  /// There must be no sub-path in progress when this method is called.
  /// No sub-path is in progress after the method is called.
  ///
  /// # Parameters
  /// * `center` - The center point of the ellipse
  /// * `radius` - The radius vector (x and y radii) of the ellipse
  /// * `rotation` - The rotation angle of the ellipse in radians
  /// * `is_positive` - If true, adds the ellipse with positive winding (normal
  ///   fill). If false, adds the ellipse with negative winding (can be used to
  ///   exclude area).
  #[inline]
  pub fn ellipse(
    &mut self, center: Point, radius: Vector, rotation: f32, is_positive: bool,
  ) -> &mut Self {
    self
      .path_builder
      .ellipse(center, radius, rotation, is_positive);
    self
  }

  /// Creates a path for a rectangle by `rect` with `radius`.
  ///
  /// # Parameters
  /// * `rect` - The rectangle to add to the path
  /// * `radius` - The corner radius for rounded rectangle
  /// * `is_positive` - If true, adds the rectangle with positive winding
  ///   (normal fill). If false, adds the rectangle with negative winding (can
  ///   be used to exclude area).
  #[inline]
  pub fn rect_round(&mut self, rect: &Rect, radius: &Radius, is_positive: bool) -> &mut Self {
    self
      .path_builder
      .rect_round(rect, radius, is_positive);
    self
  }

  /// Draws a bundle of paint commands that can be treated as a single command.
  /// This allows the backend to cache it.
  ///
  /// - **bounds** - The bounds of the bundle commands. This is the union of all
  ///   paint command bounds. It does not configure where the bundle is placed.
  ///   If you want to change the position of the bundle, you should call
  ///   `Painter::translate` before calling this method.
  /// - **cmds** - The list of paint commands to draw.
  pub fn draw_bundle_commands(
    &mut self, bounds: Rect, cmds: Resource<Box<[PaintCommand]>>,
  ) -> &mut Self {
    invisible_return!(self);
    if self.intersection_paint_bounds(&bounds).is_none() {
      return self;
    }

    let transform = *self.transform();
    let color_filter = *self.color_filter();
    let cmd = PaintCommand::Bundle { transform, color_filter, bounds, cmds };
    self.commands.push(cmd);
    self
  }

  pub fn draw_svg(&mut self, svg: &Svg) -> &mut Self {
    invisible_return!(self);
    let rect = Rect::from_size(svg.size());
    if self.intersection_paint_bounds(&rect).is_none() {
      return self;
    }

    let commands = svg.commands(self.fill_brush(), self.stroke_brush());

    // For a large number of path commands (more than 16), bundle them
    // together as a single resource. This allows the backend to cache
    // them collectively.
    // For a small number of path commands (less than 16), store them
    // individually as multiple resources. This means the backend doesn't
    // need to perform a single draw operation for an SVG.
    if commands.len() <= 16 {
      let transform = *self.transform();

      for cmd in commands.iter() {
        let cmd = match cmd.clone() {
          PaintCommand::Path(mut path) => {
            path.transform(&transform);
            if let PaintPathAction::Paint { ref mut brush, .. } = path.action {
              brush.apply_color_filter(self.color_filter());
            }
            PaintCommand::Path(path)
          }
          PaintCommand::PopClip => PaintCommand::PopClip,
          PaintCommand::Bundle { transform: b_ts, mut color_filter, bounds, cmds } => {
            color_filter.chains(self.color_filter());
            PaintCommand::Bundle { transform: transform.then(&b_ts), color_filter, bounds, cmds }
          }
          PaintCommand::Filter { .. } => cmd.clone(),
          PaintCommand::Text(mut text_cmd) => {
            text_cmd.transform = text_cmd.transform.then(&transform);
            text_cmd
              .default_brush
              .apply_color_filter(self.color_filter());
            text_cmd.color_filter.chains(self.color_filter());
            PaintCommand::Text(text_cmd)
          }
        };
        self.commands.push(cmd);
      }
    } else {
      self.draw_bundle_commands(rect, commands.clone());
    }

    self
  }

  /// Draw the image
  ///
  /// if src_rect is None then will draw the whole image fitted into dst_rect,
  /// otherwise will draw the partial src_rect of the image fitted into
  /// dst_rect.
  pub fn draw_img(
    &mut self, img: Resource<PixelImage>, dst_rect: &Rect, src_rect: &Option<Rect>,
  ) -> &mut Self {
    {
      let mut painter = self.save_guard();
      painter.translate(dst_rect.min_x(), dst_rect.min_y());

      let m_width = img.width() as f32;
      let m_height = img.height() as f32;
      let mut paint_rect = Rect::from_size(Size::new(m_width, m_height));
      if let Some(rc) = src_rect {
        assert!(paint_rect.contains_rect(rc));

        if paint_rect.width() != rc.width() || paint_rect.height() != rc.height() {
          painter.clip(Path::rect(&Rect::from_size(dst_rect.size)).into());
        }
        paint_rect = *rc;
      }
      painter
        .scale(dst_rect.width() / paint_rect.width(), dst_rect.height() / paint_rect.height())
        .translate(-paint_rect.min_x(), -paint_rect.min_y())
        .rect(&Rect::from_size(Size::new(m_width, m_height)), true)
        .set_fill_brush(img)
        .fill();
    }

    self
  }

  pub fn draw_text_payload(
    &mut self, payload: Resource<TextDrawPayload>, paint_bounds: Rect,
  ) -> &mut Self {
    invisible_return!(self);
    let mut default_brush = CommandBrush::from(self.fill_brush().clone());
    default_brush.apply_color_filter(self.current_color_filter());
    self
      .commands
      .push(PaintCommand::Text(TextCommand {
        paint_bounds,
        transform: *self.transform(),
        payload,
        default_brush,
        color_filter: *self.current_color_filter(),
      }));
    self
  }

  /// Apply filters to the background content within the specified path area.
  ///
  /// This is useful for effects like backdrop blur where you want to apply
  /// a filter to what's already been drawn behind a specific region.
  pub fn filter_path(&mut self, path: PaintPath, filter: Filter) -> &mut Self {
    invisible_return!(self);
    let p_bounds = path.bounds(None);
    if p_bounds.is_empty() || !locatable_bounds(&p_bounds) {
      return self;
    }

    if !self.intersect_paint_bounds(&p_bounds) {
      return self;
    }

    let transform = *self.transform();
    let mut filter_bounds = transform.outer_transformed_rect(&p_bounds);

    let filters: Vec<_> = filter
      .into_layers()
      .into_iter()
      .map(|mut layer| {
        filter_bounds = transform_filter_layer(&mut layer, &transform, filter_bounds);
        layer
      })
      .collect();

    self
      .commands
      .push(PaintCommand::Filter { path, filter_bounds, transform, filters });

    self
  }

  /// Set filters to apply to all commands drawn in the current state scope.
  ///
  /// When [`Painter::restore`] is called, all commands drawn since the last
  /// [`Painter::save`] will be bundled together and the filters will be
  /// applied to the bundled content.
  ///
  /// # Example
  /// ```ignore
  /// painter.save();
  /// painter.filter(Filter::blur(5.));
  /// painter.rect(&rect).fill();
  /// painter.circle(center, radius, true).fill();
  /// painter.restore(); // Generates Bundle + Filter commands
  /// ```
  pub fn filter(&mut self, filter: Filter) -> &mut Self {
    let (color_filter, filter) = filter.extract_color_and_convolution();

    if !filter.is_empty() {
      let state = FilterState {
        transform: *self.transform(),
        filter_start_idx: self.commands.len(),
        color_filter: *self.color_filter(),
        filter,
      };
      self.current_state_mut().filters.push(state);
    }

    if let Some(color_filter) = color_filter {
      self.apply_color_matrix(color_filter);
    }
    self
  }

  fn inner_draw_path(&mut self, path: PaintPath, path_style: PathStyle) -> &mut Self {
    invisible_return!(self);
    let line_width = matches!(path_style, PathStyle::Stroke).then(|| self.line_width());
    let p_bounds = path.bounds(line_width);
    if p_bounds.is_empty()
      || !locatable_bounds(&p_bounds)
      || !self.intersect_paint_bounds(&p_bounds)
    {
      return self;
    }

    let brush = match path_style {
      PathStyle::Fill => self.fill_brush().clone(),
      PathStyle::Stroke => self.stroke_brush().clone(),
    };

    if brush.is_visible() {
      let mut brush = CommandBrush::from(brush);
      let painting_style = match path_style {
        PathStyle::Fill => PaintingStyle::Fill,
        PathStyle::Stroke => PaintingStyle::Stroke(self.stroke_options().clone()),
      };
      brush.apply_color_filter(self.color_filter());
      let ts = *self.transform();
      let action = PaintPathAction::Paint { brush, painting_style };
      let cmd = PathCommand::new(path, action, ts);
      self.commands.push(PaintCommand::Path(cmd));
    }

    self
  }
}

impl PaintingStyle {
  pub fn line_width(&self) -> Option<f32> {
    match self {
      PaintingStyle::Fill => None,
      PaintingStyle::Stroke(stroke) => Some(stroke.width),
    }
  }
}

impl Painter {
  fn current_state(&self) -> &PainterState {
    self
      .state_stack
      .last()
      .expect("Must have one state in stack!")
  }

  fn current_state_mut(&mut self) -> &mut PainterState {
    self
      .state_stack
      .last_mut()
      .expect("Must have one state in stack!")
  }

  fn stroke_options(&self) -> &StrokeOptions { &self.current_state().stroke_options }

  fn push_n_pop_cmd(&mut self, n: usize) {
    for _ in 0..n {
      if matches!(
        self.commands.last(),
        Some(PaintCommand::Path(PathCommand { action: PaintPathAction::Clip, .. }))
      ) {
        self.commands.pop();
      } else {
        self.commands.push(PaintCommand::PopClip)
      }
    }
  }

  fn fill_all_pop_clips(&mut self) {
    let clip_cnt = self.current_state().clip_cnt;
    self
      .state_stack
      .iter_mut()
      .for_each(|s| s.clip_cnt = 0);
    self.push_n_pop_cmd(clip_cnt);
  }

  fn is_visible_canvas(&self) -> bool {
    let t = self.current_state().transform;
    !self.is_transparent()
      && locatable_bounds(self.viewport())
      && t.m11.is_finite()
      && t.m12.is_finite()
      && t.m21.is_finite()
      && t.m22.is_finite()
      && t.m31.is_finite()
      && t.m32.is_finite()
  }

  /// Generate a Bundle command from the commands drawn since cmd_start_idx,
  /// then generate a Filter command to apply filters to the bundled content.
  fn generate_filter_bundle(
    &mut self, transform: Transform, cmd_start_idx: usize, color_filter: ColorMatrix,
    filters: Vec<FilterLayer>,
  ) {
    if cmd_start_idx >= self.commands.len() {
      return;
    }

    // Collect commands drawn in this filter scope
    let mut cmds: Vec<PaintCommand> = self.commands.drain(cmd_start_idx..).collect();
    if cmds.is_empty() {
      return;
    }

    // Calculate the bounds of all commands
    let mut current_bounds = match Self::compute_commands_bounds(&cmds) {
      Some(b) if locatable_bounds(&b) => b,
      _ => return,
    };

    let len = filters.len();
    for (i, mut layer) in filters.into_iter().enumerate() {
      let new_bounds = transform_filter_layer(&mut layer, &transform, current_bounds);

      let path = Path::rect(&new_bounds).into();
      cmds.push(PaintCommand::Filter {
        path,
        transform: Transform::identity(),
        filter_bounds: new_bounds,
        filters: vec![layer],
      });

      // Generate Bundle command
      let color_filter = if i == len - 1 { color_filter } else { ColorMatrix::default() };
      let bundle = PaintCommand::Bundle {
        transform: Transform::identity(),
        color_filter,
        bounds: new_bounds,
        cmds: Resource::new(cmds.into_boxed_slice()),
      };
      cmds = vec![bundle];
      current_bounds = new_bounds;
    }

    self.commands.extend(cmds);
  }

  /// Compute the union bounds of a list of paint commands.
  fn compute_commands_bounds(cmds: &[PaintCommand]) -> Option<Rect> {
    let mut bounds: Option<Rect> = None;
    for cmd in cmds {
      let cmd_bounds = match cmd {
        PaintCommand::Path(path_cmd) => path_cmd.paint_bounds,
        PaintCommand::Bundle { bounds: b, transform, .. } => transform.outer_transformed_rect(b),
        PaintCommand::Filter { filter_bounds, .. } => *filter_bounds,
        PaintCommand::Text(text_cmd) => text_cmd
          .transform
          .outer_transformed_rect(&text_cmd.paint_bounds),
        PaintCommand::PopClip => continue,
      };
      bounds = Some(bounds.map_or(cmd_bounds, |b| b.union(&cmd_bounds)));
    }
    bounds
  }
}

impl From<Brush> for CommandBrush {
  fn from(brush: Brush) -> Self {
    match brush {
      Brush::Color(color) => CommandBrush::Color(color),
      Brush::Image(img) => CommandBrush::Image { img, color_filter: ColorMatrix::default() },
      Brush::RadialGradient(radial_gradient) => CommandBrush::Radial(radial_gradient),
      Brush::LinearGradient(linear_gradient) => CommandBrush::Linear(linear_gradient),
    }
  }
}

impl Drop for PainterResult<'_> {
  fn drop(&mut self) { self.0.clear() }
}

impl<'a> Deref for PainterResult<'a> {
  type Target = [PaintCommand];
  fn deref(&self) -> &Self::Target { self.0 }
}

impl<'a> DerefMut for PainterResult<'a> {
  fn deref_mut(&mut self) -> &mut Self::Target { self.0 }
}

/// An RAII implementation of a "scoped state" of the render layer.
///
/// When this structure is dropped (falls out of scope), changed state will auto
/// restore. The data can be accessed through this guard via its Deref and
/// DerefMut implementations.
pub struct PainterGuard<'a>(&'a mut Painter);

impl<'a> Drop for PainterGuard<'a> {
  #[inline]
  fn drop(&mut self) {
    debug_assert!(!self.0.state_stack.is_empty());
    self.0.restore();
  }
}

impl<'a> Deref for PainterGuard<'a> {
  type Target = Painter;
  #[inline]
  fn deref(&self) -> &Self::Target { self.0 }
}

impl<'a> DerefMut for PainterGuard<'a> {
  #[inline]
  fn deref_mut(&mut self) -> &mut Self::Target { self.0 }
}

impl Deref for PaintPath {
  type Target = Path;
  fn deref(&self) -> &Self::Target {
    match self {
      PaintPath::Share(p) => p.deref(),
      PaintPath::Own(p) => p,
      PaintPath::PixelImage(_) => {
        panic!("PaintPath::PixelImage cannot be dereferenced to Path");
      }
    }
  }
}

impl PaintPath {
  pub fn path_kind(&self) -> PathKind {
    match self {
      PaintPath::Share(p) => p.path_kind(),
      PaintPath::Own(p) => p.path_kind(),
      PaintPath::PixelImage(_) => PathKind::Complex,
    }
  }

  pub fn bounds(&self, line_width: Option<f32>) -> Rect {
    match self {
      PaintPath::Share(p) => p.bounds(line_width),
      PaintPath::Own(p) => p.bounds(line_width),
      PaintPath::PixelImage(img) => {
        let size = img.size();
        Rect::from_size(Size::new(size.width as f32, size.height as f32))
      }
    }
  }
}

impl From<Path> for PaintPath {
  fn from(p: Path) -> Self { PaintPath::Own(p) }
}

impl From<Resource<Path>> for PaintPath {
  fn from(p: Resource<Path>) -> Self { PaintPath::Share(p) }
}

impl PathCommand {
  pub fn new(path: PaintPath, action: PaintPathAction, transform: Transform) -> Self {
    let line_width = if let PaintPathAction::Paint { painting_style, .. } = &action {
      painting_style.line_width()
    } else {
      None
    };
    let paint_bounds = transform.outer_transformed_rect(&path.bounds(line_width));
    Self { path, transform, paint_bounds, action }
  }

  pub fn scale(&mut self, scale: f32) {
    self.transform = self.transform.then_scale(scale, scale);
    self.paint_bounds = self.paint_bounds.scale(scale, scale);
  }

  pub fn transform(&mut self, transform: &Transform) {
    self.transform = self.transform.then(transform);
    self.paint_bounds = self
      .transform
      .outer_transformed_rect(&self.path.bounds(None));
  }
}

impl CommandBrush {
  pub fn apply_color_filter(&mut self, filter: &ColorMatrix) -> &mut Self {
    match self {
      CommandBrush::Color(color) => *color = filter.apply_to(color),
      CommandBrush::Image { color_filter, .. } => color_filter.chains(filter),
      CommandBrush::Radial(gradient) => {
        let mut gradient = (**gradient).clone();
        gradient
          .stops
          .iter_mut()
          .for_each(|s| s.color = filter.apply_to(&s.color));
        *self = CommandBrush::Radial(Resource::new(gradient));
      }
      CommandBrush::Linear(gradient) => {
        let mut gradient = (**gradient).clone();
        gradient
          .stops
          .iter_mut()
          .for_each(|s| s.color = filter.apply_to(&s.color));
        *self = CommandBrush::Linear(Resource::new(gradient));
      }
    }
    self
  }
}

impl From<usvg::SpreadMethod> for SpreadMethod {
  fn from(value: usvg::SpreadMethod) -> Self {
    match value {
      usvg::SpreadMethod::Pad => SpreadMethod::Pad,
      usvg::SpreadMethod::Reflect => SpreadMethod::Reflect,
      usvg::SpreadMethod::Repeat => SpreadMethod::Repeat,
    }
  }
}

// bounds that has a limited location and size
fn locatable_bounds(bounds: &Rect) -> bool {
  bounds.origin.is_finite() && !bounds.width().is_nan() && !bounds.height().is_nan()
}

/// Transforms a filter layer's offset from user coordinates to device
/// coordinates and computes the expanded bounds accounting for convolution
/// kernel size.
///
/// Returns the new filter bounds after expansion and offset shift.
fn transform_filter_layer(
  layer: &mut FilterLayer, transform: &Transform, current_bounds: Rect,
) -> Rect {
  use crate::filter::FlattenMatrix;

  let (w, h) = layer
    .ops
    .iter()
    .fold((1, 1), |(w, h), op| match op {
      FilterOp::Convolution(FlattenMatrix { width, height, .. }) => (w + width - 1, h + height - 1),
      _ => (w, h),
    });

  let expand = Size::new(w as f32 - 1., h as f32 - 1.);
  let expand = transform
    .outer_transformed_rect(&Rect::from_size(expand))
    .size;

  let expanded_bounds =
    Rect::new(current_bounds.origin - expand / 2., current_bounds.size + expand);

  // Transform the offset from user coordinates to device coordinates.
  // We use transform_vector (not transform_point) because offset is a
  // direction vector that should not be affected by translation.
  let offset = transform.transform_vector(Vector::new(layer.offset[0], layer.offset[1]));
  layer.offset = [offset.x, offset.y];

  let shift_bounds = expanded_bounds.translate(offset);
  expanded_bounds.union(&shift_bounds)
}

macro_rules! invisible_return {
  ($this:ident) => {
    if !$this.is_visible_canvas() {
      return $this;
    }
  };
}
use invisible_return;

#[cfg(test)]
mod test {
  use ribir_types::rect;

  use super::*;

  fn painter() -> Painter { Painter::new(Rect::from_size(Size::new(512., 512.))) }

  #[test]
  fn save_guard() {
    let mut painter = painter();
    {
      let mut guard = painter.save_guard();
      let t = Transform::new(1., 1., 1., 1., 1., 1.);
      guard.set_transform(t);
      assert_eq!(&t, guard.transform());
      {
        let mut p2 = guard.save_guard();
        let t2 = Transform::new(2., 2., 2., 2., 2., 2.);
        p2.set_transform(t2);
        assert_eq!(&t2, p2.transform());
      }
      assert_eq!(&t, guard.transform());
    }
    assert_eq!(&Transform::new(1., 0., 0., 1., 0., 0.), painter.transform());
  }

  #[test]
  fn fix_clip_pop_without_restore() {
    let mut painter = painter();
    let commands = painter
      .save()
      .clip(Path::rect(&rect(0., 0., 100., 100.)).into())
      .rect(&rect(0., 0., 10., 10.), true)
      .fill()
      .save()
      .clip(Path::rect(&rect(0., 0., 50., 50.)).into())
      .rect(&rect(0., 0., 10., 10.), true)
      .fill()
      .finish();

    assert!(matches!(commands[commands.len() - 1], PaintCommand::PopClip));
    assert!(matches!(commands[commands.len() - 2], PaintCommand::PopClip));

    std::mem::drop(commands);

    assert_eq!(painter.current_state().clip_cnt, 0);
  }

  #[test]
  fn filter_invalid_clip() {
    let mut painter = painter();

    painter
      .save()
      .set_transform(Transform::translation(f32::NAN, f32::INFINITY))
      .clip(Path::rect(&rect(0., 0., 10., 10.)).into());
    assert_eq!(painter.commands.len(), 0);
  }

  #[test]
  fn filter_invalid_commands() {
    let mut painter = painter();

    let svg =
      Svg::parse_from_bytes(include_bytes!("../../tests/assets/test1.svg"), true, false).unwrap();
    painter
      .save()
      .set_transform(Transform::translation(f32::NAN, f32::INFINITY))
      .draw_svg(&svg);
    assert_eq!(painter.commands.len(), 0);
  }

  #[test]
  fn draw_svg_gradient() {
    let mut painter = Painter::new(Rect::from_size(Size::new(64., 64.)));
    let svg = Svg::parse_from_bytes(
      include_bytes!("../../tests/assets/fill_with_gradient.svg"),
      true,
      false,
    )
    .unwrap();

    painter.draw_svg(&svg);
  }

  #[test]
  fn fix_incorrect_bounds_axis() {
    let mut painter = painter();

    painter
      .save()
      .clip(Path::rect(&rect(0., 0., 100., 100.)).into())
      .set_transform(Transform::translation(500., 500.))
      .rect(&rect(-500., -500., 10., 10.), true)
      .fill();
    assert_eq!(painter.commands.len(), 2);
  }

  #[test]
  fn fix_scale_zero_crash() {
    let mut painter = painter();

    painter
      .scale(0., 0.)
      .rect(&rect(0., 0., 10., 10.), true)
      .fill();
  }

  #[test]
  fn clip_zero() {
    let mut painter = painter();

    painter
      .clip(Path::rect(&rect(0., 0., 0., 0.)).into())
      .rect(&rect(0., 0., 10., 10.), true)
      .fill();

    assert_eq!(painter.commands.len(), 0);

    painter.draw_bundle_commands(
      Rect::from_size(Size::new(10., 10.)),
      Resource::new(Box::new([PaintCommand::Path(PathCommand::new(
        Path::rect(&rect(0., 0., 10., 10.)).into(),
        PaintPathAction::Paint {
          painting_style: PaintingStyle::Fill,
          brush: Brush::Color(Color::BLACK).into(),
        },
        Transform::identity(),
      ))])),
    );
    assert_eq!(painter.commands.len(), 0);
  }
}