Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gpencil_data.c « gpencil « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a7e7246ee82d69c70ae26f6e48a365f4e5384202 (plain)
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
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2008, Blender Foundation
 * This is a new part of Blender
 */

/** \file
 * \ingroup edgpencil
 *
 * Operators for dealing with GP data-blocks and layers.
 */

#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "MEM_guardedalloc.h"

#include "BLI_blenlib.h"
#include "BLI_ghash.h"
#include "BLI_math.h"
#include "BLI_string_utils.h"
#include "BLI_utildefines.h"

#include "BLT_translation.h"

#include "DNA_anim_types.h"
#include "DNA_brush_types.h"
#include "DNA_gpencil_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "DNA_view3d_types.h"

#include "BKE_anim_data.h"
#include "BKE_animsys.h"
#include "BKE_brush.h"
#include "BKE_context.h"
#include "BKE_deform.h"
#include "BKE_fcurve_driver.h"
#include "BKE_gpencil.h"
#include "BKE_gpencil_modifier.h"
#include "BKE_lib_id.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_paint.h"
#include "BKE_report.h"
#include "BKE_scene.h"

#include "UI_interface.h"
#include "UI_resources.h"

#include "WM_api.h"
#include "WM_types.h"

#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_enum_types.h"

#include "ED_gpencil.h"
#include "ED_object.h"

#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
#include "DEG_depsgraph_query.h"

#include "gpencil_intern.h"

/* ************************************************ */
/* Datablock Operators */

/* ******************* Add New Data ************************ */
static bool gp_data_add_poll(bContext *C)
{

  /* the base line we have is that we have somewhere to add Grease Pencil data */
  return ED_annotation_data_get_pointers(C, NULL) != NULL;
}

/* add new datablock - wrapper around API */
static int gp_data_add_exec(bContext *C, wmOperator *op)
{
  PointerRNA gpd_owner = {NULL};
  bGPdata **gpd_ptr = ED_annotation_data_get_pointers(C, &gpd_owner);

  if (gpd_ptr == NULL) {
    BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
    return OPERATOR_CANCELLED;
  }

  /* decrement user count and add new datablock */
  /* TODO: if a datablock exists,
   * we should make a copy of it instead of starting fresh (as in other areas) */
  Main *bmain = CTX_data_main(C);

  /* decrement user count of old GP datablock */
  if (*gpd_ptr) {
    bGPdata *gpd = (*gpd_ptr);
    id_us_min(&gpd->id);
  }

  /* Add new datablock, with a single layer ready to use
   * (so users don't have to perform an extra step). */
  bGPdata *gpd = BKE_gpencil_data_addnew(bmain, DATA_("Annotations"));
  *gpd_ptr = gpd;

  /* tag for annotations */
  gpd->flag |= GP_DATA_ANNOTATIONS;

  /* add new layer (i.e. a "note") */
  BKE_gpencil_layer_addnew(*gpd_ptr, DATA_("Note"), true);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_annotation_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Annotation Add New";
  ot->idname = "GPENCIL_OT_annotation_add";
  ot->description = "Add new Annotation data-block";
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_data_add_exec;
  ot->poll = gp_data_add_poll;
}

/* ******************* Unlink Data ************************ */

/* poll callback for adding data/layers - special */
static bool gp_data_unlink_poll(bContext *C)
{
  bGPdata **gpd_ptr = ED_annotation_data_get_pointers(C, NULL);

  /* only unlink annotation datablocks */
  if ((gpd_ptr != NULL) && (*gpd_ptr != NULL)) {
    bGPdata *gpd = (*gpd_ptr);
    if ((gpd->flag & GP_DATA_ANNOTATIONS) == 0) {
      return false;
    }
  }
  /* if we have access to some active data, make sure there's a datablock before enabling this */
  return (gpd_ptr && *gpd_ptr);
}

/* unlink datablock - wrapper around API */
static int gp_data_unlink_exec(bContext *C, wmOperator *op)
{
  bGPdata **gpd_ptr = ED_annotation_data_get_pointers(C, NULL);

  if (gpd_ptr == NULL) {
    BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
    return OPERATOR_CANCELLED;
  }
  else {
    /* just unlink datablock now, decreasing its user count */
    bGPdata *gpd = (*gpd_ptr);

    id_us_min(&gpd->id);
    *gpd_ptr = NULL;
  }

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_data_unlink(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Annotation Unlink";
  ot->idname = "GPENCIL_OT_data_unlink";
  ot->description = "Unlink active Annotation data-block";
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_data_unlink_exec;
  ot->poll = gp_data_unlink_poll;
}

/* ************************************************ */
/* Layer Operators */

/* ******************* Add New Layer ************************ */

/* add new layer - wrapper around API */
static int gp_layer_add_exec(bContext *C, wmOperator *op)
{
  const bool is_annotation = STREQ(op->idname, "GPENCIL_OT_layer_annotation_add");

  PointerRNA gpd_owner = {NULL};
  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);
  bGPdata *gpd = NULL;

  if (is_annotation) {
    bGPdata **gpd_ptr = ED_annotation_data_get_pointers(C, &gpd_owner);
    /* if there's no existing Grease-Pencil data there, add some */
    if (gpd_ptr == NULL) {
      BKE_report(op->reports, RPT_ERROR, "Nowhere for grease pencil data to go");
      return OPERATOR_CANCELLED;
    }
    /* Annotations */
    if (*gpd_ptr == NULL) {
      *gpd_ptr = BKE_gpencil_data_addnew(bmain, DATA_("Annotations"));
    }

    /* mark as annotation */
    (*gpd_ptr)->flag |= GP_DATA_ANNOTATIONS;
    BKE_gpencil_layer_addnew(*gpd_ptr, DATA_("Note"), true);
    gpd = *gpd_ptr;
  }
  else {
    /* GP Object */
    Object *ob = CTX_data_active_object(C);
    if ((ob != NULL) && (ob->type == OB_GPENCIL)) {
      gpd = (bGPdata *)ob->data;
      bGPDlayer *gpl = BKE_gpencil_layer_addnew(gpd, DATA_("GP_Layer"), true);
      /* Add a new frame to make it visible in Dopesheet. */
      if (gpl != NULL) {
        gpl->actframe = BKE_gpencil_layer_frame_get(gpl, CFRA, GP_GETFRAME_ADD_NEW);
      }
    }
  }

  /* notifiers */
  if (gpd) {
    DEG_id_tag_update(&gpd->id,
                      ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
  }
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add New Layer";
  ot->idname = "GPENCIL_OT_layer_add";
  ot->description = "Add new layer or note for the active data-block";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_add_exec;
  ot->poll = gp_add_poll;
}

static bool gp_add_annotation_poll(bContext *C)
{
  return ED_annotation_data_get_pointers(C, NULL) != NULL;
}

void GPENCIL_OT_layer_annotation_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add New Annotation Layer";
  ot->idname = "GPENCIL_OT_layer_annotation_add";
  ot->description = "Add new Annotation layer or note for the active data-block";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_add_exec;
  ot->poll = gp_add_annotation_poll;
}
/* ******************* Remove Active Layer ************************* */

static int gp_layer_remove_exec(bContext *C, wmOperator *op)
{
  const bool is_annotation = STREQ(op->idname, "GPENCIL_OT_layer_annotation_remove");

  bGPdata *gpd = (!is_annotation) ? ED_gpencil_data_get_active(C) :
                                    ED_annotation_data_get_active(C);
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);

  /* sanity checks */
  if (ELEM(NULL, gpd, gpl)) {
    return OPERATOR_CANCELLED;
  }

  if (gpl->flag & GP_LAYER_LOCKED) {
    BKE_report(op->reports, RPT_ERROR, "Cannot delete locked layers");
    return OPERATOR_CANCELLED;
  }

  /* make the layer before this the new active layer
   * - use the one after if this is the first
   * - if this is the only layer, this naturally becomes NULL
   */
  if (gpl->prev) {
    BKE_gpencil_layer_active_set(gpd, gpl->prev);
  }
  else {
    BKE_gpencil_layer_active_set(gpd, gpl->next);
  }

  /* delete the layer now... */
  BKE_gpencil_layer_delete(gpd, gpl);

  /* Reorder masking. */
  BKE_gpencil_layer_mask_sort_all(gpd);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_remove(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove Layer";
  ot->idname = "GPENCIL_OT_layer_remove";
  ot->description = "Remove active Grease Pencil layer";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_remove_exec;
  ot->poll = gp_active_layer_poll;
}

static bool gp_active_layer_annotation_poll(bContext *C)
{
  bGPdata *gpd = ED_annotation_data_get_active(C);
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);

  return (gpl != NULL);
}

void GPENCIL_OT_layer_annotation_remove(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove Annotation Layer";
  ot->idname = "GPENCIL_OT_layer_annotation_remove";
  ot->description = "Remove active Annotation layer";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_remove_exec;
  ot->poll = gp_active_layer_annotation_poll;
}
/* ******************* Move Layer Up/Down ************************** */

enum {
  GP_LAYER_MOVE_UP = -1,
  GP_LAYER_MOVE_DOWN = 1,
};

static int gp_layer_move_exec(bContext *C, wmOperator *op)
{
  const bool is_annotation = STREQ(op->idname, "GPENCIL_OT_layer_annotation_move");

  bGPdata *gpd = (!is_annotation) ? ED_gpencil_data_get_active(C) :
                                    ED_annotation_data_get_active(C);
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);

  const int direction = RNA_enum_get(op->ptr, "type") * -1;

  /* sanity checks */
  if (ELEM(NULL, gpd, gpl)) {
    return OPERATOR_CANCELLED;
  }

  BLI_assert(ELEM(direction, -1, 0, 1)); /* we use value below */
  if (BLI_listbase_link_move(&gpd->layers, gpl, direction)) {
    /* Reorder masking. */
    BKE_gpencil_layer_mask_sort_all(gpd);

    DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
    WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  }

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_move(wmOperatorType *ot)
{
  static const EnumPropertyItem slot_move[] = {
      {GP_LAYER_MOVE_UP, "UP", 0, "Up", ""},
      {GP_LAYER_MOVE_DOWN, "DOWN", 0, "Down", ""},
      {0, NULL, 0, NULL, NULL},
  };

  /* identifiers */
  ot->name = "Move Grease Pencil Layer";
  ot->idname = "GPENCIL_OT_layer_move";
  ot->description = "Move the active Grease Pencil layer up/down in the list";

  /* api callbacks */
  ot->exec = gp_layer_move_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  ot->prop = RNA_def_enum(ot->srna, "type", slot_move, 0, "Type", "");
}

void GPENCIL_OT_layer_annotation_move(wmOperatorType *ot)
{
  static const EnumPropertyItem slot_move[] = {
      {GP_LAYER_MOVE_UP, "UP", 0, "Up", ""},
      {GP_LAYER_MOVE_DOWN, "DOWN", 0, "Down", ""},
      {0, NULL, 0, NULL, NULL},
  };

  /* identifiers */
  ot->name = "Move Annotation Layer";
  ot->idname = "GPENCIL_OT_layer_annotation_move";
  ot->description = "Move the active Annotation layer up/down in the list";

  /* api callbacks */
  ot->exec = gp_layer_move_exec;
  ot->poll = gp_active_layer_annotation_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  ot->prop = RNA_def_enum(ot->srna, "type", slot_move, 0, "Type", "");
}
/* ********************* Duplicate Layer ************************** */

static int gp_layer_copy_exec(bContext *C, wmOperator *UNUSED(op))
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);
  bGPDlayer *new_layer;

  /* sanity checks */
  if (ELEM(NULL, gpd, gpl)) {
    return OPERATOR_CANCELLED;
  }

  /* make copy of layer, and add it immediately after the existing layer */
  new_layer = BKE_gpencil_layer_duplicate(gpl);
  BLI_insertlinkafter(&gpd->layers, gpl, new_layer);

  /* ensure new layer has a unique name, and is now the active layer */
  BLI_uniquename(&gpd->layers,
                 new_layer,
                 DATA_("GP_Layer"),
                 '.',
                 offsetof(bGPDlayer, info),
                 sizeof(new_layer->info));
  BKE_gpencil_layer_active_set(gpd, new_layer);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_duplicate(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Duplicate Layer";
  ot->idname = "GPENCIL_OT_layer_duplicate";
  ot->description = "Make a copy of the active Grease Pencil layer";

  /* callbacks */
  ot->exec = gp_layer_copy_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ********************* Duplicate Layer in a new object ************************** */
enum {
  GP_LAYER_COPY_OBJECT_ALL_FRAME = 0,
  GP_LAYER_COPY_OBJECT_ACT_FRAME = 1,
};

static bool gp_layer_duplicate_object_poll(bContext *C)
{
  ViewLayer *view_layer = CTX_data_view_layer(C);
  Object *ob = CTX_data_active_object(C);
  if ((ob == NULL) || (ob->type != OB_GPENCIL)) {
    return false;
  }

  bGPdata *gpd = (bGPdata *)ob->data;
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);

  if (gpl == NULL) {
    return false;
  }

  /* check there are more grease pencil objects */
  LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
    if ((base->object != ob) && (base->object->type == OB_GPENCIL)) {
      return true;
    }
  }

  return false;
}

static int gp_layer_duplicate_object_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);
  char name[MAX_ID_NAME - 2];
  RNA_string_get(op->ptr, "object", name);

  if (name[0] == '\0') {
    return OPERATOR_CANCELLED;
  }

  Object *ob_dst = (Object *)BKE_scene_object_find_by_name(scene, name);

  int mode = RNA_enum_get(op->ptr, "mode");

  Object *ob_src = CTX_data_active_object(C);
  bGPdata *gpd_src = (bGPdata *)ob_src->data;
  bGPDlayer *gpl_src = BKE_gpencil_layer_active_get(gpd_src);

  /* Sanity checks. */
  if (ELEM(NULL, gpd_src, gpl_src, ob_dst)) {
    return OPERATOR_CANCELLED;
  }
  /* Cannot copy itself and check destination type. */
  if ((ob_src == ob_dst) || (ob_dst->type != OB_GPENCIL)) {
    return OPERATOR_CANCELLED;
  }

  bGPdata *gpd_dst = (bGPdata *)ob_dst->data;

  /* Create new layer. */
  bGPDlayer *gpl_dst = BKE_gpencil_layer_addnew(gpd_dst, gpl_src->info, true);
  /* Need to copy some variables (not all). */
  gpl_dst->onion_flag = gpl_src->onion_flag;
  gpl_dst->thickness = gpl_src->thickness;
  gpl_dst->line_change = gpl_src->line_change;
  copy_v4_v4(gpl_dst->tintcolor, gpl_src->tintcolor);
  gpl_dst->opacity = gpl_src->opacity;

  /* Create all frames. */
  LISTBASE_FOREACH (bGPDframe *, gpf_src, &gpl_src->frames) {

    if ((mode == GP_LAYER_COPY_OBJECT_ACT_FRAME) && (gpf_src != gpl_src->actframe)) {
      continue;
    }

    /* Create new frame. */
    bGPDframe *gpf_dst = BKE_gpencil_frame_addnew(gpl_dst, gpf_src->framenum);

    /* Copy strokes. */
    LISTBASE_FOREACH (bGPDstroke *, gps_src, &gpf_src->strokes) {

      /* Make copy of source stroke. */
      bGPDstroke *gps_dst = BKE_gpencil_stroke_duplicate(gps_src, true);

      /* Check if material is in destination object,
       * otherwise add the slot with the material. */
      Material *ma_src = BKE_object_material_get(ob_src, gps_src->mat_nr + 1);
      if (ma_src != NULL) {
        int idx = BKE_gpencil_object_material_ensure(bmain, ob_dst, ma_src);

        /* Reassign the stroke material to the right slot in destination object. */
        gps_dst->mat_nr = idx;
      }

      /* Add new stroke to frame. */
      BLI_addtail(&gpf_dst->strokes, gps_dst);
    }
  }

  /* notifiers */
  DEG_id_tag_update(&gpd_dst->id,
                    ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
  DEG_id_tag_update(&ob_dst->id, ID_RECALC_COPY_ON_WRITE);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_duplicate_object(wmOperatorType *ot)
{
  static const EnumPropertyItem copy_mode[] = {
      {GP_LAYER_COPY_OBJECT_ALL_FRAME, "ALL", 0, "All Frames", ""},
      {GP_LAYER_COPY_OBJECT_ACT_FRAME, "ACTIVE", 0, "Active Frame", ""},
      {0, NULL, 0, NULL, NULL},
  };

  /* identifiers */
  ot->name = "Duplicate Layer to New Object";
  ot->idname = "GPENCIL_OT_layer_duplicate_object";
  ot->description = "Make a copy of the active Grease Pencil layer to new object";

  /* callbacks */
  ot->exec = gp_layer_duplicate_object_exec;
  ot->poll = gp_layer_duplicate_object_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  ot->prop = RNA_def_string(
      ot->srna, "object", NULL, MAX_ID_NAME - 2, "Object", "Name of the destination object");
  RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE);

  RNA_def_enum(ot->srna, "mode", copy_mode, GP_LAYER_COPY_OBJECT_ALL_FRAME, "Mode", "");
}

/* ********************* Duplicate Frame ************************** */
enum {
  GP_FRAME_DUP_ACTIVE = 0,
  GP_FRAME_DUP_ALL = 1,
};

static int gp_frame_duplicate_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *gpl_active = BKE_gpencil_layer_active_get(gpd);
  Scene *scene = CTX_data_scene(C);

  int mode = RNA_enum_get(op->ptr, "mode");

  /* sanity checks */
  if (ELEM(NULL, gpd, gpl_active)) {
    return OPERATOR_CANCELLED;
  }

  if (mode == 0) {
    BKE_gpencil_frame_addcopy(gpl_active, CFRA);
  }
  else {
    LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
      if ((gpl->flag & GP_LAYER_LOCKED) == 0) {
        BKE_gpencil_frame_addcopy(gpl, CFRA);
      }
    }
  }
  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_frame_duplicate(wmOperatorType *ot)
{
  static const EnumPropertyItem duplicate_mode[] = {
      {GP_FRAME_DUP_ACTIVE, "ACTIVE", 0, "Active", "Duplicate frame in active layer only"},
      {GP_FRAME_DUP_ALL, "ALL", 0, "All", "Duplicate active frames in all layers"},
      {0, NULL, 0, NULL, NULL},
  };

  /* identifiers */
  ot->name = "Duplicate Frame";
  ot->idname = "GPENCIL_OT_frame_duplicate";
  ot->description = "Make a copy of the active Grease Pencil Frame";

  /* callbacks */
  ot->exec = gp_frame_duplicate_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  ot->prop = RNA_def_enum(ot->srna, "mode", duplicate_mode, GP_FRAME_DUP_ACTIVE, "Mode", "");
}

/* ********************* Clean Fill Boundaries on Frame ************************** */
enum {
  GP_FRAME_CLEAN_FILL_ACTIVE = 0,
  GP_FRAME_CLEAN_FILL_ALL = 1,
};

static int gp_frame_clean_fill_exec(bContext *C, wmOperator *op)
{
  bool changed = false;
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  int mode = RNA_enum_get(op->ptr, "mode");

  CTX_DATA_BEGIN (C, bGPDlayer *, gpl, editable_gpencil_layers) {
    bGPDframe *init_gpf = gpl->actframe;
    if (mode == GP_FRAME_CLEAN_FILL_ALL) {
      init_gpf = gpl->frames.first;
    }

    for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
      if ((gpf == gpl->actframe) || (mode == GP_FRAME_CLEAN_FILL_ALL)) {

        if (gpf == NULL) {
          continue;
        }

        /* simply delete strokes which are no fill */
        LISTBASE_FOREACH_MUTABLE (bGPDstroke *, gps, &gpf->strokes) {
          /* skip strokes that are invalid for current view */
          if (ED_gpencil_stroke_can_use(C, gps) == false) {
            continue;
          }

          /* free stroke */
          if (gps->flag & GP_STROKE_NOFILL) {
            /* free stroke memory arrays, then stroke itself */
            if (gps->points) {
              MEM_freeN(gps->points);
            }
            if (gps->dvert) {
              BKE_gpencil_free_stroke_weights(gps);
              MEM_freeN(gps->dvert);
            }
            MEM_SAFE_FREE(gps->triangles);
            BLI_freelinkN(&gpf->strokes, gps);

            changed = true;
          }
        }
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  if (changed) {
    DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
    WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  }

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_frame_clean_fill(wmOperatorType *ot)
{
  static const EnumPropertyItem duplicate_mode[] = {
      {GP_FRAME_CLEAN_FILL_ACTIVE, "ACTIVE", 0, "Active Frame Only", "Clean active frame only"},
      {GP_FRAME_CLEAN_FILL_ALL, "ALL", 0, "All Frames", "Clean all frames in all layers"},
      {0, NULL, 0, NULL, NULL},
  };

  /* identifiers */
  ot->name = "Clean Fill Boundaries";
  ot->idname = "GPENCIL_OT_frame_clean_fill";
  ot->description = "Remove 'no fill' boundary strokes";

  /* callbacks */
  ot->exec = gp_frame_clean_fill_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  ot->prop = RNA_def_enum(ot->srna, "mode", duplicate_mode, GP_FRAME_DUP_ACTIVE, "Mode", "");
}

/* ********************* Clean Loose Boundaries on Frame ************************** */
static int gp_frame_clean_loose_exec(bContext *C, wmOperator *op)
{
  bool changed = false;
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  int limit = RNA_int_get(op->ptr, "limit");
  const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);

  CTX_DATA_BEGIN (C, bGPDlayer *, gpl, editable_gpencil_layers) {
    bGPDframe *init_gpf = (is_multiedit) ? gpl->frames.first : gpl->actframe;

    for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
      if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
        if (gpf == NULL) {
          continue;
        }

        /* simply delete strokes which are no loose */
        LISTBASE_FOREACH_MUTABLE (bGPDstroke *, gps, &gpf->strokes) {
          /* skip strokes that are invalid for current view */
          if (ED_gpencil_stroke_can_use(C, gps) == false) {
            continue;
          }

          /* free stroke */
          if (gps->totpoints <= limit) {
            /* free stroke memory arrays, then stroke itself */
            if (gps->points) {
              MEM_freeN(gps->points);
            }
            if (gps->dvert) {
              BKE_gpencil_free_stroke_weights(gps);
              MEM_freeN(gps->dvert);
            }
            MEM_SAFE_FREE(gps->triangles);
            BLI_freelinkN(&gpf->strokes, gps);

            changed = true;
          }
        }
      }

      /* if not multiedit, exit loop*/
      if (!is_multiedit) {
        break;
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  if (changed) {
    DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
    WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  }

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_frame_clean_loose(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Clean Loose Points";
  ot->idname = "GPENCIL_OT_frame_clean_loose";
  ot->description = "Remove loose points";

  /* callbacks */
  ot->exec = gp_frame_clean_loose_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_int(ot->srna,
              "limit",
              1,
              1,
              INT_MAX,
              "Limit",
              "Number of points to consider stroke as loose",
              1,
              INT_MAX);
}

/* *********************** Hide Layers ******************************** */

static int gp_hide_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *layer = BKE_gpencil_layer_active_get(gpd);
  bool unselected = RNA_boolean_get(op->ptr, "unselected");

  /* sanity checks */
  if (ELEM(NULL, gpd, layer)) {
    return OPERATOR_CANCELLED;
  }

  if (unselected) {
    /* hide unselected */
    LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
      if (gpl != layer) {
        gpl->flag |= GP_LAYER_HIDE;
      }
      else {
        /* Be sure the active layer is unhidden. */
        gpl->flag &= ~GP_LAYER_HIDE;
      }
    }
  }
  else {
    /* hide selected/active */
    layer->flag |= GP_LAYER_HIDE;
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_hide(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Hide Layer(s)";
  ot->idname = "GPENCIL_OT_hide";
  ot->description = "Hide selected/unselected Grease Pencil layers";

  /* callbacks */
  ot->exec = gp_hide_exec;
  ot->poll = gp_active_layer_poll; /* NOTE: we need an active layer to play with */

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* props */
  RNA_def_boolean(
      ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected layers");
}

/* ********************** Show All Layers ***************************** */

/* poll callback for showing layers */
static bool gp_reveal_poll(bContext *C)
{
  return ED_gpencil_data_get_active(C) != NULL;
}

static void gp_reveal_select_frame(bContext *C, bGPDframe *frame, bool select)
{
  bGPDstroke *gps;
  for (gps = frame->strokes.first; gps; gps = gps->next) {

    /* only deselect strokes that are valid in this view */
    if (ED_gpencil_stroke_can_use(C, gps)) {

      /* (de)select points */
      int i;
      bGPDspoint *pt;
      for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
        SET_FLAG_FROM_TEST(pt->flag, select, GP_SPOINT_SELECT);
      }

      /* (de)select stroke */
      SET_FLAG_FROM_TEST(gps->flag, select, GP_STROKE_SELECT);
    }
  }
}

static int gp_reveal_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  const bool select = RNA_boolean_get(op->ptr, "select");

  /* sanity checks */
  if (gpd == NULL) {
    return OPERATOR_CANCELLED;
  }

  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    if (gpl->flag & GP_LAYER_HIDE) {
      gpl->flag &= ~GP_LAYER_HIDE;

      /* select or deselect if requested, only on hidden layers */
      if (gpd->flag & GP_DATA_STROKE_EDITMODE) {
        if (select) {
          /* select all strokes on active frame only (same as select all operator) */
          if (gpl->actframe) {
            gp_reveal_select_frame(C, gpl->actframe, true);
          }
        }
        else {
          /* deselect strokes on all frames (same as deselect all operator) */
          bGPDframe *gpf;
          for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
            gp_reveal_select_frame(C, gpf, false);
          }
        }
      }
    }
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_reveal(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Show All Layers";
  ot->idname = "GPENCIL_OT_reveal";
  ot->description = "Show all Grease Pencil layers";

  /* callbacks */
  ot->exec = gp_reveal_exec;
  ot->poll = gp_reveal_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* props */
  RNA_def_boolean(ot->srna, "select", true, "Select", "");
}

/* ***************** Lock/Unlock All Layers ************************ */

static int gp_lock_all_exec(bContext *C, wmOperator *UNUSED(op))
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);

  /* sanity checks */
  if (gpd == NULL) {
    return OPERATOR_CANCELLED;
  }

  /* make all layers non-editable */
  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    gpl->flag |= GP_LAYER_LOCKED;
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_lock_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Lock All Layers";
  ot->idname = "GPENCIL_OT_lock_all";
  ot->description =
      "Lock all Grease Pencil layers to prevent them from being accidentally modified";

  /* callbacks */
  ot->exec = gp_lock_all_exec;
  ot->poll = gp_reveal_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* -------------------------- */

static int gp_unlock_all_exec(bContext *C, wmOperator *UNUSED(op))
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);

  /* sanity checks */
  if (gpd == NULL) {
    return OPERATOR_CANCELLED;
  }

  /* make all layers editable again */
  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    gpl->flag &= ~GP_LAYER_LOCKED;
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_unlock_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Unlock All Layers";
  ot->idname = "GPENCIL_OT_unlock_all";
  ot->description = "Unlock all Grease Pencil layers so that they can be edited";

  /* callbacks */
  ot->exec = gp_unlock_all_exec;
  ot->poll = gp_reveal_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ********************** Isolate Layer **************************** */

static int gp_isolate_layer_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *layer = BKE_gpencil_layer_active_get(gpd);
  int flags = GP_LAYER_LOCKED;
  bool isolate = false;

  if (RNA_boolean_get(op->ptr, "affect_visibility")) {
    flags |= GP_LAYER_HIDE;
  }

  if (ELEM(NULL, gpd, layer)) {
    BKE_report(op->reports, RPT_ERROR, "No active layer to isolate");
    return OPERATOR_CANCELLED;
  }

  /* Test whether to isolate or clear all flags */
  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    /* Skip if this is the active layer */
    if (gpl == layer) {
      continue;
    }

    /* If the flags aren't set, that means that the layer is
     * not alone, so we have some layers to isolate still
     */
    if ((gpl->flag & flags) == 0) {
      isolate = true;
      break;
    }
  }

  /* Set/Clear flags as appropriate */
  /* TODO: Include onion-skinning on this list? */
  if (isolate) {
    /* Set flags on all "other" layers */
    LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
      if (gpl == layer) {
        continue;
      }
      else {
        gpl->flag |= flags;
      }
    }
  }
  else {
    /* Clear flags - Restore everything else */
    LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
      gpl->flag &= ~flags;
    }
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_isolate(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Isolate Layer";
  ot->idname = "GPENCIL_OT_layer_isolate";
  ot->description =
      "Toggle whether the active layer is the only one that can be edited and/or visible";

  /* callbacks */
  ot->exec = gp_isolate_layer_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* properties */
  RNA_def_boolean(ot->srna,
                  "affect_visibility",
                  false,
                  "Affect Visibility",
                  "In addition to toggling the editability, also affect the visibility");
}

/* ********************** Merge Layer with the next layer **************************** */

static int gp_merge_layer_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *gpl_next = BKE_gpencil_layer_active_get(gpd);
  bGPDlayer *gpl_current = gpl_next->prev;

  if (ELEM(NULL, gpd, gpl_current, gpl_next)) {
    BKE_report(op->reports, RPT_ERROR, "No layers to merge");
    return OPERATOR_CANCELLED;
  }

  /* Collect frames of gpl_current in hash table to avoid O(n^2) lookups */
  GHash *gh_frames_cur = BLI_ghash_int_new_ex(__func__, 64);
  LISTBASE_FOREACH (bGPDframe *, gpf, &gpl_current->frames) {
    BLI_ghash_insert(gh_frames_cur, POINTER_FROM_INT(gpf->framenum), gpf);
  }

  /* read all frames from next layer and add any missing in current layer */
  LISTBASE_FOREACH (bGPDframe *, gpf, &gpl_next->frames) {
    /* try to find frame in current layer */
    bGPDframe *frame = BLI_ghash_lookup(gh_frames_cur, POINTER_FROM_INT(gpf->framenum));
    if (!frame) {
      bGPDframe *actframe = BKE_gpencil_layer_frame_get(
          gpl_current, gpf->framenum, GP_GETFRAME_USE_PREV);
      frame = BKE_gpencil_frame_addnew(gpl_current, gpf->framenum);
      /* duplicate strokes of current active frame */
      if (actframe) {
        BKE_gpencil_frame_copy_strokes(actframe, frame);
      }
    }
    /* add to tail all strokes */
    BLI_movelisttolist(&frame->strokes, &gpf->strokes);
  }

  /* Add Masks to destination layer. */
  LISTBASE_FOREACH (bGPDlayer_Mask *, mask, &gpl_next->mask_layers) {
    /* Don't add merged layers or missing layer names. */
    if (!BKE_gpencil_layer_named_get(gpd, mask->name) || STREQ(mask->name, gpl_next->info) ||
        STREQ(mask->name, gpl_current->info)) {
      continue;
    }
    if (!BKE_gpencil_layer_mask_named_get(gpl_current, mask->name)) {
      bGPDlayer_Mask *mask_new = MEM_dupallocN(mask);
      BLI_addtail(&gpl_current->mask_layers, mask_new);
      gpl_current->act_mask++;
    }
  }
  /* Set destination layer as active. */
  BKE_gpencil_layer_active_set(gpd, gpl_current);

  /* Now delete next layer */
  BKE_gpencil_layer_delete(gpd, gpl_next);
  BLI_ghash_free(gh_frames_cur, NULL, NULL);

  /* Reorder masking. */
  BKE_gpencil_layer_mask_sort(gpd, gpl_current);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_merge(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Merge Down";
  ot->idname = "GPENCIL_OT_layer_merge";
  ot->description = "Merge the current layer with the layer below";

  /* callbacks */
  ot->exec = gp_merge_layer_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ********************** Change Layer ***************************** */

static int gp_layer_change_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(evt))
{
  uiPopupMenu *pup;
  uiLayout *layout;

  /* call the menu, which will call this operator again, hence the canceled */
  pup = UI_popup_menu_begin(C, op->type->name, ICON_NONE);
  layout = UI_popup_menu_layout(pup);
  uiItemsEnumO(layout, "GPENCIL_OT_layer_change", "layer");
  UI_popup_menu_end(C, pup);

  return OPERATOR_INTERFACE;
}

static int gp_layer_change_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = CTX_data_gpencil_data(C);
  bGPDlayer *gpl = NULL;
  int layer_num = RNA_enum_get(op->ptr, "layer");

  /* Get layer or create new one */
  if (layer_num == -1) {
    /* Create layer */
    gpl = BKE_gpencil_layer_addnew(gpd, DATA_("GP_Layer"), true);
  }
  else {
    /* Try to get layer */
    gpl = BLI_findlink(&gpd->layers, layer_num);

    if (gpl == NULL) {
      BKE_reportf(
          op->reports, RPT_ERROR, "Cannot change to non-existent layer (index = %d)", layer_num);
      return OPERATOR_CANCELLED;
    }
  }

  /* Set active layer */
  BKE_gpencil_layer_active_set(gpd, gpl);

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_change(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Change Layer";
  ot->idname = "GPENCIL_OT_layer_change";
  ot->description = "Change active Grease Pencil layer";

  /* callbacks */
  ot->invoke = gp_layer_change_invoke;
  ot->exec = gp_layer_change_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* gp layer to use (dynamic enum) */
  ot->prop = RNA_def_enum(ot->srna, "layer", DummyRNA_DEFAULT_items, 0, "Grease Pencil Layer", "");
  RNA_def_enum_funcs(ot->prop, ED_gpencil_layers_with_new_enum_itemf);
}

static int gp_layer_active_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = (bGPdata *)ob->data;
  int layer_num = RNA_int_get(op->ptr, "layer");

  /* Try to get layer */
  bGPDlayer *gpl = BLI_findlink(&gpd->layers, layer_num);

  if (gpl == NULL) {
    BKE_reportf(
        op->reports, RPT_ERROR, "Cannot change to non-existent layer (index = %d)", layer_num);
    return OPERATOR_CANCELLED;
  }

  /* Set active layer */
  BKE_gpencil_layer_active_set(gpd, gpl);

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_active(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Active Layer";
  ot->idname = "GPENCIL_OT_layer_active";
  ot->description = "Active Grease Pencil layer";

  /* callbacks */
  ot->exec = gp_layer_active_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* GPencil layer to use. */
  ot->prop = RNA_def_int(ot->srna, "layer", 0, 0, INT_MAX, "Grease Pencil Layer", "", 0, INT_MAX);
  RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
/* ************************************************ */

/* ******************* Arrange Stroke Up/Down in drawing order ************************** */

enum {
  GP_STROKE_MOVE_UP = -1,
  GP_STROKE_MOVE_DOWN = 1,
  GP_STROKE_MOVE_TOP = 2,
  GP_STROKE_MOVE_BOTTOM = 3,
};

static int gp_stroke_arrange_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bGPDlayer *gpl_act = BKE_gpencil_layer_active_get(gpd);

  /* sanity checks */
  if (ELEM(NULL, gpd, gpl_act, gpl_act->actframe)) {
    return OPERATOR_CANCELLED;
  }

  const int direction = RNA_enum_get(op->ptr, "direction");
  const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);

  CTX_DATA_BEGIN (C, bGPDlayer *, gpl, editable_gpencil_layers) {
    /* temp listbase to store selected strokes */
    ListBase selected = {NULL};

    bGPDframe *init_gpf = (is_multiedit) ? gpl->frames.first : gpl->actframe;
    bGPDstroke *gps = NULL;

    for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
      if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
        if (gpf == NULL) {
          continue;
        }
        bool gpf_lock = false;
        /* verify if any selected stroke is in the extreme of the stack and select to move */
        for (gps = gpf->strokes.first; gps; gps = gps->next) {
          /* only if selected */
          if (gps->flag & GP_STROKE_SELECT) {
            /* skip strokes that are invalid for current view */
            if (ED_gpencil_stroke_can_use(C, gps) == false) {
              continue;
            }
            /* check if the color is editable */
            if (ED_gpencil_stroke_color_use(ob, gpl, gps) == false) {
              continue;
            }
            /* some stroke is already at front*/
            if ((direction == GP_STROKE_MOVE_TOP) || (direction == GP_STROKE_MOVE_UP)) {
              if (gps == gpf->strokes.last) {
                gpf_lock = true;
                continue;
              }
            }
            /* some stroke is already at botom */
            if ((direction == GP_STROKE_MOVE_BOTTOM) || (direction == GP_STROKE_MOVE_DOWN)) {
              if (gps == gpf->strokes.first) {
                gpf_lock = true;
                continue;
              }
            }
            /* add to list (if not locked) */
            if (!gpf_lock) {
              BLI_addtail(&selected, BLI_genericNodeN(gps));
            }
          }
        }
        /* Now do the movement of the stroke */
        if (!gpf_lock) {
          switch (direction) {
            /* Bring to Front */
            case GP_STROKE_MOVE_TOP:
              LISTBASE_FOREACH (LinkData *, link, &selected) {
                gps = link->data;
                BLI_remlink(&gpf->strokes, gps);
                BLI_addtail(&gpf->strokes, gps);
              }
              break;
            /* Bring Forward */
            case GP_STROKE_MOVE_UP:
              for (LinkData *link = selected.last; link; link = link->prev) {
                gps = link->data;
                BLI_listbase_link_move(&gpf->strokes, gps, 1);
              }
              break;
            /* Send Backward */
            case GP_STROKE_MOVE_DOWN:
              LISTBASE_FOREACH (LinkData *, link, &selected) {
                gps = link->data;
                BLI_listbase_link_move(&gpf->strokes, gps, -1);
              }
              break;
            /* Send to Back */
            case GP_STROKE_MOVE_BOTTOM:
              for (LinkData *link = selected.last; link; link = link->prev) {
                gps = link->data;
                BLI_remlink(&gpf->strokes, gps);
                BLI_addhead(&gpf->strokes, gps);
              }
              break;
            default:
              BLI_assert(0);
              break;
          }
        }
        BLI_freelistN(&selected);
      }

      /* if not multiedit, exit loop*/
      if (!is_multiedit) {
        break;
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_stroke_arrange(wmOperatorType *ot)
{
  static const EnumPropertyItem slot_move[] = {
      {GP_STROKE_MOVE_TOP, "TOP", 0, "Bring to Front", ""},
      {GP_STROKE_MOVE_UP, "UP", 0, "Bring Forward", ""},
      {GP_STROKE_MOVE_DOWN, "DOWN", 0, "Send Backward", ""},
      {GP_STROKE_MOVE_BOTTOM, "BOTTOM", 0, "Send to Back", ""},
      {0, NULL, 0, NULL, NULL}};

  /* identifiers */
  ot->name = "Arrange Stroke";
  ot->idname = "GPENCIL_OT_stroke_arrange";
  ot->description = "Arrange selected strokes up/down in the drawing order of the active layer";

  /* callbacks */
  ot->exec = gp_stroke_arrange_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* properties */
  ot->prop = RNA_def_enum(ot->srna, "direction", slot_move, GP_STROKE_MOVE_UP, "Direction", "");
}

/* ******************* Move Stroke to new color ************************** */

static int gp_stroke_change_color_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  Material *ma = NULL;
  char name[MAX_ID_NAME - 2];
  RNA_string_get(op->ptr, "material", name);

  bGPdata *gpd = ED_gpencil_data_get_active(C);
  Object *ob = CTX_data_active_object(C);
  if (name[0] == '\0') {
    ma = BKE_gpencil_material(ob, ob->actcol);
  }
  else {
    ma = (Material *)BKE_libblock_find_name(bmain, ID_MA, name);
    if (ma == NULL) {
      return OPERATOR_CANCELLED;
    }
  }
  /* try to find slot */
  int idx = BKE_gpencil_object_material_index_get(ob, ma);
  if (idx < 0) {
    return OPERATOR_CANCELLED;
  }

  /* sanity checks */
  if (ELEM(NULL, gpd)) {
    return OPERATOR_CANCELLED;
  }

  const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
  if (ELEM(NULL, ma)) {
    return OPERATOR_CANCELLED;
  }

  /* loop all strokes */
  CTX_DATA_BEGIN (C, bGPDlayer *, gpl, editable_gpencil_layers) {
    bGPDframe *init_gpf = (is_multiedit) ? gpl->frames.first : gpl->actframe;

    for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
      if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
        if (gpf == NULL) {
          continue;
        }

        LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) {
          /* only if selected */
          if (gps->flag & GP_STROKE_SELECT) {
            /* skip strokes that are invalid for current view */
            if (ED_gpencil_stroke_can_use(C, gps) == false) {
              continue;
            }
            /* check if the color is editable */
            if (ED_gpencil_stroke_color_use(ob, gpl, gps) == false) {
              continue;
            }

            /* assign new color */
            gps->mat_nr = idx;
          }
        }
      }
      /* if not multiedit, exit loop*/
      if (!is_multiedit) {
        break;
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_stroke_change_color(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Change Stroke Color";
  ot->idname = "GPENCIL_OT_stroke_change_color";
  ot->description = "Move selected strokes to active material";

  /* callbacks */
  ot->exec = gp_stroke_change_color_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_string(ot->srna, "material", NULL, MAX_ID_NAME - 2, "Material", "Name of the material");
}

/* ******************* Lock color of non selected Strokes colors ************************** */

static int gp_material_lock_unsused_exec(bContext *C, wmOperator *UNUSED(op))
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);

  Object *ob = CTX_data_active_object(C);

  short *totcol = BKE_object_material_len_p(ob);

  /* sanity checks */
  if (ELEM(NULL, gpd)) {
    return OPERATOR_CANCELLED;
  }

  /* first lock all colors */
  for (short i = 0; i < *totcol; i++) {
    Material *tmp_ma = BKE_object_material_get(ob, i + 1);
    if (tmp_ma) {
      tmp_ma->gp_style->flag |= GP_MATERIAL_LOCKED;
      DEG_id_tag_update(&tmp_ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* loop all selected strokes and unlock any color */
  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    /* only editable and visible layers are considered */
    if (BKE_gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
      for (bGPDstroke *gps = gpl->actframe->strokes.last; gps; gps = gps->prev) {
        /* only if selected */
        if (gps->flag & GP_STROKE_SELECT) {
          /* skip strokes that are invalid for current view */
          if (ED_gpencil_stroke_can_use(C, gps) == false) {
            continue;
          }
          /* unlock color */
          Material *tmp_ma = BKE_object_material_get(ob, gps->mat_nr + 1);
          if (tmp_ma) {
            tmp_ma->gp_style->flag &= ~GP_MATERIAL_LOCKED;
            DEG_id_tag_update(&tmp_ma->id, ID_RECALC_COPY_ON_WRITE);
          }
        }
      }
    }
  }
  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_lock_unused(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Lock Unused Materials";
  ot->idname = "GPENCIL_OT_material_lock_unused";
  ot->description = "Lock any material not used in any selected stroke";

  /* api callbacks */
  ot->exec = gp_material_lock_unsused_exec;
  ot->poll = gp_active_layer_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ************************************************ */
/* Drawing Brushes Operators */

/* ******************* Brush resets ************************** */
static int gp_brush_reset_exec(bContext *C, wmOperator *UNUSED(op))
{
  Main *bmain = CTX_data_main(C);
  ToolSettings *ts = CTX_data_tool_settings(C);
  const enum eContextObjectMode mode = CTX_data_mode_enum(C);
  Brush *brush = NULL;

  switch (mode) {
    case CTX_MODE_PAINT_GPENCIL: {
      Paint *paint = &ts->gp_paint->paint;
      brush = paint->brush;
      if (brush && brush->gpencil_settings) {
        BKE_gpencil_brush_preset_set(bmain, brush, brush->gpencil_settings->preset_type);
      }
      break;
    }
    case CTX_MODE_SCULPT_GPENCIL: {
      Paint *paint = &ts->gp_sculptpaint->paint;
      brush = paint->brush;
      if (brush && brush->gpencil_settings) {
        BKE_gpencil_brush_preset_set(bmain, brush, brush->gpencil_settings->preset_type);
      }
      break;
    }
    case CTX_MODE_WEIGHT_GPENCIL: {
      Paint *paint = &ts->gp_weightpaint->paint;
      brush = paint->brush;
      if (brush && brush->gpencil_settings) {
        BKE_gpencil_brush_preset_set(bmain, brush, brush->gpencil_settings->preset_type);
      }
      break;
    }
    case CTX_MODE_VERTEX_GPENCIL: {
      Paint *paint = &ts->gp_vertexpaint->paint;
      brush = paint->brush;
      if (brush && brush->gpencil_settings) {
        BKE_gpencil_brush_preset_set(bmain, brush, brush->gpencil_settings->preset_type);
      }
      break;
    }
    default:
      break;
  }

  /* notifiers */
  WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_brush_reset(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Reset Brush";
  ot->idname = "GPENCIL_OT_brush_reset";
  ot->description = "Reset Brush to default parameters";

  /* api callbacks */
  ot->exec = gp_brush_reset_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static Brush *gp_brush_get_first_by_mode(Main *bmain,
                                         Paint *UNUSED(paint),
                                         const enum eContextObjectMode mode,
                                         char tool)
{
  Brush *brush_next = NULL;
  for (Brush *brush = bmain->brushes.first; brush; brush = brush_next) {
    brush_next = brush->id.next;

    if (brush->gpencil_settings == NULL) {
      continue;
    }

    if ((mode == CTX_MODE_PAINT_GPENCIL) && (brush->gpencil_tool == tool)) {
      return brush;
    }

    if ((mode == CTX_MODE_SCULPT_GPENCIL) && (brush->gpencil_sculpt_tool == tool)) {
      return brush;
    }

    if ((mode == CTX_MODE_WEIGHT_GPENCIL) && (brush->gpencil_weight_tool == tool)) {
      return brush;
    }

    if ((mode == CTX_MODE_VERTEX_GPENCIL) && (brush->gpencil_vertex_tool == tool)) {
      return brush;
    }
  }

  return NULL;
}

static void gp_brush_delete_mode_brushes(Main *bmain,
                                         Paint *paint,
                                         const enum eContextObjectMode mode)
{
  Brush *brush_active = paint->brush;
  Brush *brush_next = NULL;
  for (Brush *brush = bmain->brushes.first; brush; brush = brush_next) {
    brush_next = brush->id.next;

    if ((brush->gpencil_settings == NULL) && (brush->ob_mode != OB_MODE_PAINT_GPENCIL)) {
      continue;
    }

    short preset = (brush->gpencil_settings) ? brush->gpencil_settings->preset_type :
                                               GP_BRUSH_PRESET_UNKNOWN;

    if (preset != GP_BRUSH_PRESET_UNKNOWN) {
      /* Verify to delete only the brushes of the current mode. */
      if (mode == CTX_MODE_PAINT_GPENCIL) {
        if ((preset < GP_BRUSH_PRESET_AIRBRUSH) || (preset > GP_BRUSH_PRESET_TINT)) {
          continue;
        }
        if ((brush_active) && (brush_active->gpencil_tool != brush->gpencil_tool)) {
          continue;
        }
      }

      if (mode == CTX_MODE_SCULPT_GPENCIL) {
        if ((preset < GP_BRUSH_PRESET_SMOOTH_STROKE) || (preset > GP_BRUSH_PRESET_CLONE_STROKE)) {
          continue;
        }
        if ((brush_active) && (brush_active->gpencil_sculpt_tool != brush->gpencil_sculpt_tool)) {
          continue;
        }
      }

      if (mode == CTX_MODE_WEIGHT_GPENCIL) {
        if (preset != GP_BRUSH_PRESET_DRAW_WEIGHT) {
          continue;
        }
        if ((brush_active) && (brush_active->gpencil_weight_tool != brush->gpencil_weight_tool)) {
          continue;
        }
      }

      if (mode == CTX_MODE_VERTEX_GPENCIL) {
        if ((preset < GP_BRUSH_PRESET_VERTEX_DRAW) || (preset > GP_BRUSH_PRESET_VERTEX_REPLACE)) {
          continue;
        }
        if ((brush_active) && (brush_active->gpencil_vertex_tool != brush->gpencil_vertex_tool)) {
          continue;
        }
      }
    }

    /* Before delete, unpinn any material of the brush. */
    if ((brush->gpencil_settings) && (brush->gpencil_settings->material != NULL)) {
      brush->gpencil_settings->material = NULL;
      brush->gpencil_settings->flag &= ~GP_BRUSH_MATERIAL_PINNED;
    }

    BKE_brush_delete(bmain, brush);
  }
}

static int gp_brush_reset_all_exec(bContext *C, wmOperator *UNUSED(op))
{
  Main *bmain = CTX_data_main(C);
  ToolSettings *ts = CTX_data_tool_settings(C);
  const enum eContextObjectMode mode = CTX_data_mode_enum(C);
  Paint *paint = NULL;

  switch (mode) {
    case CTX_MODE_PAINT_GPENCIL: {
      paint = &ts->gp_paint->paint;
      break;
    }
    case CTX_MODE_SCULPT_GPENCIL: {
      paint = &ts->gp_sculptpaint->paint;
      break;
    }
    case CTX_MODE_WEIGHT_GPENCIL: {
      paint = &ts->gp_weightpaint->paint;
      break;
    }
    case CTX_MODE_VERTEX_GPENCIL: {
      paint = &ts->gp_vertexpaint->paint;
      break;
    }
    default:
      break;
  }

  char tool = '0';
  if (paint) {
    Brush *brush_active = paint->brush;
    if (brush_active) {
      switch (mode) {
        case CTX_MODE_PAINT_GPENCIL: {
          tool = brush_active->gpencil_tool;
          break;
        }
        case CTX_MODE_SCULPT_GPENCIL: {
          tool = brush_active->gpencil_sculpt_tool;
          break;
        }
        case CTX_MODE_WEIGHT_GPENCIL: {
          tool = brush_active->gpencil_weight_tool;
          break;
        }
        case CTX_MODE_VERTEX_GPENCIL: {
          tool = brush_active->gpencil_vertex_tool;
          break;
        }
        default: {
          tool = brush_active->gpencil_tool;
          break;
        }
      }
    }

    gp_brush_delete_mode_brushes(bmain, paint, mode);

    switch (mode) {
      case CTX_MODE_PAINT_GPENCIL: {
        BKE_brush_gpencil_paint_presets(bmain, ts);
        break;
      }
      case CTX_MODE_SCULPT_GPENCIL: {
        BKE_brush_gpencil_sculpt_presets(bmain, ts);
        break;
      }
      case CTX_MODE_WEIGHT_GPENCIL: {
        BKE_brush_gpencil_weight_presets(bmain, ts);
        break;
      }
      case CTX_MODE_VERTEX_GPENCIL: {
        BKE_brush_gpencil_vertex_presets(bmain, ts);
        break;
      }
      default: {
        break;
      }
    }

    BKE_paint_toolslots_brush_validate(bmain, paint);

    /* Set Again the first brush of the mode. */
    Brush *deft_brush = gp_brush_get_first_by_mode(bmain, paint, mode, tool);
    if (deft_brush) {
      BKE_paint_brush_set(paint, deft_brush);
    }
    /* notifiers */
    DEG_relations_tag_update(bmain);
    WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL);
  }

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_brush_reset_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Reset All Brushes";
  ot->idname = "GPENCIL_OT_brush_reset_all";
  ot->description = "Delete all mode brushes and recreate a default set";

  /* api callbacks */
  ot->exec = gp_brush_reset_all_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/*********************** Vertex Groups ***********************************/

static bool gpencil_vertex_group_poll(bContext *C)
{
  Object *ob = CTX_data_active_object(C);

  if ((ob) && (ob->type == OB_GPENCIL)) {
    if (!ID_IS_LINKED(ob) && !ID_IS_LINKED(ob->data) && ob->defbase.first) {
      if (ELEM(ob->mode, OB_MODE_EDIT_GPENCIL, OB_MODE_SCULPT_GPENCIL)) {
        return true;
      }
    }
  }

  return false;
}

static bool gpencil_vertex_group_weight_poll(bContext *C)
{
  Object *ob = CTX_data_active_object(C);

  if ((ob) && (ob->type == OB_GPENCIL)) {
    if (!ID_IS_LINKED(ob) && !ID_IS_LINKED(ob->data) && ob->defbase.first) {
      if (ob->mode == OB_MODE_WEIGHT_GPENCIL) {
        return true;
      }
    }
  }

  return false;
}

static int gpencil_vertex_group_assign_exec(bContext *C, wmOperator *UNUSED(op))
{
  ToolSettings *ts = CTX_data_tool_settings(C);
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ts, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  ED_gpencil_vgroup_assign(C, ob, ts->vgroup_weight);

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_assign(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Assign to Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_assign";
  ot->description = "Assign the selected vertices to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_poll;
  ot->exec = gpencil_vertex_group_assign_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* remove point from vertex group */
static int gpencil_vertex_group_remove_from_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  ED_gpencil_vgroup_remove(C, ob);

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_remove_from(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove from Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_remove_from";
  ot->description = "Remove the selected vertices from active or all vertex group(s)";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_poll;
  ot->exec = gpencil_vertex_group_remove_from_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int gpencil_vertex_group_select_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  ED_gpencil_vgroup_select(C, ob);

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_select(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Select Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_select";
  ot->description = "Select all the vertices assigned to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_poll;
  ot->exec = gpencil_vertex_group_select_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int gpencil_vertex_group_deselect_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  ED_gpencil_vgroup_deselect(C, ob);

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_deselect(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Deselect Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_deselect";
  ot->description = "Deselect all selected vertices assigned to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_poll;
  ot->exec = gpencil_vertex_group_deselect_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* invert */
static int gpencil_vertex_group_invert_exec(bContext *C, wmOperator *op)
{
  ToolSettings *ts = CTX_data_tool_settings(C);
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ts, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  MDeformVert *dvert;
  const int def_nr = ob->actdef - 1;
  bDeformGroup *defgroup = BLI_findlink(&ob->defbase, def_nr);
  if (defgroup == NULL) {
    return OPERATOR_CANCELLED;
  }
  if (defgroup->flag & DG_LOCK_WEIGHT) {
    BKE_report(op->reports, RPT_ERROR, "Current Vertex Group is locked");
    return OPERATOR_CANCELLED;
  }

  CTX_DATA_BEGIN (C, bGPDstroke *, gps, editable_gpencil_strokes) {
    /* Verify the strokes has something to change. */
    if ((gps->totpoints == 0) || (gps->dvert == NULL)) {
      continue;
    }

    for (int i = 0; i < gps->totpoints; i++) {
      dvert = &gps->dvert[i];
      MDeformWeight *dw = BKE_defvert_find_index(dvert, def_nr);
      if (dw == NULL) {
        BKE_defvert_add_index_notest(dvert, def_nr, 1.0f);
      }
      else if (dw->weight == 1.0f) {
        BKE_defvert_remove_group(dvert, dw);
      }
      else {
        dw->weight = 1.0f - dw->weight;
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_invert(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Invert Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_invert";
  ot->description = "Invert weights to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_weight_poll;
  ot->exec = gpencil_vertex_group_invert_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* smooth */
static int gpencil_vertex_group_smooth_exec(bContext *C, wmOperator *op)
{
  const float fac = RNA_float_get(op->ptr, "factor");
  const int repeat = RNA_int_get(op->ptr, "repeat");

  ToolSettings *ts = CTX_data_tool_settings(C);
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ts, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  const int def_nr = ob->actdef - 1;
  bDeformGroup *defgroup = BLI_findlink(&ob->defbase, def_nr);
  if (defgroup == NULL) {
    return OPERATOR_CANCELLED;
  }
  if (defgroup->flag & DG_LOCK_WEIGHT) {
    BKE_report(op->reports, RPT_ERROR, "Current Vertex Group is locked");
    return OPERATOR_CANCELLED;
  }

  bGPDspoint *pta, *ptb, *ptc;
  MDeformVert *dverta, *dvertb;

  CTX_DATA_BEGIN (C, bGPDstroke *, gps, editable_gpencil_strokes) {
    /* Verify the strokes has something to change. */
    if ((gps->totpoints == 0) || (gps->dvert == NULL)) {
      continue;
    }

    for (int s = 0; s < repeat; s++) {
      for (int i = 0; i < gps->totpoints; i++) {
        /* previous point */
        if (i > 0) {
          pta = &gps->points[i - 1];
          dverta = &gps->dvert[i - 1];
        }
        else {
          pta = &gps->points[i];
          dverta = &gps->dvert[i];
        }
        /* current */
        ptb = &gps->points[i];
        dvertb = &gps->dvert[i];
        /* next point */
        if (i + 1 < gps->totpoints) {
          ptc = &gps->points[i + 1];
        }
        else {
          ptc = &gps->points[i];
        }

        float wa = BKE_defvert_find_weight(dverta, def_nr);
        float wb = BKE_defvert_find_weight(dvertb, def_nr);

        /* the optimal value is the corresponding to the interpolation of the weight
         * at the distance of point b
         */
        const float opfac = line_point_factor_v3(&ptb->x, &pta->x, &ptc->x);
        const float optimal = interpf(wa, wb, opfac);
        /* Based on influence factor, blend between original and optimal */
        MDeformWeight *dw = BKE_defvert_ensure_index(dvertb, def_nr);
        if (dw) {
          dw->weight = interpf(wb, optimal, fac);
          CLAMP(dw->weight, 0.0, 1.0f);
        }
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_smooth(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Smooth Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_smooth";
  ot->description = "Smooth weights to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_weight_poll;
  ot->exec = gpencil_vertex_group_smooth_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0, "Factor", "", 0.0f, 1.0f);
  RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
}

/* normalize */
static int gpencil_vertex_group_normalize_exec(bContext *C, wmOperator *op)
{
  ToolSettings *ts = CTX_data_tool_settings(C);
  Object *ob = CTX_data_active_object(C);

  /* sanity checks */
  if (ELEM(NULL, ts, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  MDeformVert *dvert = NULL;
  MDeformWeight *dw = NULL;
  const int def_nr = ob->actdef - 1;
  bDeformGroup *defgroup = BLI_findlink(&ob->defbase, def_nr);
  if (defgroup == NULL) {
    return OPERATOR_CANCELLED;
  }
  if (defgroup->flag & DG_LOCK_WEIGHT) {
    BKE_report(op->reports, RPT_ERROR, "Current Vertex Group is locked");
    return OPERATOR_CANCELLED;
  }

  CTX_DATA_BEGIN (C, bGPDstroke *, gps, editable_gpencil_strokes) {
    /* Verify the strokes has something to change. */
    if ((gps->totpoints == 0) || (gps->dvert == NULL)) {
      continue;
    }

    /* look for max value */
    float maxvalue = 0.0f;
    for (int i = 0; i < gps->totpoints; i++) {
      dvert = &gps->dvert[i];
      dw = BKE_defvert_find_index(dvert, def_nr);
      if ((dw != NULL) && (dw->weight > maxvalue)) {
        maxvalue = dw->weight;
      }
    }

    /* normalize weights */
    if (maxvalue > 0.0f) {
      for (int i = 0; i < gps->totpoints; i++) {
        dvert = &gps->dvert[i];
        dw = BKE_defvert_find_index(dvert, def_nr);
        if (dw != NULL) {
          dw->weight = dw->weight / maxvalue;
        }
      }
    }
  }
  CTX_DATA_END;

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_normalize(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Normalize Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_normalize";
  ot->description = "Normalize weights to the active vertex group";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_weight_poll;
  ot->exec = gpencil_vertex_group_normalize_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* normalize all */
static int gpencil_vertex_group_normalize_all_exec(bContext *C, wmOperator *op)
{
  ToolSettings *ts = CTX_data_tool_settings(C);
  Object *ob = CTX_data_active_object(C);
  bool lock_active = RNA_boolean_get(op->ptr, "lock_active");

  /* sanity checks */
  if (ELEM(NULL, ts, ob, ob->data)) {
    return OPERATOR_CANCELLED;
  }

  bDeformGroup *defgroup = NULL;
  MDeformVert *dvert = NULL;
  MDeformWeight *dw = NULL;
  const int def_nr = ob->actdef - 1;
  const int defbase_tot = BLI_listbase_count(&ob->defbase);
  if (defbase_tot == 0) {
    return OPERATOR_CANCELLED;
  }

  CTX_DATA_BEGIN (C, bGPDstroke *, gps, editable_gpencil_strokes) {
    /* Verify the strokes has something to change. */
    if ((gps->totpoints == 0) || (gps->dvert == NULL)) {
      continue;
    }

    /* look for tot value */
    float *tot_values = MEM_callocN(gps->totpoints * sizeof(float), __func__);

    for (int i = 0; i < gps->totpoints; i++) {
      dvert = &gps->dvert[i];
      for (int v = 0; v < defbase_tot; v++) {
        defgroup = BLI_findlink(&ob->defbase, v);
        /* skip NULL or locked groups */
        if ((defgroup == NULL) || (defgroup->flag & DG_LOCK_WEIGHT)) {
          continue;
        }

        /* skip current */
        if ((lock_active) && (v == def_nr)) {
          continue;
        }

        dw = BKE_defvert_find_index(dvert, v);
        if (dw != NULL) {
          tot_values[i] += dw->weight;
        }
      }
    }

    /* normalize weights */
    for (int i = 0; i < gps->totpoints; i++) {
      if (tot_values[i] == 0.0f) {
        continue;
      }

      dvert = &gps->dvert[i];
      for (int v = 0; v < defbase_tot; v++) {
        defgroup = BLI_findlink(&ob->defbase, v);
        /* skip NULL or locked groups */
        if ((defgroup == NULL) || (defgroup->flag & DG_LOCK_WEIGHT)) {
          continue;
        }

        /* skip current */
        if ((lock_active) && (v == def_nr)) {
          continue;
        }

        dw = BKE_defvert_find_index(dvert, v);
        if (dw != NULL) {
          dw->weight = dw->weight / tot_values[i];
        }
      }
    }

    /* free temp array */
    MEM_SAFE_FREE(tot_values);
  }
  CTX_DATA_END;

  /* notifiers */
  bGPdata *gpd = ob->data;
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED | ND_SPACE_PROPERTIES, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_vertex_group_normalize_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Normalize All Vertex Group";
  ot->idname = "GPENCIL_OT_vertex_group_normalize_all";
  ot->description =
      "Normalize all weights of all vertex groups, "
      "so that for each vertex, the sum of all weights is 1.0";

  /* api callbacks */
  ot->poll = gpencil_vertex_group_weight_poll;
  ot->exec = gpencil_vertex_group_normalize_all_exec;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* props */
  RNA_def_boolean(ot->srna,
                  "lock_active",
                  true,
                  "Lock Active",
                  "Keep the values of the active group while normalizing others");
}

/****************************** Join ***********************************/

/* userdata for joined_gpencil_fix_animdata_cb() */
typedef struct tJoinGPencil_AdtFixData {
  bGPdata *src_gpd;
  bGPdata *tar_gpd;

  GHash *names_map;
} tJoinGPencil_AdtFixData;

/**
 * Callback to pass to #BKE_fcurves_main_cb()
 * for RNA Paths attached to each F-Curve used in the #AnimData.
 */
static void joined_gpencil_fix_animdata_cb(ID *id, FCurve *fcu, void *user_data)
{
  tJoinGPencil_AdtFixData *afd = (tJoinGPencil_AdtFixData *)user_data;
  ID *src_id = &afd->src_gpd->id;
  ID *dst_id = &afd->tar_gpd->id;

  GHashIterator gh_iter;

  /* Fix paths - If this is the target datablock, it will have some "dirty" paths */
  if ((id == src_id) && fcu->rna_path && strstr(fcu->rna_path, "layers[")) {
    GHASH_ITER (gh_iter, afd->names_map) {
      const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
      const char *new_name = BLI_ghashIterator_getValue(&gh_iter);

      /* only remap if changed;
       * this still means there will be some waste if there aren't many drivers/keys */
      if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
        fcu->rna_path = BKE_animsys_fix_rna_path_rename(
            id, fcu->rna_path, "layers", old_name, new_name, 0, 0, false);

        /* we don't want to apply a second remapping on this F-Curve now,
         * so stop trying to fix names names
         */
        break;
      }
    }
  }

  /* Fix driver targets */
  if (fcu->driver) {
    /* Fix driver references to invalid ID's */
    LISTBASE_FOREACH (DriverVar *, dvar, &fcu->driver->variables) {
      /* Only change the used targets, since the others will need fixing manually anyway. */
      DRIVER_TARGETS_USED_LOOPER_BEGIN (dvar) {
        /* Change the ID's used. */
        if (dtar->id == src_id) {
          dtar->id = dst_id;

          /* Also check on the subtarget...
           * We duplicate the logic from drivers_path_rename_fix() here, with our own
           * little twists so that we know that it isn't going to clobber the wrong data
           */
          if (dtar->rna_path && strstr(dtar->rna_path, "layers[")) {
            GHASH_ITER (gh_iter, afd->names_map) {
              const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
              const char *new_name = BLI_ghashIterator_getValue(&gh_iter);

              /* Only remap if changed. */
              if (!STREQ(old_name, new_name)) {
                if ((dtar->rna_path) && strstr(dtar->rna_path, old_name)) {
                  /* Fix up path */
                  dtar->rna_path = BKE_animsys_fix_rna_path_rename(
                      id, dtar->rna_path, "layers", old_name, new_name, 0, 0, false);
                  break; /* no need to try any more names for layer path */
                }
              }
            }
          }
        }
      }
      DRIVER_TARGETS_LOOPER_END;
    }
  }
}

/* join objects called from OBJECT_OT_join */
int ED_gpencil_join_objects_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);
  Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);
  Object *ob_active = CTX_data_active_object(C);
  bGPdata *gpd_dst = NULL;
  bool ok = false;

  /* Ensure we're in right mode and that the active object is correct */
  if (!ob_active || ob_active->type != OB_GPENCIL) {
    return OPERATOR_CANCELLED;
  }

  bGPdata *gpd = (bGPdata *)ob_active->data;
  if ((!gpd) || GPENCIL_ANY_MODE(gpd)) {
    return OPERATOR_CANCELLED;
  }

  /* Ensure all rotations are applied before */
  CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects) {
    if (ob_iter->type == OB_GPENCIL) {
      if ((ob_iter->rot[0] != 0) || (ob_iter->rot[1] != 0) || (ob_iter->rot[2] != 0)) {
        BKE_report(op->reports, RPT_ERROR, "Apply all rotations before join objects");
        return OPERATOR_CANCELLED;
      }
    }
  }
  CTX_DATA_END;

  CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects) {
    if (ob_iter == ob_active) {
      ok = true;
      break;
    }
  }
  CTX_DATA_END;

  /* that way the active object is always selected */
  if (ok == false) {
    BKE_report(op->reports, RPT_WARNING, "Active object is not a selected grease pencil");
    return OPERATOR_CANCELLED;
  }

  gpd_dst = ob_active->data;
  Object *ob_dst = ob_active;

  /* loop and join all data */
  CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects) {
    if ((ob_iter->type == OB_GPENCIL) && (ob_iter != ob_active)) {
      /* we assume that each datablock is not already used in active object */
      if (ob_active->data != ob_iter->data) {
        Object *ob_src = ob_iter;
        bGPdata *gpd_src = ob_iter->data;

        /* Apply all GP modifiers before */
        LISTBASE_FOREACH (GpencilModifierData *, md, &ob_iter->greasepencil_modifiers) {
          const GpencilModifierTypeInfo *mti = BKE_gpencil_modifier_get_info(md->type);
          if (mti->bakeModifier) {
            mti->bakeModifier(bmain, depsgraph, md, ob_iter);
          }
        }

        /* copy vertex groups to the base one's */
        int old_idx = 0;
        LISTBASE_FOREACH (bDeformGroup *, dg, &ob_iter->defbase) {
          bDeformGroup *vgroup = MEM_dupallocN(dg);
          int idx = BLI_listbase_count(&ob_active->defbase);
          BKE_object_defgroup_unique_name(vgroup, ob_active);
          BLI_addtail(&ob_active->defbase, vgroup);
          /* update vertex groups in strokes in original data */
          LISTBASE_FOREACH (bGPDlayer *, gpl_src, &gpd->layers) {
            LISTBASE_FOREACH (bGPDframe *, gpf, &gpl_src->frames) {
              LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) {
                MDeformVert *dvert;
                int i;
                if (gps->dvert == NULL) {
                  continue;
                }
                for (i = 0, dvert = gps->dvert; i < gps->totpoints; i++, dvert++) {
                  if ((dvert->dw != NULL) && (dvert->dw->def_nr == old_idx)) {
                    dvert->dw->def_nr = idx;
                  }
                }
              }
            }
          }
          old_idx++;
        }
        if (ob_active->defbase.first && ob_active->actdef == 0) {
          ob_active->actdef = 1;
        }

        /* add missing materials reading source materials and checking in destination object */
        short *totcol = BKE_object_material_len_p(ob_src);

        for (short i = 0; i < *totcol; i++) {
          Material *tmp_ma = BKE_gpencil_material(ob_src, i + 1);
          BKE_gpencil_object_material_ensure(bmain, ob_dst, tmp_ma);
        }

        /* duplicate bGPDlayers  */
        tJoinGPencil_AdtFixData afd = {0};
        afd.src_gpd = gpd_src;
        afd.tar_gpd = gpd_dst;
        afd.names_map = BLI_ghash_str_new("joined_gp_layers_map");

        float imat[3][3], bmat[3][3];
        float offset_global[3];
        float offset_local[3];

        sub_v3_v3v3(offset_global, ob_active->loc, ob_iter->obmat[3]);
        copy_m3_m4(bmat, ob_active->obmat);
        invert_m3_m3(imat, bmat);
        mul_m3_v3(imat, offset_global);
        mul_v3_m3v3(offset_local, imat, offset_global);

        LISTBASE_FOREACH (bGPDlayer *, gpl_src, &gpd_src->layers) {
          bGPDlayer *gpl_new = BKE_gpencil_layer_duplicate(gpl_src);
          float diff_mat[4][4];
          float inverse_diff_mat[4][4];

          /* recalculate all stroke points */
          BKE_gpencil_parent_matrix_get(depsgraph, ob_iter, gpl_src, diff_mat);
          invert_m4_m4(inverse_diff_mat, diff_mat);

          Material *ma_src = NULL;
          LISTBASE_FOREACH (bGPDframe *, gpf, &gpl_new->frames) {
            LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) {

              /* Reassign material. Look old material and try to find in destination. */
              ma_src = BKE_gpencil_material(ob_src, gps->mat_nr + 1);
              gps->mat_nr = BKE_gpencil_object_material_ensure(bmain, ob_dst, ma_src);

              bGPDspoint *pt;
              int i;
              for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
                float mpt[3];
                mul_v3_m4v3(mpt, inverse_diff_mat, &pt->x);
                sub_v3_v3(mpt, offset_local);
                mul_v3_m4v3(&pt->x, diff_mat, mpt);
              }
            }
          }

          /* be sure name is unique in new object */
          BLI_uniquename(&gpd_dst->layers,
                         gpl_new,
                         DATA_("GP_Layer"),
                         '.',
                         offsetof(bGPDlayer, info),
                         sizeof(gpl_new->info));
          BLI_ghash_insert(afd.names_map, BLI_strdup(gpl_src->info), gpl_new->info);

          /* add to destination datablock */
          BLI_addtail(&gpd_dst->layers, gpl_new);
        }

        /* Fix all the animation data */
        BKE_fcurves_main_cb(bmain, joined_gpencil_fix_animdata_cb, &afd);
        BLI_ghash_free(afd.names_map, MEM_freeN, NULL);

        /* Only copy over animdata now, after all the remapping has been done,
         * so that we don't have to worry about ambiguities re which datablock
         * a layer came from!
         */
        if (ob_iter->adt) {
          if (ob_active->adt == NULL) {
            /* no animdata, so just use a copy of the whole thing */
            ob_active->adt = BKE_animdata_copy(bmain, ob_iter->adt, 0);
          }
          else {
            /* merge in data - we'll fix the drivers manually */
            BKE_animdata_merge_copy(
                bmain, &ob_active->id, &ob_iter->id, ADT_MERGECOPY_KEEP_DST, false);
          }
        }

        if (gpd_src->adt) {
          if (gpd_dst->adt == NULL) {
            /* no animdata, so just use a copy of the whole thing */
            gpd_dst->adt = BKE_animdata_copy(bmain, gpd_src->adt, 0);
          }
          else {
            /* merge in data - we'll fix the drivers manually */
            BKE_animdata_merge_copy(
                bmain, &gpd_dst->id, &gpd_src->id, ADT_MERGECOPY_KEEP_DST, false);
          }
        }
        DEG_id_tag_update(&gpd_src->id,
                          ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
      }

      /* Free the old object */
      ED_object_base_free_and_unlink(bmain, scene, ob_iter);
    }
  }
  CTX_DATA_END;

  DEG_id_tag_update(&gpd_dst->id,
                    ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
  DEG_relations_tag_update(bmain); /* because we removed object(s) */

  WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);

  return OPERATOR_FINISHED;
}

/* Color Handle operator */
static bool gpencil_active_material_poll(bContext *C)
{
  Object *ob = CTX_data_active_object(C);
  if (ob && ob->data && (ob->type == OB_GPENCIL)) {
    short *totcolp = BKE_object_material_len_p(ob);
    return *totcolp > 0;
  }
  return false;
}

/* **************** Lock and hide any color non used in current layer **************************
 */
static int gpencil_lock_layer_exec(bContext *C, wmOperator *UNUSED(op))
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  Object *ob = CTX_data_active_object(C);
  MaterialGPencilStyle *gp_style = NULL;

  /* sanity checks */
  if (ELEM(NULL, gpd)) {
    return OPERATOR_CANCELLED;
  }

  /* first lock and hide all colors */
  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);
  if (totcol == 0) {
    return OPERATOR_CANCELLED;
  }

  for (short i = 0; i < *totcol; i++) {
    ma = BKE_gpencil_material(ob, i + 1);
    if (ma) {
      gp_style = ma->gp_style;
      gp_style->flag |= GP_MATERIAL_LOCKED;
      gp_style->flag |= GP_MATERIAL_HIDE;
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* loop all selected strokes and unlock any color used in active layer */
  LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
    /* only editable and visible layers are considered */
    if (BKE_gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL) &&
        (gpl->flag & GP_LAYER_ACTIVE)) {
      for (bGPDstroke *gps = gpl->actframe->strokes.last; gps; gps = gps->prev) {
        /* skip strokes that are invalid for current view */
        if (ED_gpencil_stroke_can_use(C, gps) == false) {
          continue;
        }

        ma = BKE_gpencil_material(ob, gps->mat_nr + 1);
        DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);

        gp_style = ma->gp_style;
        /* unlock/unhide color if not unlocked before */
        if (gp_style != NULL) {
          gp_style->flag &= ~GP_MATERIAL_LOCKED;
          gp_style->flag &= ~GP_MATERIAL_HIDE;
        }
      }
    }
  }
  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_lock_layer(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Disable Unused Layer Colors";
  ot->idname = "GPENCIL_OT_lock_layer";
  ot->description = "Lock and hide any color not used in any layer";

  /* api callbacks */
  ot->exec = gpencil_lock_layer_exec;
  ot->poll = gp_active_layer_poll;
}

/* ********************** Isolate gpencil_ color **************************** */

static int gpencil_material_isolate_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  Object *ob = CTX_data_active_object(C);
  Material *active_ma = BKE_gpencil_material(ob, ob->actcol);
  MaterialGPencilStyle *active_color = BKE_gpencil_material_settings(ob, ob->actcol);
  MaterialGPencilStyle *gp_style;

  int flags = GP_MATERIAL_LOCKED;
  bool isolate = false;

  if (RNA_boolean_get(op->ptr, "affect_visibility")) {
    flags |= GP_MATERIAL_HIDE;
  }

  if (ELEM(NULL, gpd, active_color)) {
    BKE_report(op->reports, RPT_ERROR, "No active color to isolate");
    return OPERATOR_CANCELLED;
  }

  /* Test whether to isolate or clear all flags */
  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);
  for (short i = 0; i < *totcol; i++) {
    ma = BKE_gpencil_material(ob, i + 1);
    /* Skip if this is the active one */
    if ((ma == NULL) || (ma == active_ma)) {
      continue;
    }

    /* If the flags aren't set, that means that the color is
     * not alone, so we have some colors to isolate still
     */
    gp_style = ma->gp_style;
    if ((gp_style->flag & flags) == 0) {
      isolate = true;
      break;
    }
  }

  /* Set/Clear flags as appropriate */
  if (isolate) {
    /* Set flags on all "other" colors */
    for (short i = 0; i < *totcol; i++) {
      ma = BKE_gpencil_material(ob, i + 1);
      if (ma == NULL) {
        continue;
      }
      gp_style = ma->gp_style;
      if (gp_style == active_color) {
        continue;
      }
      else {
        gp_style->flag |= flags;
      }
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }
  else {
    /* Clear flags - Restore everything else */
    for (short i = 0; i < *totcol; i++) {
      ma = BKE_gpencil_material(ob, i + 1);
      if (ma == NULL) {
        continue;
      }
      gp_style = ma->gp_style;
      gp_style->flag &= ~flags;
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_isolate(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Isolate Material";
  ot->idname = "GPENCIL_OT_material_isolate";
  ot->description =
      "Toggle whether the active material is the only one that is editable and/or visible";

  /* callbacks */
  ot->exec = gpencil_material_isolate_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* properties */
  RNA_def_boolean(ot->srna,
                  "affect_visibility",
                  false,
                  "Affect Visibility",
                  "In addition to toggling "
                  "the editability, also affect the visibility");
}

/* *********************** Hide colors ******************************** */

static int gpencil_material_hide_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = (bGPdata *)ob->data;
  MaterialGPencilStyle *active_color = BKE_gpencil_material_settings(ob, ob->actcol);

  bool unselected = RNA_boolean_get(op->ptr, "unselected");

  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);
  if (totcol == 0) {
    return OPERATOR_CANCELLED;
  }

  if (unselected) {
    /* hide unselected */
    MaterialGPencilStyle *color = NULL;
    for (short i = 0; i < *totcol; i++) {
      ma = BKE_gpencil_material(ob, i + 1);
      if (ma) {
        color = ma->gp_style;
        if (active_color != color) {
          color->flag |= GP_MATERIAL_HIDE;
          DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
        }
      }
    }
  }
  else {
    /* hide selected/active */
    active_color->flag |= GP_MATERIAL_HIDE;
  }

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_hide(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Hide Material(s)";
  ot->idname = "GPENCIL_OT_material_hide";
  ot->description = "Hide selected/unselected Grease Pencil materials";

  /* callbacks */
  ot->exec = gpencil_material_hide_exec;
  ot->poll = gpencil_active_material_poll; /* NOTE: we need an active color to play with */

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* props */
  RNA_def_boolean(
      ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected colors");
}

/* ********************** Show All Colors ***************************** */

static int gpencil_material_reveal_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = (bGPdata *)ob->data;
  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);

  if (totcol == 0) {
    return OPERATOR_CANCELLED;
  }

  /* make all colors visible */
  MaterialGPencilStyle *gp_style = NULL;

  for (short i = 0; i < *totcol; i++) {
    ma = BKE_gpencil_material(ob, i + 1);
    if (ma) {
      gp_style = ma->gp_style;
      gp_style->flag &= ~GP_MATERIAL_HIDE;
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_reveal(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Show All Materials";
  ot->idname = "GPENCIL_OT_material_reveal";
  ot->description = "Unhide all hidden Grease Pencil materials";

  /* callbacks */
  ot->exec = gpencil_material_reveal_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ***************** Lock/Unlock All colors ************************ */

static int gpencil_material_lock_all_exec(bContext *C, wmOperator *UNUSED(op))
{

  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = (bGPdata *)ob->data;
  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);

  if (totcol == 0) {
    return OPERATOR_CANCELLED;
  }

  /* make all layers non-editable */
  MaterialGPencilStyle *gp_style = NULL;

  for (short i = 0; i < *totcol; i++) {
    ma = BKE_gpencil_material(ob, i + 1);
    if (ma) {
      gp_style = ma->gp_style;
      gp_style->flag |= GP_MATERIAL_LOCKED;
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_lock_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Lock All Materials";
  ot->idname = "GPENCIL_OT_material_lock_all";
  ot->description =
      "Lock all Grease Pencil materials to prevent them from being accidentally modified";

  /* callbacks */
  ot->exec = gpencil_material_lock_all_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* -------------------------- */

static int gpencil_material_unlock_all_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = (bGPdata *)ob->data;
  Material *ma = NULL;
  short *totcol = BKE_object_material_len_p(ob);

  if (totcol == 0) {
    return OPERATOR_CANCELLED;
  }

  /* make all layers editable again*/
  MaterialGPencilStyle *gp_style = NULL;

  for (short i = 0; i < *totcol; i++) {
    ma = BKE_gpencil_material(ob, i + 1);
    if (ma) {
      gp_style = ma->gp_style;
      gp_style->flag &= ~GP_MATERIAL_LOCKED;
      DEG_id_tag_update(&ma->id, ID_RECALC_COPY_ON_WRITE);
    }
  }

  /* updates */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY);

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_unlock_all(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Unlock All Materials";
  ot->idname = "GPENCIL_OT_material_unlock_all";
  ot->description = "Unlock all Grease Pencil materials so that they can be edited";

  /* callbacks */
  ot->exec = gpencil_material_unlock_all_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* ***************** Select all strokes using color ************************ */

static int gpencil_material_select_exec(bContext *C, wmOperator *op)
{
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  Object *ob = CTX_data_active_object(C);
  MaterialGPencilStyle *gp_style = BKE_gpencil_material_settings(ob, ob->actcol);
  const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
  const bool deselected = RNA_boolean_get(op->ptr, "deselect");

  /* sanity checks */
  if (ELEM(NULL, gpd, gp_style)) {
    return OPERATOR_CANCELLED;
  }

  /* read all strokes and select*/
  CTX_DATA_BEGIN (C, bGPDlayer *, gpl, editable_gpencil_layers) {
    bGPDframe *init_gpf = (is_multiedit) ? gpl->frames.first : gpl->actframe;

    for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
      if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {

        /* verify something to do */
        LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) {
          /* skip strokes that are invalid for current view */
          if (ED_gpencil_stroke_can_use(C, gps) == false) {
            continue;
          }
          /* check if the color is editable */
          if (ED_gpencil_stroke_color_use(ob, gpl, gps) == false) {
            continue;
          }

          /* select */
          if (ob->actcol == gps->mat_nr + 1) {
            bGPDspoint *pt;
            int i;

            if (!deselected) {
              gps->flag |= GP_STROKE_SELECT;
            }
            else {
              gps->flag &= ~GP_STROKE_SELECT;
            }
            for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
              if (!deselected) {
                pt->flag |= GP_SPOINT_SELECT;
              }
              else {
                pt->flag &= ~GP_SPOINT_SELECT;
              }
            }
          }
        }
      }
      /* if not multiedit, exit loop*/
      if (!is_multiedit) {
        break;
      }
    }
  }
  CTX_DATA_END;

  /* copy on write tag is needed, or else no refresh happens */
  DEG_id_tag_update(&gpd->id, ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);

  /* notifiers */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_select(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Select Material";
  ot->idname = "GPENCIL_OT_material_select";
  ot->description = "Select/Deselect all Grease Pencil strokes using current material";

  /* callbacks */
  ot->exec = gpencil_material_select_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* props */
  ot->prop = RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Unselect strokes");
  RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}

/* ***************** Set active material ************************* */
static int gpencil_material_set_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  int slot = RNA_enum_get(op->ptr, "slot");

  /* Try to get material */
  if ((slot < 1) || (slot > ob->totcol)) {
    BKE_reportf(
        op->reports, RPT_ERROR, "Cannot change to non-existent material (index = %d)", slot);
    return OPERATOR_CANCELLED;
  }

  /* Set active material. */
  ob->actcol = slot;

  /* updates */
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_SELECTED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_material_set(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Set Material";
  ot->idname = "GPENCIL_OT_material_set";
  ot->description = "Set active material";

  /* callbacks */
  ot->exec = gpencil_material_set_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* Material to use (dynamic enum) */
  ot->prop = RNA_def_enum(ot->srna, "slot", DummyRNA_DEFAULT_items, 0, "Material Slot", "");
  RNA_def_enum_funcs(ot->prop, ED_gpencil_material_enum_itemf);
}

/* ***************** Set selected stroke material the active material ************************ */

static int gpencil_set_active_material_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  bGPdata *gpd = ED_gpencil_data_get_active(C);
  bool changed = false;

  /* Sanity checks. */
  if (gpd == NULL) {
    BKE_report(op->reports, RPT_ERROR, "No Grease Pencil data");
    return OPERATOR_CANCELLED;
  }

  /* Loop all selected strokes. */
  GP_EDITABLE_STROKES_BEGIN (gpstroke_iter, C, gpl, gps) {
    if (gps->flag & GP_STROKE_SELECT) {
      /* Change Active material. */
      ob->actcol = gps->mat_nr + 1;
      changed = true;
      break;
    }
  }
  GP_EDITABLE_STROKES_END(gpstroke_iter);

  /* notifiers */
  if (changed) {
    WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
  }

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_set_active_material(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Set active material";
  ot->idname = "GPENCIL_OT_set_active_material";
  ot->description = "Set the selected stroke material as the active material";

  /* callbacks */
  ot->exec = gpencil_set_active_material_exec;
  ot->poll = gpencil_active_material_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/* Parent GPencil object to Lattice */
bool ED_gpencil_add_lattice_modifier(const bContext *C,
                                     ReportList *reports,
                                     Object *ob,
                                     Object *ob_latt)
{
  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);

  if (ob == NULL) {
    return false;
  }

  /* if no lattice modifier, add a new one */
  GpencilModifierData *md = BKE_gpencil_modifiers_findby_type(ob, eGpencilModifierType_Lattice);
  if (md == NULL) {
    md = ED_object_gpencil_modifier_add(
        reports, bmain, scene, ob, "Lattice", eGpencilModifierType_Lattice);
    if (md == NULL) {
      BKE_report(reports, RPT_ERROR, "Unable to add a new Lattice modifier to object");
      return false;
    }
    DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  }

  /* verify lattice */
  LatticeGpencilModifierData *mmd = (LatticeGpencilModifierData *)md;
  if (mmd->object == NULL) {
    mmd->object = ob_latt;
  }
  else {
    if (ob_latt != mmd->object) {
      BKE_report(reports,
                 RPT_ERROR,
                 "The existing Lattice modifier is already using a different Lattice object");
      return false;
    }
  }

  return true;
}

/* Masking operators */
static int gp_layer_mask_add_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  if ((ob == NULL) || (ob->type != OB_GPENCIL)) {
    return OPERATOR_CANCELLED;
  }

  bGPdata *gpd = (bGPdata *)ob->data;
  bGPDlayer *gpl_active = BKE_gpencil_layer_active_get(gpd);
  if (gpl_active == NULL) {
    return OPERATOR_CANCELLED;
  }
  char name[128];
  RNA_string_get(op->ptr, "name", name);
  bGPDlayer *gpl = BKE_gpencil_layer_named_get(gpd, name);

  if (gpl == NULL) {
    BKE_report(op->reports, RPT_ERROR, "Unable to find layer to add");
    return OPERATOR_CANCELLED;
  }

  if (gpl == gpl_active) {
    BKE_report(op->reports, RPT_ERROR, "Cannot add active layer as mask");
    return OPERATOR_CANCELLED;
  }

  if (BKE_gpencil_layer_mask_named_get(gpl_active, name)) {
    BKE_report(op->reports, RPT_ERROR, "Layer already added");
    return OPERATOR_CANCELLED;
  }

  if (gpl_active->act_mask == 256) {
    BKE_report(op->reports, RPT_ERROR, "Maximum number of masking layers reached");
    return OPERATOR_CANCELLED;
  }

  BKE_gpencil_layer_mask_add(gpl_active, name);

  /* Reorder masking. */
  BKE_gpencil_layer_mask_sort(gpd, gpl_active);

  /* notifiers */
  if (gpd) {
    DEG_id_tag_update(&gpd->id,
                      ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
  }
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_mask_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add New Mask Layer";
  ot->idname = "GPENCIL_OT_layer_mask_add";
  ot->description = "Add new layer as masking";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_mask_add_exec;
  ot->poll = gp_add_poll;

  /* properties */
  RNA_def_string(ot->srna, "name", NULL, 128, "Layer", "Name of the layer");
}

static int gp_layer_mask_remove_exec(bContext *C, wmOperator *UNUSED(op))
{
  Object *ob = CTX_data_active_object(C);
  if ((ob == NULL) || (ob->type != OB_GPENCIL)) {
    return OPERATOR_CANCELLED;
  }

  bGPdata *gpd = (bGPdata *)ob->data;
  bGPDlayer *gpl = BKE_gpencil_layer_active_get(gpd);
  if (gpl == NULL) {
    return OPERATOR_CANCELLED;
  }
  if (gpl->act_mask > 0) {
    bGPDlayer_Mask *mask = BLI_findlink(&gpl->mask_layers, gpl->act_mask - 1);
    if (mask != NULL) {
      BKE_gpencil_layer_mask_remove(gpl, mask);
      if ((gpl->mask_layers.first != NULL) && (gpl->act_mask == 0)) {
        gpl->act_mask = 1;
      }
    }
  }

  /* Reorder masking. */
  BKE_gpencil_layer_mask_sort(gpd, gpl);

  /* notifiers */
  DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);

  return OPERATOR_FINISHED;
}

void GPENCIL_OT_layer_mask_remove(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove Mask Layer";
  ot->idname = "GPENCIL_OT_layer_mask_remove";
  ot->description = "Remove Layer Mask";

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* callbacks */
  ot->exec = gp_layer_mask_remove_exec;
  ot->poll = gp_active_layer_poll;
}