aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/evas/filters/evas_filter_parser.c
blob: 90db0cbce8193e417edc8540d23694b1669c842b (plain) (blame)
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
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
#include "evas_filter_private.h"

#include <stdarg.h>

// Lua breaks API all the time
#ifdef ENABLE_LUA_OLD
// For 5.2 --> 5.1 compatibility
# define LUA_COMPAT_ALL
// For 5.3 --> 5.1 compatibility
# define LUA_COMPAT_5_1
#endif

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

#define FILTERS_LEGACY_COMPAT

#define EVAS_FILTER_MODE_GROW   (EVAS_FILTER_MODE_LAST+1)
#define EVAS_FILTER_MODE_BUFFER (EVAS_FILTER_MODE_LAST+2)

#define INSTR_PARAM_CHECK(a) do { if (!(a)) { \
   ERR("Argument %s can not be nil in %s!", #a, instr->name); return -1; } \
   } while (0)

/* Note on the documentation:
 * To keep it simple, I'm not using any fancy features, only <ul>/<li> lists
 * and @a, @b, @c flags from Doxygen.
 * Let's keep it that way.
 *
 * This is a REFERENCE documentation, not supposed to contain tons of examples,
 * but each filter command should have one simple copy and pasteable example.
 */

/**
  @page evasfiltersref Evas filters reference

  The Evas filters are a combination of filters used to apply specific effects
  to an @ref Evas_Object "Evas Object". For the moment, these effects are
  specific to the @ref Evas_Object_Text "Text Objects".

  The filters can be applied to an object using simple Lua scripts. A script
  will contain a series of buffer declarations and filter commands to apply
  to these buffers. The Lua programming language reference can be found
  <a href="http://www.lua.org/manual/5.1/manual.html">here</a>.

  Basically, when applying an effect to a @ref Evas_Object_Text "Text Object",
  an alpha-only @c input buffer is created, where the text is rendered, and
  an RGBA @c output buffer is created, where the text with effects shall be
  finally rendered.

  The script language being Lua, it respects the usual Lua syntax and concepts.
  As these are simple filters, the scripts should be kept as small and simple
  as possible.

  Note: Lua has been used since 1.10. The previous filters syntax is not
        garanteed to be compatible with 1.10 and newer versions.

  Here are the available commands:
  <ul>
    <li> @ref sec_syntax "Syntax" </li>
    <li> @ref sec_buffers "Buffer management" </li>
    <ul>
      <li> @ref sec_buffers_cspace "Colorspaces" </li>
      <li> @ref sec_buffers_auto "Automatic buffers" </li>
      <li> @ref sec_buffers_cmd "@c buffer command" </li>
    </ul>
    <li> @ref sec_commands "Commands" </li>
    <ul>
      <li> @ref sec_commands_blend "@c blend command"</li>
      <li> @ref sec_commands_blur "@c blur command"</li>
      <li> @ref sec_commands_grow "@c grow command"</li>
      <li> @ref sec_commands_curve "@c curve command"</li>
      <li> @ref sec_commands_fill "@c fill command"</li>
      <li> @ref sec_commands_mask "@c mask command"</li>
      <li> @ref sec_commands_bump "@c bump command"</li>
      <li> @ref sec_commands_displace "@c displace command"</li>
      <li> @ref sec_commands_transform "@c transform command"</li>
    </ul>
  </ul>

  All the examples in this page can (should) be directly used in
  @ref evas_obj_text_filter_program_set.

  Note that most of the text effects work better with larger font sizes (> 50px),
  and so do the examples in this page (embedded devices in mind).
 */

/**
  @page evasfiltersref
  @section sec_syntax Syntax

  Here is a simple example illustrating the syntax:

  @verbinclude filter_example_1.lua

  This example will display a cyan and dark blue glow surrounding the
  main text (its color depends on the object's theme).

  <center>
  @image html filter_example_1.png
  </center>

  The syntax is pretty simple and follows a small set of rules:
  <ul>
    <li>All dimensions are in pixels</li>
    <li>The commands will be executed in sequential order</li>
    <li>Most commands have default values</li>
    <li>A command argument can either be set by name, or sequentially omitting the name. So that:<br>
    @verbatim function (arg1, arg2, arg3) @endverbatim</li>
    <li>is equivalent to:<br>
    @verbatim function ({ arg1, arg2, arg2 }) @endverbatim</li>
    <li>or even (considering opt1, opt2 and opt3 are the first 3 arguments):<br>
    @verbatim function ({ opt1 = arg1, opt2 = arg2, opt3 = arg3 }) @endverbatim</li>
    <li>and since this is Lua, we can also write it as:<br>
    @verbatim function { arg1, opt3 = arg3, opt2 = arg2 } @endverbatim</li>
    <li>Boolean values are @c true/@c false but 1/0 and special string values are also accepted: 'yes'/'no', 'enabled'/'disabled'</li>
  </ul>

  <h3>Special keywords and their values</h3>

  Some options accept a certain set of values (like enums):
  <ul>
    <li>@c color</li>
    @anchor evasfilters_color
    <ul>
      <li>Colors can be referred to by strings or integers:</li>
      <li>An integer can refer to any RGB or ARGB values:
          @c 0xRRGGBB or @c 0xAARRGGBB. If alpha is zero, the color
          will be opaque (alpha = @c 0xFF), unless R=G=B=0 (invisible).
          These colors are <b>not</b> premultiplied.
      </li>
      <li>Hexademical values: @c '#RRGGBB', @c '#RRGGBBAA', @c '#RGB', @c '#RGBA'</li>
      <li>The following string values are also accepted:</li>
      <tt><ul>
        <li>'white' == '#FFFFFF'</li>
        <li>'black' == '#000000'</li>
        <li>'red' == '#FF0000'</li>
        <li>'green' == '#008000'</li>
        <li>'blue' == '#0000FF'</li>
        <li>'darkblue' == '#0000A0'</li>
        <li>'yellow' == '#FFFF00'</li>
        <li>'magenta' == '#FF00FF'</li>
        <li>'cyan' == '#00FFFF'</li>
        <li>'orange' == '#FFA500'</li>
        <li>'purple' == '#800080'</li>
        <li>'brown' == '#A52A2A'</li>
        <li>'maroon' == '#800000'</li>
        <li>'lime' == '#00FF00'</li>
        <li>'gray' == '#808080'</li>
        <li>'grey' == '#808080'</li>
        <li>'silver' == '#C0C0C0'</li>
        <li>'olive' == '#808000'</li>
        <li>'invisible', 'transparent' == '#0000' -- (alpha is zero)</li>
      </ul></tt>
    </ul>
    <li>@c fillmode</li>
    @anchor evasfilter_fillmode
    <tt><ul>
      <li>'none'</li>
      <li>'stretch_x'</li>
      <li>'stretch_y'</li>
      <li>'repeat_x'</li>
      <li>'repeat_y'</li>
      <li>'repeat_x_stretch_y', 'stretch_y_repeat_x'</li>
      <li>'repeat_y_stretch_x', 'stretch_x_repeat_y'</li>
      <li>'repeat', 'repeat_xy'</li>
      <li>'stretch', 'stretch_xy'</li>
    </ul></tt>
  </ul>
 */

/**
  @page evasfiltersref
  @section sec_buffers Buffer management

  The Evas filters subsystem is based on the concept of using various
  buffers as image layers and drawing or applying filters to these buffers.
  Think of it as how image drawing tools like The Gimp can combine multiple
  layers and apply operations on them.

  Most of the buffers are allocated automatically at runtime, depending on the
  various inputs and commands used (eg. 2-D blur will require a temporary
  intermediate buffer).

  @subsection sec_buffers_cspace Colorspaces and size

  The buffers' size will be automatically defined at runtime, based on the
  content of the input and the series of operations to apply (eg. blur adds
  some necessary margins).

  The buffers can be either ALPHA (1 color channel only) or RGBA (full color).
  Some operations might require specifically an ALPHA buffer, some others RGBA.

  Most buffers will have the same size, except those specified by an external
  source.


  @subsection sec_buffers_auto Automatic buffers

  The two most important buffers, input and output, are statically defined and
  always present when running a filter. input is an ALPHA buffer, containing
  the @ref Evas_Object_Text "Text Object"'s rendered text, and output is the
  final target on which to render as RGBA.

  Some operations, like 2-D blur might require temporary intermediate buffers,
  that will be allocated automatically. Those buffers are internal only and
  can't be used from the script.

  Finally, if a buffer is created using another Evas Object as source (see
  @ref sec_buffers_cmd "buffer" for more details), its pixel data will be filled
  by rendering the Evas Object into this buffer. This is how it will be
  possible to load external images, textures and even animations into a buffer.

  @since 1.9
 */

static struct
{
   const char *name;
   Evas_Filter_Fill_Mode value;
} fill_modes[] =
{
   { "none", EVAS_FILTER_FILL_MODE_NONE },
   { "stretch_x", EVAS_FILTER_FILL_MODE_STRETCH_X },
   { "stretch_y", EVAS_FILTER_FILL_MODE_STRETCH_Y },
   { "repeat_x", EVAS_FILTER_FILL_MODE_REPEAT_X },
   { "repeat_y", EVAS_FILTER_FILL_MODE_REPEAT_Y },
   { "repeat_x_stretch_y", EVAS_FILTER_FILL_MODE_REPEAT_X_STRETCH_Y },
   { "repeat_y_stretch_x", EVAS_FILTER_FILL_MODE_REPEAT_Y_STRETCH_X },
   { "stretch_y_repeat_x", EVAS_FILTER_FILL_MODE_REPEAT_X_STRETCH_Y }, // alias
   { "stretch_x_repeat_y", EVAS_FILTER_FILL_MODE_REPEAT_Y_STRETCH_X }, // alias
   { "repeat", EVAS_FILTER_FILL_MODE_REPEAT_XY }, // alias
   { "repeat_xy", EVAS_FILTER_FILL_MODE_REPEAT_XY },
   { "stretch", EVAS_FILTER_FILL_MODE_STRETCH_XY }, // alias
   { "stretch_xy", EVAS_FILTER_FILL_MODE_STRETCH_XY }
};

static const char *_lua_buffer_meta = "buffer";
static const char *_lua_color_meta = "color";
#define _lua_methods_table "__methods"
#define _lua_register_func "__register"
#define _lua_errfunc_name "__backtrace"

static Evas_Filter_Fill_Mode _fill_mode_get(Evas_Filter_Instruction *instr);
static Eina_Bool _lua_instruction_run(lua_State *L, Evas_Filter_Instruction *instr);
static int _lua_backtrace(lua_State *L);

typedef enum
{
   VT_NONE,
   VT_BOOL,
   VT_INT,
   VT_REAL,
   VT_STRING,
   VT_COLOR,
   VT_BUFFER,
   VT_SPECIAL
} Value_Type;

typedef struct _Buffer
{
   EINA_INLIST;
   Eina_Stringshare *name;
   Eina_Stringshare *proxy;
   int cid; // Transient value
   struct {
      int l, r, t, b; // Used for padding calculation. Can change over time.
   } pad;
   int w, h;
   Eina_Bool alpha : 1;
   Eina_Bool manual : 1; // created by "buffer" instruction
} Buffer;

typedef struct _Instruction_Param Instruction_Param;
struct _Instruction_Param
{
   EINA_INLIST;
   Eina_Stringshare *name;
   Value_Type type;
   union {
      Eina_Bool b;
      int i;
      double f;
      char *s;
      unsigned int c;
      Buffer *buf;
      struct {
         void *data;
         Eina_Bool (*func)(lua_State *L, int i, Evas_Filter_Program *, Evas_Filter_Instruction *, Instruction_Param *);
      } special;
   } value;
   Eina_Bool set : 1;
   Eina_Bool allow_seq : 1;
   Eina_Bool allow_any_string : 1;
};

struct _Evas_Filter_Instruction
{
   EINA_INLIST;
   Eina_Stringshare *name;
   int /*Evas_Filter_Mode*/ type;
   Eina_Inlist /* Instruction_Param */ *params;
   int return_count;
   Eina_Bool (* parse_run) (lua_State *L, Evas_Filter_Program *, Evas_Filter_Instruction *);
   struct
   {
      int (* update) (Evas_Filter_Program *, Evas_Filter_Instruction *, int *, int *, int *, int *);
   } pad;
   Eina_Bool valid : 1;
};

struct _Evas_Filter_Program_State
{
   struct {
      struct { int a, r, g, b; } outline;
      struct { int a, r, g, b; } shadow;
      struct { int a, r, g, b; } glow;
      struct { int a, r, g, b; } glow2;
   } text;
   struct {
      int a, r, g, b;
   } color;
   struct {
      const char *name;
      double value;
   } cur;
   struct {
      const char *name;
      double value;
   } next;
   int w, h;
   double scale;
   double pos;
};

struct _Evas_Filter_Program
{
   Eina_Stringshare *name; // Optional for now
   Eina_Hash /* const char * : Evas_Filter_Proxy_Binding */ *proxies;
   Eina_Inlist /* Evas_Filter_Instruction */ *instructions;
   Eina_Inlist /* Buffer */ *buffers;
   struct {
      // Note: padding can't be in the state as it's calculated after running Lua
      int l, r, t, b;
   } pad;
   Evas_Filter_Program_State state;
   Eina_Inlist *data; // Evas_Filter_Data_Binding
   lua_State *L;
   int       lua_func;
   int       last_bufid;
   Eina_Bool valid : 1;
   Eina_Bool padding_calc : 1; // Padding has been calculated
   Eina_Bool padding_set : 1; // Padding has been forced
   Eina_Bool changed : 1; // State (w,h) changed, needs re-run of Lua
   Eina_Bool input_alpha : 1;
};

/* Instructions */
static Evas_Filter_Instruction *
_instruction_new(const char *name)
{
   Evas_Filter_Instruction *instr;

   instr = calloc(1, sizeof(Evas_Filter_Instruction));
   instr->name = eina_stringshare_add(name);

   return instr;
}

static Eina_Bool
_instruction_param_addv(Evas_Filter_Instruction *instr, const char *name,
                        Value_Type format, Eina_Bool sequential, va_list args)
{
   Instruction_Param *param;
   char *s;

   param = calloc(1, sizeof(Instruction_Param));
   param->name = eina_stringshare_add(name);
   param->type = format;
   switch (format)
     {
      case VT_BOOL:
        param->value.b = (va_arg(args, unsigned int) != 0);
        break;
      case VT_INT:
        param->value.i = va_arg(args, int);
        break;
      case VT_REAL:
        param->value.f = va_arg(args, double);
        break;
      case VT_STRING:
        s = va_arg(args, char *);
        param->value.s = s ? strdup(s) : NULL;
        break;
      case VT_BUFFER:
        param->value.buf = va_arg(args, Buffer *);
        break;
      case VT_COLOR:
        param->value.c = va_arg(args, DATA32);
        break;
      case VT_SPECIAL:
        param->value.special.func = va_arg(args, typeof(param->value.special.func));
        param->value.special.data = va_arg(args, void *);
        break;
      case VT_NONE:
      default:
        free(param);
        return EINA_FALSE;
     }
   param->allow_seq = sequential;
   instr->params = eina_inlist_append(instr->params, EINA_INLIST_GET(param));

   return EINA_TRUE;
}

static Eina_Bool
_instruction_param_adda(Evas_Filter_Instruction *instr, const char *name,
                        Value_Type format, Eina_Bool sequential,
                        /* default value */ ...)
{
   Eina_Bool ok;
   va_list args;

   va_start(args, sequential);
   ok = _instruction_param_addv(instr, name, format, sequential, args);
   va_end(args);

   return ok;
}
#define _instruction_param_seq_add(a,b,c,...) _instruction_param_adda((a),(b),(c),1,__VA_ARGS__)
#define _instruction_param_name_add(a,b,c,...) _instruction_param_adda((a),(b),(c),0,__VA_ARGS__)

static void
_instruction_del(Evas_Filter_Instruction *instr)
{
   Instruction_Param *param;

   if (!instr) return;
   EINA_INLIST_FREE(instr->params, param)
     {
        if (param->type == VT_STRING)
          free(param->value.s);
        else if (param->type == VT_SPECIAL)
          free(param->value.special.data);
        eina_stringshare_del(param->name);
        instr->params = eina_inlist_remove(instr->params, EINA_INLIST_GET(param));
        free(param);
     }
   eina_stringshare_del(instr->name);
   free(instr);
}

static Instruction_Param *
_instruction_param_get(Evas_Filter_Instruction *instr, const char *name)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       return param;

   return NULL;
}

static int
_instruction_param_geti(Evas_Filter_Instruction *instr, const char *name,
                        Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.i;
       }

   if (isset) *isset = EINA_FALSE;
   return -1;
}

static double
_instruction_param_getd(Evas_Filter_Instruction *instr, const char *name,
                        Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.f;
       }

   if (isset) *isset = EINA_FALSE;
   return 0.0;
}

static DATA32
_instruction_param_getc(Evas_Filter_Instruction *instr, const char *name,
                        Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.c;
       }

   if (isset) *isset = EINA_FALSE;
   return 0;
}

static void *
_instruction_param_getspecial(Evas_Filter_Instruction *instr, const char *name,
                              Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.special.data;
       }

   if (isset) *isset = EINA_FALSE;
   return 0;
}

static const char *
_instruction_param_gets(Evas_Filter_Instruction *instr, const char *name,
                        Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.s;
       }

   if (isset) *isset = EINA_FALSE;
   return NULL;
}

static Buffer *
_instruction_param_getbuf(Evas_Filter_Instruction *instr, const char *name,
                          Eina_Bool *isset)
{
   Instruction_Param *param;

   EINA_INLIST_FOREACH(instr->params, param)
     if (!strcasecmp(name, param->name))
       {
          if (isset) *isset = param->set;
          return param->value.buf;
       }

   if (isset) *isset = EINA_FALSE;
   return NULL;
}

static Eina_Bool
_bool_parse(const char *str, Eina_Bool *b)
{
   if (!str || !*str) return EINA_FALSE;
   if (!strcmp(str, "1") ||
       !strcasecmp(str, "yes") ||
       !strcasecmp(str, "on") ||
       !strcasecmp(str, "enable") ||
       !strcasecmp(str, "enabled") ||
       !strcasecmp(str, "true"))
     {
        if (b) *b = EINA_TRUE;
        return EINA_TRUE;
     }
   else if (!strcmp(str, "0") ||
            !strcasecmp(str, "no") ||
            !strcasecmp(str, "off") ||
            !strcasecmp(str, "disable") ||
            !strcasecmp(str, "disabled") ||
            !strcasecmp(str, "false"))
     {
        if (b) *b = EINA_FALSE;
        return EINA_TRUE;
     }
   return EINA_FALSE;
}

#define PARSE_ABORT() do {} while (0)
//#define PARSE_ABORT() abort()

#define PARSE_CHECK(a) do { if (!(a)) { ERR("Parsing failed because '%s' is false at %s:%d", #a, __FUNCTION__, __LINE__); PARSE_ABORT(); goto end; } } while (0)

/* Buffers */
static Buffer *
_buffer_get(Evas_Filter_Program *pgm, const char *name)
{
   Buffer *buf;

   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, NULL);
   EINA_SAFETY_ON_NULL_RETURN_VAL(name, NULL);

   EINA_INLIST_FOREACH(pgm->buffers, buf)
     {
        if (!strcmp(buf->name, name))
          return buf;
        else if (buf->proxy && !strcmp(buf->proxy, name))
          return buf;
     }

   return NULL;
}

static Eina_Bool
_lua_buffer_push(lua_State *L, Buffer *buf)
{
   Buffer **ptr;

   lua_getglobal(L, buf->name);//+1
   ptr = lua_newuserdata(L, sizeof(Buffer *));//+1
   *ptr = buf;
   luaL_getmetatable(L, _lua_buffer_meta);//+1
   lua_setmetatable(L, -2);//-1
   lua_setglobal(L, buf->name);//-1
   lua_pop(L, 1);

   return EINA_TRUE;
}

// Begin of Lua metamethods and stuff

static int
_lua_buffer_tostring(lua_State *L)
{
   Buffer *buf, **pbuf;
   pbuf = lua_touserdata(L, 1);
   buf = pbuf ? *pbuf : NULL;
   if (!buf)
     lua_pushstring(L, "nil");
   else
     lua_pushfstring(L, "Buffer[#%d %dx%d %s%s%s]", buf->cid, buf->w, buf->h,
                     buf->alpha ? "alpha" : "rgba",
                     buf->proxy ? " src: " : "", buf->proxy ? buf->proxy : "");
   return 1;
}

static int
_lua_buffer_index(lua_State *L)
{
   Buffer *buf, **pbuf;
   const char *key;

   pbuf = lua_touserdata(L, 1);
   buf = pbuf ? *pbuf : NULL;
   if (!buf) return 0;

   key = lua_tostring(L, 2);
   if (!key) return 0;

   if (!strcmp(key, "w") || !strcmp(key, "width"))
     {
        lua_pushinteger(L, buf->w);
        return 1;
     }
   else if (!strcmp(key, "h") || !strcmp(key, "height"))
     {
        lua_pushinteger(L, buf->h);
        return 1;
     }
   else if (!strcmp(key, "type"))
     {
        lua_pushstring(L, buf->alpha ? "alpha" : "rgba");
        return 1;
     }
   else if (!strcmp(key, "alpha"))
     {
        lua_pushboolean(L, buf->alpha);
        return 1;
     }
   else if (!strcmp(key, "rgba"))
     {
        lua_pushboolean(L, !buf->alpha);
        return 1;
     }
   else if (!strcmp(key, "name"))
     {
        lua_pushstring(L, buf->name);
        return 1;
     }
   else if (!strcmp(key, "source"))
     {
        if (!buf->proxy) return 0;
        lua_pushstring(L, buf->proxy);
        return 1;
     }
   else
     return luaL_error(L, "Unknown index '%s' for a buffer", key);

   return 0;
}

// remove metatable from first argument if this is a __call metafunction
static inline int
_lua_implicit_metatable_drop(lua_State *L, const char *name)
{
   int ret = 0;
   if (lua_istable(L, 1) && lua_getmetatable(L, 1))
     {
        luaL_getmetatable(L, name);
        if (lua_rawequal(L, -1, -2))
          {
             lua_remove(L, 1);
             ret = 1;
          }
        lua_pop(L, 2);
     }
   return ret;
}

// End of all lua metamethods and stuff

static inline void
_buffer_name_format(char *name /*[64]*/, Evas_Filter_Program *pgm, const char *src)
{
   unsigned i;

   if (src)
     {
        // Cleanup name and avoid overriding existing globals
        snprintf(name, 64, "__source_%s", src);
        name[63] = '\0';
        for (i = 0; name[i]; i++)
          {
             if (!isdigit(name[i]) && !isalpha(name[i]))
               name[i] = '_';
          }
     }
   else
     {
        sprintf(name, "__buffer_%02d", ++pgm->last_bufid);
     }
}

static Buffer *
_buffer_add(Evas_Filter_Program *pgm, const char *name, Eina_Bool alpha,
            const char *src, Eina_Bool manual)
{
   Buffer *buf;

   buf = _buffer_get(pgm, name);
   if (buf)
     {
        if (!src)
          {
             ERR("Buffer '%s' already exists", name);
             return NULL;
          }
        else return buf;
     }

   if (alpha && src)
     {
        ERR("Can not set proxy buffer as alpha!");
        return NULL;
     }

   buf = calloc(1, sizeof(Buffer));
   if (!buf) return NULL;

   buf->manual = manual;
   if (!name)
     {
        char bufname[64];
        _buffer_name_format(bufname, pgm, src);
        buf->name = eina_stringshare_add(bufname);
     }
   else
     buf->name = eina_stringshare_add(name);
   buf->proxy = eina_stringshare_add(src);
   buf->alpha = alpha;
   buf->w = pgm->state.w;
   buf->h = pgm->state.h;

   pgm->buffers = eina_inlist_append(pgm->buffers, EINA_INLIST_GET(buf));
   _lua_buffer_push(pgm->L, buf);

   return buf;
}

static void
_buffer_del(Buffer *buf)
{
   if (!buf) return;
   eina_stringshare_del(buf->name);
   eina_stringshare_del(buf->proxy);
   free(buf);
}

static const int this_is_not_a_cat = 42;

static Evas_Filter_Program *
_lua_program_get(lua_State *L)
{
   Evas_Filter_Program *pgm;
   lua_pushlightuserdata(L, (void *) &this_is_not_a_cat);
   lua_gettable(L, LUA_REGISTRYINDEX);
   pgm = lua_touserdata(L, -1);
   lua_pop(L, 1);
   return pgm;
}

/* Instruction definitions */

/**
  @page evasfiltersref

  @subsection sec_buffers_cmd Buffer command

  Create a new buffer.

  @verbatim
  name1 = buffer()
  name2 = buffer("alpha")
  name3 = buffer("rgba")
  name4 = buffer({ type = "rgba" })
  name5 = buffer({ src = "partname" })
  @endverbatim

  @param type   Buffer type: @c rgba (default) or @c alpha
  @param src    An optional source. If set, @a type will be @c rgba.
  @return A new buffer. This value must not be saved to a variable.

  This creates a new named buffer, specify its colorspace or source. Possible options:
    @li @c alpha: Create an alpha-only buffer (1 channel, no color)
    @li @c rgba: Create an RGBA buffer (4 channels, full color)
    @li <tt>{src = "partname"}</tt>: Use another <tt>Evas Object</tt> as source for this
      buffer's pixels. The name can either be an Edje part name or the one
      specified in @c evas_obj_text_filter_source_set.

  If no option is given, an RGBA buffer will be created. All buffers have the
  same size, unless they are based on an external source.

  @see evas_obj_text_filter_source_set

  @since 1.10
 */

static Eina_Bool
_buffer_instruction_parse_run(lua_State *L,
                              Evas_Filter_Program *pgm,
                              Evas_Filter_Instruction *instr)
{
   char bufname[64] = {0};
   const char *src, *type;
   Eina_Bool alpha = EINA_FALSE;
   Buffer *buf;

   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);

   // FIXME: Buffers are still referred to internally by name.
   // This is pretty bad with the switch to Lua.

   type = _instruction_param_gets(instr, "type", NULL);
   src = _instruction_param_gets(instr, "src", NULL);

   alpha = (type && !strcasecmp(type, "alpha"));

   if (src)
     {
        if (alpha) WRN("Proxy buffers can't be alpha. Disarding alpha flag.");
        alpha = EINA_FALSE;
     }

   _buffer_name_format(bufname, pgm, src);
   buf = _buffer_add(pgm, bufname, alpha, src, EINA_TRUE);
   if (!buf) return EINA_FALSE;

   lua_getglobal(L, bufname);
   instr->return_count = 1;

   return EINA_TRUE;
}

static int
_lua_buffer_new(lua_State *L)
{
   // Reuse old "buffer" instruction code
   Evas_Filter_Program *pgm = _lua_program_get(L);
   Evas_Filter_Instruction *instr;

   instr = _instruction_new(_lua_buffer_meta);
   instr->type = EVAS_FILTER_MODE_BUFFER;
   instr->parse_run = _buffer_instruction_parse_run;
   _instruction_param_seq_add(instr, "type", VT_STRING, "rgba");
   _instruction_param_seq_add(instr, "src", VT_STRING, NULL);

   // drop "buffer" metatable
   _lua_implicit_metatable_drop(L, _lua_buffer_meta);

   if (!_lua_instruction_run(L, instr))
     {
        _instruction_del(instr);
        return luaL_error(L, "buffer instanciation failed");
     }
   else
     {
        pgm->instructions = eina_inlist_append(pgm->instructions, EINA_INLIST_GET(instr));
     }

   return instr->return_count;
}

static int
_blend_padding_update(Evas_Filter_Program *pgm EINA_UNUSED,
                      Evas_Filter_Instruction *instr,
                      int *padl, int *padr, int *padt, int *padb)
{
   Evas_Filter_Fill_Mode fillmode;
   Buffer *src, *dst;
   int ox, oy, l = 0, r = 0, t = 0, b = 0;

   ox = _instruction_param_geti(instr, "ox", NULL);
   oy = _instruction_param_geti(instr, "oy", NULL);

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   fillmode = _fill_mode_get(instr);
   if (fillmode & (EVAS_FILTER_FILL_MODE_STRETCH_X | EVAS_FILTER_FILL_MODE_REPEAT_X)) ox = 0;
   if (fillmode & (EVAS_FILTER_FILL_MODE_STRETCH_Y | EVAS_FILTER_FILL_MODE_REPEAT_Y)) oy = 0;

   if (ox < 0) l = (-ox) + src->pad.l;
   else r = ox + src->pad.r;

   if (oy < 0) t = (-oy) + src->pad.t;
   else b = oy + src->pad.b;

   if (dst->pad.l < l) dst->pad.l = l;
   if (dst->pad.r < r) dst->pad.r = r;
   if (dst->pad.t < t) dst->pad.t = t;
   if (dst->pad.b < b) dst->pad.b = b;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;

   return 0;
}

/**
  @page evasfiltersref
  @section sec_commands Filter commands
  @page evasfiltersref

  This section will present the various filter instructions, their syntax
  and their effects.
 */

/**
  @page evasfiltersref

  @subsection sec_commands_blend Blend

  Blend a buffer onto another. This is the simplest filter, as it just
  renders one buffer on another, potentially using a color, an
  offset and fill options.

  @verbatim
  blend ({ src = input, dst = output, ox = 0, oy = 0, color = 'white', fillmode = 'none' })
  @endverbatim

  @param src Source buffer to blend.
  @param dst Destination buffer for blending.
  @param ox  X offset. Moves the buffer to the right (ox > 0) or to the left (ox < 0) by N pixels.
  @param oy  Y offset. Moves the buffer to the bottom (oy > 0) or to the top (oy < 0) by N pixels.
  @param color A color to use for alpha to RGBA conversion. See @ref evasfilters_color "colors". <br>
                 If the input is an alpha buffer and the output is RGBA, this will
                 draw the buffer in this color. If both buffers are RGBA, this will
                 have no effect.
  @param fillmode Map the input onto the whole surface of the output by stretching or
                 repeating it. See @ref evasfilter_fillmode "fillmodes".

  If @a src is an alpha buffer and @a dst is an RGBA buffer, then the @a color option should be set.

  @verbinclude filter_blend.lua

  <center>
  @image html filter_blend.png
  </center>

  @since 1.9
 */

static Eina_Bool
_blend_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "blend"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_BLEND;
   instr->pad.update = _blend_padding_update;
   _instruction_param_seq_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_seq_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_seq_add(instr, "ox", VT_INT, 0);
   _instruction_param_seq_add(instr, "oy", VT_INT, 0);
   _instruction_param_name_add(instr, "color", VT_COLOR, 0xFFFFFFFF);
   _instruction_param_name_add(instr, "fillmode", VT_STRING, "none");

   return EINA_TRUE;
}

static int
_blur_padding_update(Evas_Filter_Program *pgm EINA_UNUSED,
                     Evas_Filter_Instruction *instr,
                     int *padl, int *padr, int *padt, int *padb)
{
   Eina_Bool yset = EINA_FALSE;
   int rx, ry, ox, oy, l, r, t, b, count;
   const char *typestr;
   Evas_Filter_Blur_Type type = EVAS_FILTER_BLUR_DEFAULT;
   Buffer *src, *dst;

   rx = _instruction_param_geti(instr, "rx", NULL);
   ry = _instruction_param_geti(instr, "ry", &yset);
   ox = _instruction_param_geti(instr, "ox", NULL);
   oy = _instruction_param_geti(instr, "oy", NULL);
   count = _instruction_param_geti(instr, "count", NULL);
   typestr = _instruction_param_gets(instr, "type", NULL);

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (typestr && !strcasecmp(typestr, "box"))
     type = EVAS_FILTER_BLUR_BOX;

   if (!yset) ry = rx;
   if (rx < 0) rx = 0;
   if (ry < 0) ry = 0;

   if (type == EVAS_FILTER_BLUR_BOX)
     {
        if (count < 1) count = 1;
        if (count > 6) count = 3;
     }
   else
     count = 1;

   rx *= count;
   ry *= count;

   l = rx + src->pad.l + ((ox < 0) ? (-ox) : 0);
   r = rx + src->pad.r + ((ox > 0) ? ox : 0);
   t = ry + src->pad.t + ((oy < 0) ? (-oy) : 0);
   b = ry + src->pad.b + ((oy > 0) ? oy : 0);

   if (dst->pad.l < l) dst->pad.l = l;
   if (dst->pad.r < r) dst->pad.r = r;
   if (dst->pad.t < t) dst->pad.t = t;
   if (dst->pad.b < b) dst->pad.b = b;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;

   return 0;
}

/**
  @page evasfiltersref

  @subsection sec_commands_blur Blur

  Apply blur effect on a buffer (box or gaussian).

  @verbatim
  blur ({ rx = 3, ry = nil, type = 'default', ox = 0, oy = 0, color = 'white', src = input, dst = output })
  @endverbatim

  @param rx    X radius. Specifies the radius of the blurring kernel (X direction).
  @param ry    Y radius. Specifies the radius of the blurring kernel (Y direction). If -1 is used, then @a ry = @a rx.
  @param type  Blur type to apply. One of @c default, @c box or @c gaussian. See below for details about @c default.
  @param ox    X offset. Moves the buffer to the right (@a ox > 0) or to the left (@a ox < 0) by N pixels.
  @param oy    Y offset. Moves the buffer to the bottom (@a oy > 0) or to the top (@a oy < 0) by N pixels.
  @param color A color to use for alpha to RGBA conversion. See @ref evasfilters_color "colors". <br>
                 If the input is an alpha buffer and the output is RGBA, this will
                 draw the buffer in this color.
  @param src   Source buffer to blur.
  @param dst   Destination buffer for blending.
  @param count Number of times to repeat the blur. Only valid with @c box blur. Valid range is: 1 to 6.

  The blur type @c default is <b>recommended in all situations</b> as it will select the smoothest
  and fastest operation possible depending on the kernel size. Instead of running a real
  gaussian blur, 2 or 3 box blurs may be chained to produce a similar effect at a much
  higher speed. The value @a count can be set to a value from 1 to 6 if blur type @c box
  has been specified.

  The speedups of @c box over @c gaussian are of orders of 4x to more than 20x faster.

  If @a src is an alpha buffer and @a dst is an RGBA buffer, then the color option should be set.

  @a ox and @a oy can be used to move the blurry output by a few pixels, like a drop shadow. Example:
  @verbinclude filter_blur.lua

  <center>
  @image html filter_blur.png
  </center>

  @since 1.9
 */

static Eina_Bool
_blur_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "blur"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_BLUR;
   instr->pad.update = _blur_padding_update;
   _instruction_param_seq_add(instr, "rx", VT_INT, 3);
   _instruction_param_seq_add(instr, "ry", VT_INT, -1);
   _instruction_param_seq_add(instr, "type", VT_STRING, "default");
   _instruction_param_seq_add(instr, "ox", VT_INT, 0);
   _instruction_param_seq_add(instr, "oy", VT_INT, 0);
   _instruction_param_name_add(instr, "color", VT_COLOR, 0xFFFFFFFF);
   _instruction_param_name_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_name_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_name_add(instr, "count", VT_INT, 0);

   return EINA_TRUE;
}

/**
  @page evasfiltersref

  @subsection sec_commands_bump Bump

  Apply a light effect (ambient light, specular reflection and shadows) based on a bump map.

  This can be used to give a relief effect on the object.

  @verbatim
  bump ({ map, azimuth = 135.0, elevation = 45.0, depth = 8.0, specular = 0.0,
          color = 'white', compensate = false, src = input, dst = output,
          black = 'black', white = 'white', fillmode = 'repeat' })
  @endverbatim

  @param map        An alpha buffer treated like a Z map for the light effect (bump map). Must be specified.
  @param azimuth    The angle between the light vector and the X axis in the XY plane (Z = 0). 135.0 means 45 degrees from the top-left. Counter-clockwise notation.
  @param elevation  The angle between the light vector and the Z axis. 45.0 means 45 degrees to the screen's plane. Ranges from 0 to 90 only.
  @param depth      The depth of the object in an arbitrary unit. More depth means the shadows will be stronger. Default is 8.0.
  @param specular   An arbitrary unit for the specular light effect. Default is 0.0, but a common value would be 40.0.
  @param color      The main color of the object if src is an alpha buffer. This represents the light's normal color. See @ref evasfilters_color "colors".
  @param compensate If set to true, compensate for whitening or darkening on flat surfaces. Default is false but it is recommended if specular light is wanted.
  @param src        Source buffer. This should be an alpha buffer.
  @param dst        Destination buffer. This should be an RGBA buffer (although alpha is supported). Must be of the same size as @a src.
  @param black      The shadows' color. Usually this will be black (@c #000).
  @param white      The specular light's color. Usually this will be white (@c #FFF).
  @param fillmode   This specifies how to handle @a map when its dimensions don't match those of @a src and @a dst. Default is to @c repeat. See @ref evasfilter_fillmode "fillmodes".

  @note As of 2014/02/11, the ALPHA to RGBA support is of much better quality than ALPHA only, but @b very slow. RGBA sources are not supported yet.

  Here is a full example of a very simple bevel effect:
  @verbinclude filter_bump.lua

  <center>
  @image html filter_bump.png
  </center>

  @since 1.9
 */

static Eina_Bool
_bump_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "bump"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_BUMP;
   _instruction_param_seq_add(instr, "map", VT_BUFFER, NULL);
   _instruction_param_seq_add(instr, "azimuth", VT_REAL, 135.0);
   _instruction_param_seq_add(instr, "elevation", VT_REAL, 45.0);
   _instruction_param_seq_add(instr, "depth", VT_REAL, 8.0);
   _instruction_param_seq_add(instr, "specular", VT_REAL, 0.0);
   _instruction_param_name_add(instr, "color", VT_COLOR, 0xFFFFFFFF);
   _instruction_param_name_add(instr, "compensate", VT_BOOL, EINA_FALSE);
   _instruction_param_name_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_name_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_name_add(instr, "black", VT_COLOR, 0xFF000000);
   _instruction_param_name_add(instr, "white", VT_COLOR, 0xFFFFFFFF);
   _instruction_param_name_add(instr, "fillmode", VT_STRING, "repeat");

   return EINA_TRUE;
}

static Eina_Bool
_lua_curve_points_func(lua_State *L, int i, Evas_Filter_Program *pgm EINA_UNUSED,
                       Evas_Filter_Instruction *instr, Instruction_Param *param)
{
   int values[256];
   char *token, *copy = NULL;
   const char *points_str;
   lua_Number n;
   int k;

   switch (lua_type(L, i))
     {
      case LUA_TTABLE:
        // FIXME: indices start from 0 here. Lua prefers starting with 1.
        for (k = 0; k < 256; k++)
          {
             lua_rawgeti(L, i, k);
             if (lua_isnil(L, -1))
               {
                  lua_pop(L, 1);
                  values[k] = -1;
               }
             else if (lua_isnumber(L, -1))
               {
                  n = lua_tonumber(L, -1);
                  if ((n < -1) || (n > 255))
                    {
                       WRN("Value out of range in argument '%s' of function '%s' (got %d, expected 0-255)",
                           param->name, instr->name, (int) n);
                       if (n < -1) n = 0;
                       if (n > 255) n = 255;
                    }
                  lua_pop(L, 1);
                  values[k] = (int) n;
               }
             else
               {
                  lua_pop(L, 1);
                  ERR("Invalid value type '%s' (expected number) in table for argument '%s' of function '%s'",
                      lua_typename(L, -1), param->name, instr->name);
                  return EINA_FALSE;
               }
          }
        break;

      case LUA_TSTRING:
        for (k = 0; k < 256; k++)
          values[k] = -1;
        points_str = lua_tostring(L, i);
        copy = strdup(points_str);
        if (!copy) return EINA_FALSE;
        token = strtok(copy, "-");
        if (!token)
          {
             ERR("Invalid string format for argument '%s' of function '%s'",
                 param->name, instr->name);
             free(copy);
             return EINA_FALSE;
          }
        while (token)
          {
             int x, y, r, minx = 0;
             r = sscanf(token, "%i:%i", &x, &y);
             if ((r != 2) || (x < minx) || (x >= 256))
               {
                  ERR("Invalid string format for argument '%s' of function '%s'",
                      param->name, instr->name);
                  free(copy);
                  return EINA_FALSE;
               }
             minx = x + 1;
             if ((y < -1) || (y > 255))
               {
                  WRN("Value out of range in argument '%s' of function '%s' (got %d, expected 0-255)",
                      param->name, instr->name, y);
                  if (y < -1) y = 0;
                  if (y > 255) y = 255;
               }
             values[x] = y;
             token = strtok(NULL, "-");
          }
        free(copy);
        break;

      case LUA_TFUNCTION:
        for (k = 0; k < 256; k++)
          {
             lua_getglobal(L, _lua_errfunc_name);
             lua_pushvalue(L, i);
             lua_pushinteger(L, k);
             if (!lua_pcall(L, 1, 1, -3))
               {
                  if (!lua_isnumber(L, -1))
                    {
                       ERR("Function returned an invalid type '%s' (expected number) "
                           "in argument '%s' of function '%s'",
                           lua_typename(L, -1), param->name, instr->name);
                       return EINA_FALSE;
                    }
                  n = lua_tonumber(L, -1);
                  if ((n < -1) || (n > 255))
                    {
                       WRN("Value out of range in argument '%s' of function '%s' (got %d, expected 0-255)",
                           param->name, instr->name, (int) n);
                       if (n < -1) n = 0;
                       if (n > 255) n = 255;
                    }
                  lua_pop(L, 2);
                  values[k] = (int) n;
               }
             else
               {
                  ERR("Failed to call function for argument '%s' of function '%s': %s",
                      param->name, instr->name, lua_tostring(L, -1));
                  return EINA_FALSE;
               }
          }
        break;

      default:
        ERR("Invalid type '%s' for argument '%s' of function '%s'",
            lua_typename(L, i), param->name, instr->name);
        return EINA_FALSE;
     }

   free(param->value.special.data);
   param->value.special.data = malloc(sizeof(values));
   if (!param->value.special.data) return EINA_FALSE;
   memcpy(param->value.special.data, values, sizeof(values));

   return EINA_TRUE;
}

/**
  @page evasfiltersref

  @subsection sec_commands_curve Curve

  Apply a color curve to a specific channel in a buffer.

  @verbatim
  curve ({ points, interpolation = 'linear', channel = 'rgb', src = input, dst = output })
  @endverbatim

  Modify the colors of a buffer. This applies a color curve y = f(x) to every pixel.

  @param points        The color curve to apply. See below for the syntax.
  @param interpolation How to interpolate between points. One of @c linear (y = ax + b) or @c none (y = Yk).
  @param channel       Target channel for the color modification. One of @c R(ed), @c G(reen), @c B(lue), @c A(lpha), @c RGB and @c RGBA. If @a src is an alpha buffer, this parameter will be ignored.
  @param src           Source buffer.
  @param dst           Destination buffer, must be of same dimensions and color space as @a src.

  The @a points argument contains a list of (X,Y) points in the range 0..255,
  describing a function <tt>f(x) = y</tt> to apply to all pixel values.

  The syntax of this @a points string is <tt>'x1:y1 - x2:y2 - x3:y3 - ... - xn:yn'</tt>
  (remember that all spaces are discarded).
  The points @c xn are in @a increasing order: <tt>x1 < x2 < x3 < ... < xn</tt>,
  and all values @c xn or @c yn are within the range 0..255.

  The identity curve is then described as <tt>'0:0-255:255'</tt>, with linear interpolation:
  @verbatim
  curve ({ points = '0:0 - 255:255', interpolation = linear })
  @endverbatim
  If ignored, y(x = 0) is 0 and y(x = 255) is 255.

  The following example will generate a 4px thick stroke around text letters:
  @verbinclude filter_curve.lua

  <center>
  @image html filter_curve.png
  </center>

  The curve command can be used to alter the output of a blur operation.

  @since 1.9
 */

static Eina_Bool
_curve_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   Instruction_Param *param;

   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "curve"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_CURVE;

   // TODO: Allow passing an array of 256 values as points.
   // It could be easily computed from another function in the script.
   _instruction_param_seq_add(instr, "points", VT_SPECIAL, _lua_curve_points_func, NULL);
   param = EINA_INLIST_CONTAINER_GET(eina_inlist_last(instr->params), Instruction_Param);
   param->allow_any_string = EINA_TRUE;

   _instruction_param_seq_add(instr, "interpolation", VT_STRING, "linear");
   _instruction_param_seq_add(instr, "channel", VT_STRING, "rgb");
   _instruction_param_name_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_name_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));

   return EINA_TRUE;
}

static int
_displace_padding_update(Evas_Filter_Program *pgm EINA_UNUSED,
                         Evas_Filter_Instruction *instr,
                         int *padl, int *padr, int *padt, int *padb)
{
   int intensity = 0;
   int l, r, t, b;
   Buffer *src, *dst;

   intensity = _instruction_param_geti(instr, "intensity", NULL);
   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   l = intensity + src->pad.l;
   r = intensity + src->pad.r;
   t = intensity + src->pad.t;
   b = intensity + src->pad.b;

   if (dst->pad.l < l) dst->pad.l = l;
   if (dst->pad.r < r) dst->pad.r = r;
   if (dst->pad.t < t) dst->pad.t = t;
   if (dst->pad.b < b) dst->pad.b = b;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;

   return 0;
}

/**
  @page evasfiltersref

  @subsection sec_commands_displace Displace

  Apply a displacement map on a buffer.

  @verbatim
  displace ({ map, intensity = 10, flags = 0, src = input, dst = output, fillmode = 'repeat' })
  @endverbatim

  @param map       An RGBA buffer containing a displacement map. See below for more details.
  @param intensity Maximum distance for the displacement.
                   This means 0 and 255 will represent a displacement of @c intensity pixels.
  @param flags     One of @c default, @c nearest, @c smooth, @c nearest_stretch or @c smooth_stretch.
                   This defines how pixels should be treated when going out of the @a src image bounds.
                   @c default is equivalent to @c smooth_stretch.
  @param src       Source buffer
  @param dst       Destination buffer. Must be of same color format and size as @a src.
  @param fillmode  Defines how to handle cases where the map has a different size from @a src and @a dst.
                   It should be a combination of @c stretch or @c repeat: @c none is not supported.
                   See @ref evasfilter_fillmode "fillmodes".

  <h3>Displacement map</h3>

  The @a map buffer is an RGBA image containing displacement and alpha values.
  Its size can be different from @c src or @c dst.

  The @b red channel is used for X displacements while the @b green channel is
  used for Y displacements. All subpixel values are in the range 0..255.
  A value of 128 means 0 displacement, lower means displace to the top/left
  and higher than 128 displace to the bottom/right.

  If <tt>signed char</tt> is used instead of <tt>unsigned char</tt> to represent
  these R and G values, then < 0 means displace top/left while > 0 means bottom/right.

  The @c alpha channel is used as an alpha multiplier for blending.

  Considering <tt>I(x, y)</tt> represents the pixel at position (x, y) in the
  image I, then here is how the displacement is applied to @a dst:
  @verbatim
  D = map (x, y)
  dst (x, y) = D.alpha * src (x + (D.red - 128) * intensity / 128, y + (D.green - 128) * intensity / 128) / 255 + (255 - D.alpha) * dst (x, y) / 255
  @endverbatim
  Of course, the real algorithm takes into account interpolation between pixels as well.

  @since 1.9
 */

static Eina_Bool
_displace_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "displace"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_DISPLACE;
   instr->pad.update = _displace_padding_update;
   _instruction_param_seq_add(instr, "map", VT_BUFFER, NULL);
   _instruction_param_seq_add(instr, "intensity", VT_INT, 10);
   _instruction_param_seq_add(instr, "flags", VT_STRING, "default");
   _instruction_param_name_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_name_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_name_add(instr, "fillmode", VT_STRING, "repeat");

   return EINA_TRUE;
}

/**
  @page evasfiltersref

  @subsection sec_commands_fill Fill

  Fill a buffer with a specific color.
  Not blending, can be used to clear a buffer.

  @verbatim
  fill ({ dst = output, color = 'transparent', l = 0, r = 0, t = 0, b = 0 })
  @endverbatim

  @param dst       Target buffer to fill with @a color.
  @param color     The color used to fill the buffer. All pixels within the fill area will be reset to this value. See @ref evasfilters_color "colors".
  @param l         Left padding: skip @a l pixels from the left border of the buffer
  @param r         Right padding: skip @a r pixels from the right border of the buffer
  @param t         Top padding: skip @a t pixels from the top border of the buffer
  @param b         Bottom padding: skip @a b pixels from the bottom border of the buffer

  This function should generally not be used, except for:
  <ul>
    <li>@a Testing an effect over a specific background color</li>
    <li>Clearing out a buffer with either white or transparent color</li>
  </ul>

  @since 1.9
 */

static Eina_Bool
_fill_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "fill"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_FILL;
   _instruction_param_seq_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_seq_add(instr, "color", VT_COLOR, 0x0);
   _instruction_param_seq_add(instr, "l", VT_INT, 0);
   _instruction_param_seq_add(instr, "r", VT_INT, 0);
   _instruction_param_seq_add(instr, "t", VT_INT, 0);
   _instruction_param_seq_add(instr, "b", VT_INT, 0);

   return EINA_TRUE;
}

static int
_grow_padding_update(Evas_Filter_Program *pgm EINA_UNUSED,
                     Evas_Filter_Instruction *instr,
                     int *padl, int *padr, int *padt, int *padb)
{
   Buffer *src, *dst;
   int l, r, t, b;
   int radius;

   radius = _instruction_param_geti(instr, "radius", NULL);
   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (radius < 0) radius = 0;

   l = radius + src->pad.l;
   r = radius + src->pad.r;
   t = radius + src->pad.t;
   b = radius + src->pad.b;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;

   if (dst->pad.l < l) dst->pad.l = l;
   if (dst->pad.r < r) dst->pad.r = r;
   if (dst->pad.t < t) dst->pad.t = t;
   if (dst->pad.b < b) dst->pad.b = b;

   return 0;
}

/**
  @page evasfiltersref

  @subsection sec_commands_grow Grow

  Grow or shrink a buffer's contents. This is not a zoom effect.

  @verbatim
  grow ({ radius, smooth = true, src = input, dst = output })
  @endverbatim

  @param radius  The radius of the grow kernel.
                 If a negative value is specified, the contents will shrink rather than grow.
  @param smooth  If @c true, use a smooth transitions between black and white (smooth blur and smoother curve).
  @param src     Source buffer to blur.
  @param dst     Destination buffer for blending. This must be of same size and colorspace as @a src.

  Example:
  @verbinclude filter_grow.lua

  This will first grow the letters in the buffer @c input by a few pixels, and
  then draw this buffer in black in the background.

  <center>
  @image html filter_grow.png
  </center>

  @since 1.9
 */

static Eina_Bool
_grow_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "grow"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_GROW;
   instr->pad.update = _grow_padding_update;
   _instruction_param_seq_add(instr, "radius", VT_INT, 0);
   _instruction_param_name_add(instr, "smooth", VT_BOOL, EINA_TRUE);
   _instruction_param_name_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_name_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));

   return EINA_TRUE;
}

/**
  @page evasfiltersref

  @subsection sec_commands_mask Mask

  Blend two input buffers into a third (target).

  @verbatim
  mask ({ mask, src = input, dst = output, color = 'white', fillmode = 'repeat' })
  @endverbatim

  @param mask     A mask or texture to blend with the input @a src into the target @a dst.
  @param src      Source buffer. This can also be thought of a mask if @a src is alpha and @a mask is RGBA.
  @param dst      Destination buffer for blending. This must be of same size and colorspace as @a src.
  @param color    A color to use for alpha to RGBA conversion for the blend operations. White means no change.
                  See @ref evasfilters_color "colors". This will have no effect on RGBA sources.
  @param fillmode Defines whether to stretch or repeat the @a mask if its size that of @src.
                  Should be set when masking with external textures. Default is repeat. See @ref evasfilter_fillmode "fillmodes".

  Note that @a src and @a mask are interchangeable, if they have the same dimensions.

  Example:
  @verbinclude filter_mask.lua

  This will create an inner shadow effect.

  <center>
  @image html filter_mask.png
  </center>

  @since 1.9
 */

static Eina_Bool
_mask_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "mask"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_MASK;
   _instruction_param_seq_add(instr, "mask", VT_BUFFER, NULL);
   _instruction_param_seq_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   _instruction_param_seq_add(instr, "dst", VT_BUFFER, _buffer_get(pgm, "output"));
   _instruction_param_name_add(instr, "color", VT_COLOR, 0xFFFFFFFF);
   _instruction_param_name_add(instr, "fillmode", VT_STRING, "repeat");

   return EINA_TRUE;
}

static int
_transform_padding_update(Evas_Filter_Program *pgm EINA_UNUSED,
                          Evas_Filter_Instruction *instr,
                          int *padl, int *padr, int *padt, int *padb)
{
   Buffer *dst;
   int ox, oy, l = 0, r = 0, t = 0, b = 0;

   //ox = _instruction_param_geti(instr, "ox", NULL);
   ox = 0;
   oy = _instruction_param_geti(instr, "oy", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(dst);

   if (ox < 0) l = (-ox) * 2;
   else r = ox * 2;

   if (oy < 0) t = (-oy) * 2;
   else b = oy * 2;

   if (dst->pad.l < l) dst->pad.l = l;
   if (dst->pad.r < r) dst->pad.r = r;
   if (dst->pad.t < t) dst->pad.t = t;
   if (dst->pad.b < b) dst->pad.b = b;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;

   return 0;
}

/**
  @page evasfiltersref

  @subsection sec_commands_transform Transform

  Apply a geometrical transformation to a buffer.

  Right now, only <b>vertical flip</b> is implemented and available.
  This operation does not blend and assumes the destination buffer is empty.

  @verbatim
  transform ({ dst, op = 'vflip', src = input, oy = 0 })
  @endverbatim

  @param dst      Destination buffer. Must be of the same colorspace as @a src. Must be specified.
  @param op       Must be @c 'vflip'. There is no other operation yet.
  @param src      Source buffer to transform.
  @param oy       Y offset.

  Example:
  @verbinclude filter_transform.lua

  This will create a mirrored text effect, for a font of 50px.

  <center>
  @image html filter_transform.png
  </center>

  @note Because of the meaning of @a oy, this effect probably needs to be
        customized for a single font size (FIXME).

  @since 1.9
 */

static Eina_Bool
_transform_instruction_prepare(Evas_Filter_Program *pgm, Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "transform"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_TRANSFORM;
   instr->pad.update = _transform_padding_update;
   _instruction_param_seq_add(instr, "dst", VT_BUFFER, NULL);
   _instruction_param_seq_add(instr, "op", VT_STRING, "vflip");
   _instruction_param_seq_add(instr, "src", VT_BUFFER, _buffer_get(pgm, "input"));
   //_instruction_param_name_add(instr, "ox", VT_INT, 0);
   _instruction_param_name_add(instr, "oy", VT_INT, 0);

   return EINA_TRUE;
}

static int
_padding_set_padding_update(Evas_Filter_Program *pgm,
                            Evas_Filter_Instruction *instr,
                            int *padl, int *padr, int *padt, int *padb)
{
   int l = 0, r = 0, t = 0, b = 0;
   Eina_Bool lset = EINA_FALSE;
   Eina_Bool rset = EINA_FALSE;
   Eina_Bool tset = EINA_FALSE;
   Eina_Bool bset = EINA_FALSE;

   l = _instruction_param_geti(instr, "l", &lset);
   r = _instruction_param_geti(instr, "r", &rset);
   t = _instruction_param_geti(instr, "t", &tset);
   b = _instruction_param_geti(instr, "b", &bset);

   if (!lset && !rset && !bset && !tset)
     INF("padding_set() called without specifying any of l,r,t,b resets to 0");

   if (l < 0 || r < 0 || t < 0 || b < 0)
     {
        WRN("invalid padding values in padding_set(%d, %d, %d, %d), resets to 0", l, r, t, b);
        l = r = t = b = 0;
     }

   if (!rset) r = l;
   if (!tset) t = r;
   if (!bset) b = t;

   if (padl) *padl = l;
   if (padr) *padr = r;
   if (padt) *padt = t;
   if (padb) *padb = b;
   pgm->padding_set = EINA_TRUE;

   return 0;
}

/**
  @page evasfiltersref

  @subsection sec_commands_padding_set Padding_Set

  Forcily set a specific padding for this filter.

  @verbatim
  padding_set ({ l, r = [l], t = [r], b = [t] })
  @endverbatim

  @param l        Padding on the left side in pixels.
  @param r        Padding on the right side in pixels. If unset, defaults to @a l.
  @param t        Padding on the top in pixels. If unset, defaults to @a r.
  @param b        Padding on the bottom in pixels. If unset, defaults to @a t.

  All values must be >= 0. When filtering 'filled' images, some values may be too high
  and would result in completely hiding the image.

  It is not possible to set only one of those without forcing the others as well.
  A common use case will be when changing a blur size during an animation, or
  when applying a mask that will hide most of the (blurred) text.

  Example (the @c fill command is used for illustration purposes):
  @verbinclude filter_padding.lua

  This will set the left, right, top and bottom paddings to their respective values,
  and some effects may look like they've been "clipped" out.

  <center>
  @image html filter_padding.png
  </center>

  @since 1.10
 */

static Eina_Bool
_padding_set_instruction_prepare(Evas_Filter_Program *pgm EINA_UNUSED,
                                 Evas_Filter_Instruction *instr)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(instr->name, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(!strcasecmp(instr->name, "padding_set"), EINA_FALSE);

   instr->type = EVAS_FILTER_MODE_PADDING_SET;
   instr->pad.update = _padding_set_padding_update;
   _instruction_param_seq_add(instr, "l", VT_INT, 0);
   _instruction_param_seq_add(instr, "r", VT_INT, 0);
   _instruction_param_seq_add(instr, "t", VT_INT, 0);
   _instruction_param_seq_add(instr, "b", VT_INT, 0);

   return EINA_TRUE;
}

/* Evas_Filter_Parser entry points */

#undef PARSE_CHECK
#define PARSE_CHECK(a) do { if (!(a)) { ERR("Parsing failed because '%s' is false at %s:%d", #a, __FUNCTION__, __LINE__); PARSE_ABORT(); goto end; } } while (0)

EAPI void
evas_filter_program_del(Evas_Filter_Program *pgm)
{
   Evas_Filter_Instruction *instr;
   Buffer *buf;

   if (!pgm) return;

   if (pgm->L)
     lua_close(pgm->L);

   EINA_INLIST_FREE(pgm->buffers, buf)
     {
        pgm->buffers = eina_inlist_remove(pgm->buffers, EINA_INLIST_GET(buf));
        _buffer_del(buf);
     }

   EINA_INLIST_FREE(pgm->instructions, instr)
     {
        pgm->instructions = eina_inlist_remove(pgm->instructions, EINA_INLIST_GET(instr));
        _instruction_del(instr);
     }

   eina_stringshare_del(pgm->name);
   free(pgm);
}

// [-1, +1, e] -- converts the top of the stack to a valid 'color' object
static Eina_Bool
_lua_convert_color(lua_State *L)
{
   int top = lua_gettop(L);
   lua_getglobal(L, _lua_errfunc_name); //+1
   lua_getglobal(L, _lua_color_meta); //+1 (mt)
   lua_getfield(L, -1, "__call"); //+1 (func)
   lua_pushvalue(L, -2); //+1 (mt)
   lua_pushvalue(L, top); //+1 (argument)
   if (lua_pcall(L, 2, 1, top + 1) != 0)
     {
        ERR("Failed to call metamethod __call: %s", lua_tostring(L, -1));
        lua_settop(L, top);
        return EINA_FALSE;
     }
   lua_insert(L, top);
   lua_settop(L, top);
   return EINA_TRUE;
}

static Eina_Bool
_lua_parameter_parse(Evas_Filter_Program *pgm, lua_State *L,
                     Evas_Filter_Instruction *instr,
                     Instruction_Param *param, int i)
{
   if (!param) return EINA_FALSE;
   if (param->set)
     {
        ERR("Parameter %s has already been set", param->name);
        return luaL_error(L, "Parameter %s has already been set", param->name);
     }

   if (i < 0)
     i = lua_gettop(L) + i + 1;

   switch (param->type)
     {
      case VT_BOOL:
        if (lua_type(L, i) == LUA_TSTRING)
          {
             Eina_Bool ok = EINA_FALSE;
             const char *str = lua_tostring(L, i);
             Eina_Bool val = _bool_parse(str, &ok);
             if (!ok)
               goto fail;
             param->value.b = val;
          }
        else if (lua_isboolean(L, i) || lua_isnumber(L, i))
          param->value.b = lua_toboolean(L, i);
        else
          goto fail;
        break;
      case VT_INT:
        if (!lua_isnumber(L, i))
          goto fail;
        param->value.i = lua_tointeger(L, i);
        break;
      case VT_REAL:
        if (!lua_isnumber(L, i))
          goto fail;
        param->value.f = lua_tonumber(L, i);
        break;
      case VT_STRING:
        if (lua_type(L, i) != LUA_TSTRING)
          goto fail;
        free(param->value.s);
        param->value.s = strdup(lua_tostring(L, i));
        break;
      case VT_COLOR:
        {
           // Auto convert values to a color() if they aren't one already
           int cid = 0, pop = 0, A, R, G, B;
           if (lua_istable(L, i))
             {
                luaL_getmetatable(L, _lua_color_meta);
                lua_getmetatable(L, i);
                if (!lua_isnil(L, -1) && lua_rawequal(L, -2, -1))
                  {
                     // this is a color already
                     cid = i;
                  }
                lua_pop(L, 2);
             }
           if (!cid)
             {
                lua_pushvalue(L, i); //+1 (arg)
                if (!_lua_convert_color(L)) //-1/+1
                  {
                     ERR("Failed to convert color: %s", lua_tostring(L, -1));
                     goto fail;
                  }
                cid = lua_gettop(L);
                pop = 1;
             }
           if (!lua_istable(L, cid))
             goto fail;
           lua_getfield(L, cid, "a");
           A = lua_tointeger(L, -1);
           lua_getfield(L, cid, "r");
           R = lua_tointeger(L, -1);
           lua_getfield(L, cid, "g");
           G = lua_tointeger(L, -1);
           lua_getfield(L, cid, "b");
           B = lua_tointeger(L, -1);
           lua_pop(L, pop + 4);
           evas_color_argb_premul(A, &R, &G, &B);
           param->value.c = ARGB_JOIN(A, R, G, B);
        }
        break;
      case VT_BUFFER:
        {
           if (lua_type(L, i) == LUA_TSTRING)
             {
                param->value.buf = _buffer_get(pgm, lua_tostring(L, i));
                if (!param->value.buf)
                  goto fail;
             }
           else
             {
                Buffer **pbuf;
                luaL_checkudata(L, i, _lua_buffer_meta);
                pbuf = lua_touserdata(L, i);
                param->value.buf = pbuf ? *pbuf : NULL;
             }
           break;
        }
      case VT_SPECIAL:
        if (!param->value.special.func ||
            !param->value.special.func(L, i, pgm, instr, param))
          goto fail;
        break;
      case VT_NONE:
      default:
        // This should not happen
        CRI("Invalid function declaration");
        goto fail;
     }

   if (i != lua_gettop(L))
     ERR("something is wrong");

   param->set = EINA_TRUE;
   return EINA_TRUE;

fail:
   ERR("Invalid value for parameter %s", param->name);
   return luaL_error(L, "Invalid value for parameter %s", param->name);
}

static Instruction_Param *
_parameter_get_by_id(Evas_Filter_Instruction *instr, int id)
{
   Instruction_Param *param;
   int i = 0;

   if (id < 0)
     return NULL;

   EINA_INLIST_FOREACH(instr->params, param)
     if (id == (i++))
       return param;

   return NULL;
}

static Eina_Bool
_lua_instruction_run(lua_State *L, Evas_Filter_Instruction *instr)
{
   const unsigned int argc = lua_gettop(L);
   Evas_Filter_Program *pgm = _lua_program_get(L);
   Instruction_Param *param;
   unsigned int i = 0;

   if (!instr) return EINA_FALSE;

   if (eina_inlist_count(instr->params) < argc)
     {
        ERR("Too many arguments passed to the instruction %s", instr->name);
        return EINA_FALSE;
     }

   if (lua_istable(L, 1))
     {
        if (argc > 1)
          {
             ERR("Too many arguments passed to the instruction %s (in table mode)", instr->name);
             return EINA_FALSE;
          }

        lua_pushnil(L);
        while (lua_next(L, 1))
          {
             if (!lua_isnumber(L, -2) && (lua_type(L, -2) == LUA_TSTRING))
               {
                  const char *name = lua_tostring(L, -2);
                  param = _instruction_param_get(instr, name);
                  if (!param)
                    {
                       ERR("Parameter %s does not exist", name);
                       return EINA_FALSE;
                    }
               }
             else if (lua_isnumber(L, -2))
               {
                  int idx = (int) lua_tonumber(L, -2);
                  param = _parameter_get_by_id(instr, idx - 1);
                  if (!param)
                    {
                       ERR("Too many parameters for the function %s", instr->name);
                       return EINA_FALSE;
                    }

                  if (!param->allow_seq)
                    {
                       ERR("The parameter %s must be referred to by name in function %s",
                           param->name, instr->name);
                       return EINA_FALSE;
                    }
               }
             else
               {
                  ERR("Invalid type for the parameter key in function %s", instr->name);
                  return EINA_FALSE;
               }

             if (!_lua_parameter_parse(pgm, L, instr, param, -1))
               return EINA_FALSE;
             lua_pop(L, 1);
          }
     }
   else
     {
        EINA_INLIST_FOREACH(instr->params, param)
          {
             if ((++i) > argc) break;
             if (!_lua_parameter_parse(pgm, L, instr, param, i))
               return EINA_FALSE;
          }
     }

   if (instr->parse_run)
     {
        if (!instr->parse_run(L, pgm, instr))
          {
             ERR("Failed to run instruction '%s'", instr->name);
             return EINA_FALSE;
          }
     }

   return EINA_TRUE;
}

static int
_lua_generic_function(lua_State *L, const char *name,
                      Eina_Bool (* prepare) (Evas_Filter_Program *pgm, Evas_Filter_Instruction *))
{
   Evas_Filter_Program *pgm = _lua_program_get(L);
   Evas_Filter_Instruction *instr;

   instr = _instruction_new(name);
   prepare(pgm, instr);

   if (!_lua_instruction_run(L, instr))
     {
        _instruction_del(instr);
        return luaL_error(L, "Instruction parsing failed");
     }
   else
     {
        pgm->instructions = eina_inlist_append(pgm->instructions, EINA_INLIST_GET(instr));
     }

   return instr->return_count;
}

static int
_lua_print(lua_State *L)
{
   Eina_Strbuf *s;
   int nargs = lua_gettop(L);
   int i;

   if (nargs < 1)
     {
        INF("(nothing)");
        return 0;
     }

   s = eina_strbuf_new();

   for (i = 1; i <= nargs; i++)
     {
        const char *str;
        lua_getglobal(L, _lua_errfunc_name);
        lua_getglobal(L, "tostring"); //+1
        lua_pushvalue(L, i); //+1
        lua_pcall(L, 1, 1, -3); //-2/+1
        str = lua_tostring(L, -1);
        eina_strbuf_append(s, str ? str : "(nil)");
        lua_pop(L, 2);
        eina_strbuf_append_char(s, ' ');
     }

   INF("%s", eina_strbuf_string_get(s));
   eina_strbuf_free(s);

   return 0;
}

#define LUA_GENERIC_FUNCTION(name) \
static int \
_lua_##name(lua_State *L) \
{ \
   return _lua_generic_function(L, #name, _##name##_instruction_prepare); \
}

#define PUSH_LUA_FUNCTION(name) \
   lua_pushcfunction(L, _lua_##name); \
   lua_setglobal(L, #name);

LUA_GENERIC_FUNCTION(blend)
LUA_GENERIC_FUNCTION(blur)
LUA_GENERIC_FUNCTION(bump)
LUA_GENERIC_FUNCTION(curve)
LUA_GENERIC_FUNCTION(displace)
LUA_GENERIC_FUNCTION(fill)
LUA_GENERIC_FUNCTION(grow)
LUA_GENERIC_FUNCTION(mask)
LUA_GENERIC_FUNCTION(padding_set)
LUA_GENERIC_FUNCTION(transform)

static const luaL_Reg _lua_buffer_metamethods[] = {
   { "__call", _lua_buffer_new },
   { "__tostring", _lua_buffer_tostring },
   { "__index", _lua_buffer_index },
   { NULL, NULL }
};

static char *_lua_color_code = NULL;

static inline void
_lua_import_path_get(char *path, size_t len, const char *name)
{
   const char *pfx = _evas_module_datadir_get();
   size_t r;

#ifdef FILTERS_DEBUG
   struct stat st;
   // This is a hack to fetch the most recent file from source
   if (stat(path, &st) == -1)
     {
        char *sep = evas_file_path_join("", "");
        char *src = strdup(__FILE__);
        char *slash = strrchr(src, *sep);
        if (slash)
          {
             *slash = '\0';
             if (*src == '/')
               r = snprintf(path, len - 1, "%s/lua/%s.lua", src, name);
             else // abs_srcdir is unknown here
                r =  snprintf(path, len - 1, "%s/src/%s/lua/%s.lua", PACKAGE_BUILD_DIR, src, name);
             if (r >= len) path[len - 1] = '\0';
          }
        free(sep);
        free(src);
        if (!stat(path, &st)) return;
     }
#endif

   r = snprintf(path, len - 1, "%s/filters/lua/%s.lua", pfx ? pfx : ".", name);
   if (r >= len) path[len - 1] = '\0';
}

static Eina_Bool
_lua_import_class(lua_State *L, const char *name, char **code)
{
   // Load code from file
   if (!*code)
     {
        char path[PATH_MAX];
        Eina_File *f;
        void *map;
        size_t sz;

        _lua_import_path_get(path, PATH_MAX, name);
        f = eina_file_open(path, EINA_FALSE);
        if (!f) return EINA_FALSE;
        sz = eina_file_size_get(f);
        *code = malloc(sz + 1);
        if (!*code) return EINA_FALSE;
        map = eina_file_map_all(f, EINA_FILE_SEQUENTIAL);
        if (!map) return EINA_FALSE;
        memcpy(*code, map, sz);
        (*code)[sz] = '\0';
        eina_file_map_free(f, map);
        eina_file_close(f);
     }

   if (!luaL_dostring(L, *code)) //+1
     {
        lua_getglobal(L, _lua_errfunc_name); //+1
        lua_pushliteral(L, _lua_register_func); //+1
        lua_rawget(L, -3); //-1/+1
        if (lua_isfunction(L, -1))
          {
             if (lua_pcall(L, 0, 0, -2) != 0) //-1
               {
                  ERR("Failed to register globals for '%s': %s", name, lua_tostring(L, -1));
                  lua_pop(L, 1);
               }
          }
        else lua_pop(L, 1);
        lua_pop(L, 1); // -1 (errfunc)
        lua_setglobal(L, name); //-1
     }
   else
     {
        ERR("Lua class '%s' could not be loaded: %s", name, lua_tostring(L, -1));
        return EINA_FALSE;
     }
   return EINA_TRUE;
}

static void
_filter_program_buffers_set(Evas_Filter_Program *pgm)
{
   // Standard buffers
   _buffer_add(pgm, "input", pgm->input_alpha, NULL, EINA_FALSE);
   _buffer_add(pgm, "output", EINA_FALSE, NULL, EINA_FALSE);

   // Register proxies
   if (pgm->proxies)
     {
        Eina_Iterator *it = eina_hash_iterator_tuple_new(pgm->proxies);
        Eina_Hash_Tuple *tup;

        EINA_ITERATOR_FOREACH(it, tup)
          {
             const char *source = tup->key;
             char name[64];
             Buffer *buf;

             _buffer_name_format(name, pgm, source);
             buf = _buffer_add(pgm, name, EINA_FALSE, source, EINA_FALSE);
             if (buf)
               {
                  Evas_Filter_Proxy_Binding *bind = tup->data;
                  Evas_Object_Protected_Data *obj;

                  obj = eo_data_scope_get(bind->eo_source, EVAS_OBJECT_CLASS);
                  buf->w = obj->cur->geometry.w;
                  buf->h = obj->cur->geometry.h;
               }
          }

        eina_iterator_free(it);
     }
}

static inline void
_lua_class_create(lua_State *L, const char *name,
                  const luaL_Reg *meta, const luaL_Reg *methods)
{
   luaL_newmetatable(L, name);
   luaL_register(L, NULL, meta);
   lua_pushliteral(L, "__metatable");
   lua_pushvalue(L, -2);
   lua_rawset(L, -3);
   if (methods)
     {
        lua_pushliteral(L, _lua_methods_table);
        lua_newtable(L);
        luaL_register(L, NULL, methods);
        lua_rawset(L, -3);
     }
   lua_pushvalue(L, -1);
   lua_setmetatable(L, -2);
   lua_setglobal(L, name);
}

#if LUA_VERSION_NUM < 502
// From LuaJIT/src/lib_init.c
// Prevent loading package, IO and OS libs (mini-sandbox)
static const luaL_Reg lj_lib_load[] = {
  { "",                 luaopen_base },
  //{ LUA_LOADLIBNAME,    luaopen_package },
  { LUA_TABLIBNAME,     luaopen_table },
  //{ LUA_IOLIBNAME,      luaopen_io },
  //{ LUA_OSLIBNAME,      luaopen_os },
  { LUA_STRLIBNAME,     luaopen_string },
  { LUA_MATHLIBNAME,    luaopen_math },
  { LUA_DBLIBNAME,      luaopen_debug },
#ifdef LUA_BITLIBNAME
  { LUA_BITLIBNAME,     luaopen_bit },
#endif
#ifdef LUA_JITLIBNAME
  { LUA_JITLIBNAME,     luaopen_jit },
#endif
  { NULL,               NULL }
};

static void
_luaL_openlibs(lua_State *L)
{
  const luaL_Reg *lib;
  for (lib = lj_lib_load; lib->func; lib++) {
    lua_pushcfunction(L, lib->func);
    lua_pushstring(L, lib->name);
    lua_call(L, 1, 0);
  }
}
#endif

static lua_State *
_lua_state_create(Evas_Filter_Program *pgm)
{
   lua_State *L;

   pgm->L = L = luaL_newstate();
   if (!L)
     {
        ERR("Could not create a new Lua state");
        return NULL;
     }

#if LUA_VERSION_NUM >= 502
   luaL_requiref(L, "",       luaopen_base, 1);
   luaL_requiref(L, "table",  luaopen_table, 1);
   luaL_requiref(L, "string", luaopen_string, 1);
   luaL_requiref(L, "math",   luaopen_math, 1);
   luaL_requiref(L, "debug",  luaopen_debug, 1);
#else
   _luaL_openlibs(L);
#endif
   lua_settop(L, 0);

   // Implement print
   lua_pushcfunction(L, _lua_print);
   lua_setglobal(L, "print");

   // Add backtrace error function
   lua_pushcfunction(L, _lua_backtrace);
   lua_setglobal(L, _lua_errfunc_name);

   // Store program
   lua_pushlightuserdata(L, (void *) &this_is_not_a_cat);
   lua_pushlightuserdata(L, pgm);
   lua_settable(L, LUA_REGISTRYINDEX);

   // Register functions
   PUSH_LUA_FUNCTION(blend)
   PUSH_LUA_FUNCTION(blur)
   PUSH_LUA_FUNCTION(bump)
   PUSH_LUA_FUNCTION(curve)
   PUSH_LUA_FUNCTION(displace)
   PUSH_LUA_FUNCTION(fill)
   PUSH_LUA_FUNCTION(grow)
   PUSH_LUA_FUNCTION(mask)
   PUSH_LUA_FUNCTION(padding_set)
   PUSH_LUA_FUNCTION(transform)

   for (unsigned k = 0; k < (sizeof(fill_modes) / sizeof(fill_modes[0])); k++)
     {
        if (strcmp("repeat", fill_modes[k].name))
          {
             lua_pushstring(L, fill_modes[k].name);
             lua_setglobal(L, fill_modes[k].name);
          }
     }

   lua_pushstring(L, "rgba");
   lua_setglobal(L, "rgba");

   lua_pushstring(L, "alpha");
   lua_setglobal(L, "alpha");

   static const struct { Eina_Bool b; const char *name; } booleans[] =
   {
      { EINA_TRUE, "on" },
      { EINA_TRUE, "yes" },
      { EINA_TRUE, "enable" },
      { EINA_TRUE, "enabled" },
      { EINA_FALSE, "off" },
      { EINA_FALSE, "no" },
      { EINA_FALSE, "disable" },
      { EINA_FALSE, "disabled" }
   };

   for (unsigned k = 0; k < (sizeof(booleans) / sizeof(booleans[0])); k++)
     {
        lua_pushnumber(L, booleans[k].b);
        lua_setglobal(L, booleans[k].name);
     }

   // Create buffer class based on userdata
   _lua_class_create(L, _lua_buffer_meta, _lua_buffer_metamethods, NULL);

   // Load color class
   if (!_lua_import_class(L, _lua_color_meta, &_lua_color_code))
     ERR("Could not load color class!");

   return L;
}

static int
_lua_backtrace(lua_State *L)
{
   if (!lua_isstring(L, 1))  /* 'message' not a string? */
     return 1;  /* keep it intact */
   ERR("Lua error: %s", lua_tolstring(L, 1, NULL));
   lua_getglobal(L, "debug");
   if (!lua_istable(L, -1))
     {
        lua_pop(L, 1);
        return 1;
     }
   lua_getfield(L, -1, "traceback");
   if (!lua_isfunction(L, -1))
     {
        lua_pop(L, 2);
        return 1;
     }
   lua_pushvalue(L, 1);  /* pass error message */
   lua_pushinteger(L, 2);  /* skip this function and traceback */
   lua_call(L, 2, 1);  /* call debug.traceback */
   return 1;
}

#ifdef FILTERS_LEGACY_COMPAT
// This function is here to avoid breaking the ABI too much.
// It should not stay here long, only until all client apps have changed the filters' code to Lua.
static char *
_legacy_strdup(const char *str)
{
   static Eina_Strbuf *dst = NULL;

   if (!dst) dst = eina_strbuf_new();
   for (const char *ptr = str; ptr && *ptr; ptr++)
     {
        if (ptr[0] == '/' && ptr[1] == '/')
          {
             // Comments
             ptr = strchr(ptr, '\n');
             if (!ptr) break;
          }
        else if (ptr[0] == '/' && ptr[1] == '*')
          {
             /* Comments */
             ptr = strstr(ptr + 2, "*/");
             if (!ptr) break;
             ptr++;
          }
        else if (*ptr == '(')
          eina_strbuf_append_char(dst, '{');
        else if (*ptr == ')')
          eina_strbuf_append_char(dst, '}');
        else if (*ptr == '#')
          {
             // Colors: #RGBA becomes "#RGBA"
             ptr++;
             eina_strbuf_append_length(dst, "\"#", 2);
             while (*ptr && *ptr != ',' && *ptr != ')')
               eina_strbuf_append_char(dst, *ptr++);
             eina_strbuf_append_char(dst, '"');
             ptr--;
          }
        else if (!strncasecmp("buffer", ptr, 6))
          {
             // Buffers: "buffer : a (rgba)" into "local a = buffer (rgba)"
             ptr = strchr(ptr, ':');
             if (!ptr) break;
             eina_strbuf_append(dst, "local ");
             for (ptr++; ptr && *ptr; ptr++)
               {
                  if (*ptr != '(')
                    eina_strbuf_append_char(dst, *ptr);
                  else
                    {
                       eina_strbuf_append(dst, " = buffer{");
                       break;
                    }
               }
          }
        else if (!strncasecmp("points", ptr, 6))
          {
             // Color curves: points = 0:0 - 255:255 becomes points = "0:0-255:255"
             ptr = strchr(ptr, '=');
             if (!ptr) break;
             ptr++;
             eina_strbuf_append(dst, "points = \"");
             while (*ptr && *ptr != ',' && *ptr != ')')
               {
                  if (isspace(*ptr))
                    {
                       ptr++;
                       continue;
                    }
                  eina_strbuf_append_char(dst, *ptr++);
               }
             eina_strbuf_append_char(dst, '"');
             ptr--;
          }
        else if (!strncasecmp("curve", ptr, 5))
          {
             // Color curves: curve (0:0 - 255:255, becomes curve { points = "0:0-255:255",
             const char *end = strchr(ptr, ')');
             const char *points = strstr(ptr, "points");
             if (!end || (points > end)) break;
             if (!points)
               {
                  while (*ptr != '(') ptr++;
                  ptr++;
                  eina_strbuf_append(dst, "curve { points = \"");
                  while (*ptr && *ptr != ',' && *ptr != ')')
                    {
                       if (isspace(*ptr))
                         {
                            ptr++;
                            continue;
                         }
                       eina_strbuf_append_char(dst, *ptr++);
                    }
                  eina_strbuf_append_char(dst, '"');
                  ptr--;
               }
             else
               {
                  eina_strbuf_append_length(dst, "curve", 5);
                  ptr += 4;
               }
          }
        else if (!strncasecmp("repeat", ptr, 6))
          {
             // repeat is a Lua keyword, replace all occurences by "repeat_xy"
             if (ptr[-1] != '_' && ptr[6] != '_')
               {
                  eina_strbuf_append(dst, "\"repeat_xy\"");
                  ptr += 5;
               }
             else
               eina_strbuf_append_char(dst, *ptr);
          }
        else
          eina_strbuf_append_char(dst, *ptr);
     }

   return eina_strbuf_string_steal(dst);
}
#endif

static Eina_Bool
_filter_program_state_set(Evas_Filter_Program *pgm)
{
   lua_State *L = pgm->L;

   // TODO:
   // text properties: colors, font size, ascent/descent, style (enum)

   /* State is defined as follow:
    * state = {
    *   text = {
    *     outline = COL
    *     shadow = COL
    *     glow = COL
    *     glow2 = COL
    *   }
    *   color = COL
    * }
    */

#define JOINC(k) (double) ({ DATA32 d; int A = pgm->state.k.a, R = pgm->state.k.r, G = pgm->state.k.g, B = pgm->state.k.b; \
   evas_color_argb_unpremul(A, &R, &G, &B); d = ARGB_JOIN(A, R, G, B); d; })
#define SETFIELD(name, val) do { lua_pushnumber(L, val); lua_setfield(L, -2, name); } while(0)
#define SETCOLOR(name, val) do { lua_pushnumber(L, val); _lua_convert_color(L); lua_setfield(L, -2, name); } while(0)

   // TODO: Mark program as dependent on some values so we can improve
   // the changed flag (ie. re-run the filter only when required)
   // eg. edje state_val changed but it is not used by the filter --> no redraw
   // --> this needs a metatable with __index

   lua_newtable(L); // "state"
   {
      SETCOLOR("color", JOINC(color));
      SETFIELD("scale", pgm->state.scale);
      SETFIELD("pos", pgm->state.pos);
      lua_newtable(L); // "cur"
      {
         SETFIELD("value", pgm->state.cur.value);
         lua_pushstring(L, pgm->state.cur.name);
         lua_setfield(L, -2, "name");
         lua_setfield(L, -2, "cur");
      }
      if (pgm->state.next.name)
        {
           lua_newtable(L); // "next"
           {
              SETFIELD("value", pgm->state.next.value);
              lua_pushstring(L, pgm->state.next.name);
              lua_setfield(L, -2, "name");
           }
           lua_setfield(L, -2, "next");
        }
      lua_newtable(L); // "text"
      {
         SETCOLOR("outline", JOINC(text.outline));
         SETCOLOR("shadow",  JOINC(text.shadow));
         SETCOLOR("glow",    JOINC(text.glow));
         SETCOLOR("glow2",   JOINC(text.glow2));
         lua_setfield(L, -2, "text");
      }
   }
   lua_setglobal(L, "state");

   /* now push all extra data */
   if (pgm->data)
     {
        Evas_Filter_Data_Binding *db;
        EINA_INLIST_FOREACH(pgm->data, db)
          {
             if (db->value)
               {
                  if (db->execute)
                    {
                       if (luaL_dostring(L, db->value) != 0)
                         {
                            ERR("Failed to run value: %s", lua_tostring(L, -1));
                            return EINA_FALSE;
                         }
                    }
                  else
                    {
                       lua_pushstring(L, db->value);
                       lua_setglobal(L, db->name);
                    }
               }
             else
               {
                  lua_pushnil(L);
                  lua_setglobal(L, db->name);
               }
          }
     }

   return EINA_TRUE;

#undef JOINC
#undef SETFIELD
#undef SETCOLOR
}

static Eina_Bool
_filter_program_reset(Evas_Filter_Program *pgm)
{
   Evas_Filter_Instruction *instr;
   lua_State *L = pgm->L;
   Eina_Inlist *il;
   Buffer *buf;

   // Clear out commands
   EINA_INLIST_FREE(pgm->instructions, instr)
     {
        pgm->instructions = eina_inlist_remove(pgm->instructions, EINA_INLIST_GET(instr));
        _instruction_del(instr);
     }

   // Clear out buffers
   EINA_INLIST_FOREACH_SAFE(pgm->buffers, il, buf)
     {
        lua_pushnil(L);
        lua_setglobal(L, buf->name);
        pgm->buffers = eina_inlist_remove(pgm->buffers, EINA_INLIST_GET(buf));
        _buffer_del(buf);
     }

   // Re-create buffers
   _filter_program_buffers_set(pgm);

   // Reset state table
   return _filter_program_state_set(pgm);
}

/** Parse a style program */

EAPI Eina_Bool
evas_filter_program_parse(Evas_Filter_Program *pgm, const char *str)
{
   lua_State *L;
   Eina_Bool ok;

   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(str, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(*str != 0, EINA_FALSE);

   L = _lua_state_create(pgm);
   if (!L) return EINA_FALSE;

   ok = !luaL_loadstring(L, str);
   if (!ok)
     {
        ERR("Failed to load Lua program: %s", lua_tostring(L, -1));
     }

#ifdef FILTERS_LEGACY_COMPAT
   if (!ok)
     {
        char *code = _legacy_strdup(str);
        DBG("Fallback to transformed legacy code:\n%s", code);
        ok = !luaL_loadstring(L, code);
        free(code);
     }
#endif

   if (ok)
     {
        pgm->lua_func = luaL_ref(L, LUA_REGISTRYINDEX);
        ok =_filter_program_reset(pgm);
        if (ok)
          {
             lua_getglobal(L, _lua_errfunc_name);
             lua_rawgeti(L, LUA_REGISTRYINDEX, pgm->lua_func);
             ok = !lua_pcall(L, 0, LUA_MULTRET, -2);
          }
     }

   if (!ok)
     {
        const char *msg = lua_tostring(L, -1);
        ERR("Lua parsing failed: %s", msg);
        lua_close(L);
        pgm->L = NULL;
     }
   else if (!pgm->instructions)
     {
        ERR("No instructions found in Lua script");
        lua_close(L);
        ok = EINA_FALSE;
        pgm->L = NULL;
     }
   pgm->valid = ok;
   pgm->padding_calc = EINA_FALSE;
   pgm->changed = EINA_FALSE;

   return ok;
}

/** Run a program, must be already loaded */

static void
_buffers_update(Evas_Filter_Context *ctx, Evas_Filter_Program *pgm)
{
   Evas_Object_Protected_Data *source;
   Evas_Filter_Proxy_Binding *pb;
   Evas_Filter_Buffer *fb;
   Buffer *buf;

   EINA_INLIST_FOREACH(pgm->buffers, buf)
     {
        if (buf->proxy)
          {
             pb = eina_hash_find(pgm->proxies, buf->proxy);
             if (!pb) continue;

             buf->cid = evas_filter_buffer_empty_new(ctx, buf->alpha);
             fb = _filter_buffer_get(ctx, buf->cid);
             fb->proxy = pb->eo_proxy;
             fb->source = pb->eo_source;
             fb->source_name = eina_stringshare_ref(pb->name);
             fb->ctx->has_proxies = EINA_TRUE;

             source = eo_data_scope_get(fb->source, EVAS_OBJECT_CLASS);
             if ((source->cur->geometry.w != buf->w) ||
                 (source->cur->geometry.h != buf->h))
               pgm->changed = EINA_TRUE;
             buf->w = fb->w = source->cur->geometry.w;
             buf->h = fb->h = source->cur->geometry.h;
          }
        else
          {
             if ((buf->w != pgm->state.w) || (buf->h != pgm->state.h))
               pgm->changed = EINA_TRUE;
             buf->cid = evas_filter_buffer_empty_new(ctx, buf->alpha);
             fb = _filter_buffer_get(ctx, buf->cid);
             fb->w = buf->w = pgm->state.w;
             fb->h = buf->h = pgm->state.h;
          }
     }
}

/** Evaluate required padding to correctly apply an effect */

EAPI Eina_Bool
evas_filter_program_padding_get(Evas_Filter_Program *pgm,
                                int *l, int *r, int *t, int *b)
{
   Evas_Filter_Instruction *instr;
   int pl = 0, pr = 0, pt = 0, pb = 0;
   int maxl = 0, maxr = 0, maxt = 0, maxb = 0;
   Buffer *buf;

   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, EINA_FALSE);

   if (pgm->padding_calc || pgm->padding_set)
     {
        if (l) *l = pgm->pad.l;
        if (r) *r = pgm->pad.r;
        if (t) *t = pgm->pad.t;
        if (b) *b = pgm->pad.b;
        return EINA_TRUE;
     }

   // Reset all paddings
   EINA_INLIST_FOREACH(pgm->buffers, buf)
     buf->pad.l = buf->pad.r = buf->pad.t = buf->pad.b = 0;

   // Accumulate paddings
   EINA_INLIST_FOREACH(pgm->instructions, instr)
     {
        if (instr->type == EVAS_FILTER_MODE_PADDING_SET)
          {
             instr->pad.update(pgm, instr, &maxl, &maxr, &maxt, &maxb);
             break;
          }
        else if (instr->pad.update)
          {
             instr->pad.update(pgm, instr, &pl, &pr, &pt, &pb);
             if (pl > maxl) maxl = pl;
             if (pr > maxr) maxr = pr;
             if (pt > maxt) maxt = pt;
             if (pb > maxb) maxb = pb;
          }
     }

   pgm->pad.l = maxl;
   pgm->pad.r = maxr;
   pgm->pad.t = maxt;
   pgm->pad.b = maxb;
   pgm->padding_calc = EINA_TRUE;

   if (l) *l = maxl;
   if (r) *r = maxr;
   if (t) *t = maxt;
   if (b) *b = maxb;

   return EINA_TRUE;
}

/** Create an empty filter program for style parsing */

EAPI Evas_Filter_Program *
evas_filter_program_new(const char *name, Eina_Bool input_alpha)
{
   Evas_Filter_Program *pgm;

   pgm = calloc(1, sizeof(Evas_Filter_Program));
   if (!pgm) return NULL;
   pgm->name = eina_stringshare_add(name);
   pgm->input_alpha = input_alpha;
   pgm->state.color.r = 255;
   pgm->state.color.g = 255;
   pgm->state.color.b = 255;
   pgm->state.color.a = 255;
   pgm->state.scale = 1.0;

   return pgm;
}

EAPI Eina_Bool
evas_filter_program_state_set(Evas_Filter_Program *pgm, Evas_Object *eo_obj,
                              Evas_Object_Protected_Data *obj,
                              const char *cur_state, double cur_val,
                              const char *next_state, double next_val,
                              double pos)
{
   Evas_Filter_Program_State old_state;

   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, EINA_FALSE);

   memcpy(&old_state, &pgm->state, sizeof(Evas_Filter_Program_State));

   pgm->state.w = obj->cur->geometry.w;
   pgm->state.h = obj->cur->geometry.h;
   pgm->state.scale = obj->cur->scale;
   pgm->state.pos = pos;
   pgm->state.cur.name = cur_state;
   pgm->state.cur.value = cur_val;
   pgm->state.next.name = next_state;
   pgm->state.next.value = next_val;

   eo_do(eo_obj,
         efl_gfx_color_get(eo_obj, &pgm->state.color.r,
                           &pgm->state.color.g,
                           &pgm->state.color.b,
                           &pgm->state.color.a));

   if (eo_isa(eo_obj, EVAS_TEXT_CLASS))
     {
        eo_do(eo_obj,
              evas_obj_text_shadow_color_get(eo_obj, &pgm->state.text.shadow.r,
                                             &pgm->state.text.shadow.g,
                                             &pgm->state.text.shadow.b,
                                             &pgm->state.text.shadow.a),
              evas_obj_text_outline_color_get(eo_obj, &pgm->state.text.outline.r,
                                              &pgm->state.text.outline.g,
                                              &pgm->state.text.outline.b,
                                              &pgm->state.text.outline.a),
              evas_obj_text_glow_color_get(eo_obj, &pgm->state.text.glow.r,
                                           &pgm->state.text.glow.g,
                                           &pgm->state.text.glow.b,
                                           &pgm->state.text.glow.a),
              evas_obj_text_glow2_color_get(eo_obj, &pgm->state.text.glow2.r,
                                            &pgm->state.text.glow2.g,
                                            &pgm->state.text.glow2.b,
                                            &pgm->state.text.glow2.a));
     }

   if (memcmp(&old_state, &pgm->state, sizeof(Evas_Filter_Program_State)) != 0)
     pgm->changed = EINA_TRUE;

   if (pgm->changed)
     pgm->padding_calc = EINA_FALSE;

   return pgm->changed;
}

/** Bind objects for proxy rendering */
EAPI void
evas_filter_program_source_set_all(Evas_Filter_Program *pgm,
                                   Eina_Hash *proxies)
{
   if (!pgm) return;
   pgm->proxies = proxies;
}

void
evas_filter_program_data_set_all(Evas_Filter_Program *pgm, Eina_Inlist *data)
{
   if (!pgm) return;
   pgm->data = data;
}

/** Glue with Evas' filters */

#define CA(color) ((color >> 24) & 0xFF)
#define CR(color) ((color >> 16) & 0xFF)
#define CG(color) ((color >> 8) & 0xFF)
#define CB(color) ((color) & 0xFF)

#define SETCOLOR(c) do { ENFN->context_color_get(ENDT, dc, &R, &G, &B, &A); \
   ENFN->context_color_set(ENDT, dc, CR(c), CG(c), CB(c), CA(c)); } while (0)
#define RESETCOLOR() do { ENFN->context_color_set(ENDT, dc, R, G, B, A); } while (0)

#define SETCLIP(l, r, t, b) int _l = 0, _r = 0, _t = 0, _b = 0; \
   do { ENFN->context_clip_get(ENDT, dc, &_l, &_r, &_t, &_b); \
   ENFN->context_clip_set(ENDT, dc, l, r, t, b); } while (0)
#define RESETCLIP() do { ENFN->context_clip_set(ENDT, dc, _l, _r, _t, _b); } while (0)

static Evas_Filter_Fill_Mode
_fill_mode_get(Evas_Filter_Instruction *instr)
{
   const char *fill;
   unsigned k;

   if (!instr) return EVAS_FILTER_FILL_MODE_NONE;
   fill = _instruction_param_gets(instr, "fillmode", NULL);
   if (!fill) return EVAS_FILTER_FILL_MODE_NONE;

   for (k = 0; k < sizeof(fill_modes) / sizeof(fill_modes[0]); k++)
     {
        if (!strcasecmp(fill_modes[k].name, fill))
          return fill_modes[k].value;
     }

   return EVAS_FILTER_FILL_MODE_NONE;
}

static int
_instr2cmd_blend(Evas_Filter_Context *ctx,
                 Evas_Filter_Instruction *instr, void *dc)
{
   Eina_Bool isset = EINA_FALSE;
   DATA32 color;
   Buffer *src, *dst;
   Evas_Filter_Fill_Mode fillmode;
   int cmdid, ox, oy, A, R, G, B;

   ox = _instruction_param_geti(instr, "ox", NULL);
   oy = _instruction_param_geti(instr, "oy", NULL);
   color = _instruction_param_getc(instr, "color", &isset);
   fillmode = _fill_mode_get(instr);
   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (isset) SETCOLOR(color);
   cmdid = evas_filter_command_blend_add(ctx, dc, src->cid, dst->cid, ox, oy,
                                         fillmode);
   if (isset) RESETCOLOR();
   if (cmdid < 0) return cmdid;

   return cmdid;
}

static int
_instr2cmd_blur(Evas_Filter_Context *ctx,
                Evas_Filter_Instruction *instr, void *dc)
{
   Eina_Bool colorset = EINA_FALSE, yset = EINA_FALSE, cntset = EINA_FALSE;
   Evas_Filter_Blur_Type type = EVAS_FILTER_BLUR_DEFAULT;
   const char *typestr;
   DATA32 color;
   Buffer *src, *dst;
   int cmdid, ox, oy, rx, ry, A, R, G, B, count;

   ox = _instruction_param_geti(instr, "ox", NULL);
   oy = _instruction_param_geti(instr, "oy", NULL);
   rx = _instruction_param_geti(instr, "rx", NULL);
   ry = _instruction_param_geti(instr, "ry", &yset);
   color = _instruction_param_getc(instr, "color", &colorset);
   typestr = _instruction_param_gets(instr, "type", NULL);
   count = _instruction_param_geti(instr, "count", &cntset);
   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (typestr)
     {
        if (!strcasecmp(typestr, "gaussian"))
          type = EVAS_FILTER_BLUR_GAUSSIAN;
        else if (!strcasecmp(typestr, "box"))
          type = EVAS_FILTER_BLUR_BOX;
        else if (!strcasecmp(typestr, "default"))
          type = EVAS_FILTER_BLUR_DEFAULT;
        else
          ERR("Unknown blur type '%s'. Using default blur.", typestr);
     }

   if (type == EVAS_FILTER_BLUR_BOX)
     {
        if (count < 1) count = 1;
        if (count > 6)
          {
             WRN("Box blur count should be below 6, defaults to 3.");
             count = 3;
          }
     }
   else
     {
        if (cntset) WRN("Blur count can only be used with BOX blur.");
        count = 1;
     }

   if (!yset) ry = rx;
   if (colorset) SETCOLOR(color);
   cmdid = evas_filter_command_blur_add(ctx, dc, src->cid, dst->cid, type,
                                        rx, ry, ox, oy, count);
   if (colorset) RESETCOLOR();

   return cmdid;
}

static int
_instr2cmd_bump(Evas_Filter_Context *ctx,
                Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Bump_Flags flags = EVAS_FILTER_BUMP_NORMAL;
   Evas_Filter_Fill_Mode fillmode;
   DATA32 color, black, white;
   Buffer *src, *dst, *map;
   double azimuth, elevation, depth, specular;
   int cmdid, compensate;

   color = _instruction_param_getc(instr, "color", NULL);
   white = _instruction_param_getc(instr, "white", NULL);
   black = _instruction_param_getc(instr, "black", NULL);
   azimuth = _instruction_param_getd(instr, "azimuth", NULL);
   elevation = _instruction_param_getd(instr, "elevation", NULL);
   depth = _instruction_param_getd(instr, "depth", NULL);
   specular = _instruction_param_getd(instr, "specular", NULL);
   compensate = _instruction_param_geti(instr, "compensate", NULL);
   fillmode = _fill_mode_get(instr);
   if (compensate) flags |= EVAS_FILTER_BUMP_COMPENSATE;

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   map = _instruction_param_getbuf(instr, "map", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);
   INSTR_PARAM_CHECK(map);

   cmdid = evas_filter_command_bump_map_add(ctx, dc, src->cid, map->cid, dst->cid,
                                            azimuth, elevation, depth, specular,
                                            black, color, white, flags,
                                            fillmode);

   return cmdid;
}

static int
_instr2cmd_displace(Evas_Filter_Context *ctx,
                    Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Fill_Mode fillmode;
   Evas_Filter_Displacement_Flags flags =
         EVAS_FILTER_DISPLACE_STRETCH | EVAS_FILTER_DISPLACE_LINEAR;
   const char *flagsstr;
   Buffer *src, *dst, *map;
   int cmdid, intensity;
   Eina_Bool isset = EINA_FALSE;

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   map = _instruction_param_getbuf(instr, "map", NULL);
   intensity = _instruction_param_geti(instr, "intensity", NULL);
   flagsstr = _instruction_param_gets(instr, "flags", &isset);
   fillmode = _fill_mode_get(instr);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);
   INSTR_PARAM_CHECK(map);

   if (!flagsstr) flagsstr = "default";
   if (!strcasecmp(flagsstr, "nearest"))
     flags = EVAS_FILTER_DISPLACE_NEAREST;
   else if (!strcasecmp(flagsstr, "smooth"))
     flags = EVAS_FILTER_DISPLACE_LINEAR;
   else if (!strcasecmp(flagsstr, "nearest_stretch"))
     flags = EVAS_FILTER_DISPLACE_NEAREST | EVAS_FILTER_DISPLACE_STRETCH;
   else if (!strcasecmp(flagsstr, "default") || !strcasecmp(flagsstr, "smooth_stretch"))
     flags = EVAS_FILTER_DISPLACE_STRETCH | EVAS_FILTER_DISPLACE_LINEAR;
   else if (isset)
     WRN("Invalid flags '%s' in displace operation. Using default instead", flagsstr);

   cmdid = evas_filter_command_displacement_map_add(ctx, dc, src->cid, dst->cid,
                                                    map->cid, flags, intensity,
                                                    fillmode);

   return cmdid;
}

static int
_instr2cmd_fill(Evas_Filter_Context *ctx,
                Evas_Filter_Instruction *instr, void *dc)
{
   Buffer *dst;
   int R, G, B, A, l, r, t, b;
   Evas_Filter_Command *cmd;
   Eina_Inlist *il;
   DATA32 color;
   int cmdid;

   dst = _instruction_param_getbuf(instr, "dst", NULL);
   color = _instruction_param_getc(instr, "color", NULL);
   l = _instruction_param_geti(instr, "l", NULL);
   r = _instruction_param_geti(instr, "r", NULL);
   t = _instruction_param_geti(instr, "t", NULL);
   b = _instruction_param_geti(instr, "b", NULL);
   INSTR_PARAM_CHECK(dst);

   SETCOLOR(color);
   cmdid = evas_filter_command_fill_add(ctx, dc, dst->cid);
   RESETCOLOR();

   if (cmdid < 0) return -1;
   il = eina_inlist_last(ctx->commands);
   if (!il) return -1;

   cmd = EINA_INLIST_CONTAINER_GET(il, Evas_Filter_Command);
   cmd->draw.clip.l = l;
   cmd->draw.clip.r = r;
   cmd->draw.clip.t = t;
   cmd->draw.clip.b = b;
   cmd->draw.clip_mode_lrtb = EINA_TRUE;

   return cmdid;
}

static int
_instr2cmd_grow(Evas_Filter_Context *ctx,
                Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Command *cmd;
   Buffer *src, *dst;
   Eina_Bool smooth;
   int cmdid, radius;

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   radius = _instruction_param_geti(instr, "radius", NULL);
   smooth = _instruction_param_geti(instr, "smooth", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   cmdid = evas_filter_command_grow_add(ctx, dc, src->cid, dst->cid,
                                        radius, smooth);

   cmd = _evas_filter_command_get(ctx, cmdid);
   if (cmd) cmd->draw.need_temp_buffer = EINA_TRUE;

   return cmdid;
}

static int
_instr2cmd_mask(Evas_Filter_Context *ctx,
                Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Fill_Mode fillmode;
   Buffer *src, *dst, *mask;
   DATA32 color;
   int R, G, B, A, cmdid;

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   mask = _instruction_param_getbuf(instr, "mask", NULL);
   color = _instruction_param_getc(instr, "color", NULL);
   fillmode = _fill_mode_get(instr);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);
   INSTR_PARAM_CHECK(mask);

   SETCOLOR(color);
   cmdid = evas_filter_command_mask_add(ctx, dc, src->cid, mask->cid, dst->cid, fillmode);
   RESETCOLOR();
   if (cmdid < 0) return cmdid;

   if (!src->alpha && !mask->alpha && !dst->alpha)
     {
        Evas_Filter_Command *cmd;

        cmd = _evas_filter_command_get(ctx, cmdid);
        cmd->draw.need_temp_buffer = EINA_TRUE;
     }

   return cmdid;
}

static int
_instr2cmd_curve(Evas_Filter_Context *ctx,
                 Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Interpolation_Mode mode = EVAS_FILTER_INTERPOLATION_MODE_LINEAR;
   Evas_Filter_Channel channel = EVAS_FILTER_CHANNEL_RGB;
   const char *interpolation, *channel_name;
   Buffer *src, *dst;
   DATA8 values[256];
   int *points;
   int cmdid;

   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   points = _instruction_param_getspecial(instr, "points", NULL);
   interpolation = _instruction_param_gets(instr, "interpolation", NULL);
   channel_name = _instruction_param_gets(instr, "channel", NULL);
   INSTR_PARAM_CHECK(points);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (channel_name)
     {
        if (tolower(*channel_name) == 'r')
          {
             if (!strcasecmp(channel_name, "rgb"))
               channel = EVAS_FILTER_CHANNEL_RGB;
             else
               channel = EVAS_FILTER_CHANNEL_RED;
          }
        else if (tolower(*channel_name) == 'g')
          channel = EVAS_FILTER_CHANNEL_GREEN;
        else if (tolower(*channel_name) == 'b')
          channel = EVAS_FILTER_CHANNEL_BLUE;
        else if (tolower(*channel_name) == 'a')
          channel = EVAS_FILTER_CHANNEL_ALPHA;
     }

   if (interpolation && !strcasecmp(interpolation, "none"))
     mode = EVAS_FILTER_INTERPOLATION_MODE_NONE;

   if (!evas_filter_interpolate(values, points, mode))
     {
        int x;
        ERR("Failed to parse the interpolation chain");
        for (x = 0; x < 256; x++)
          values[x] = x;
     }

   cmdid = evas_filter_command_curve_add(ctx, dc, src->cid, dst->cid, values, channel);

   return cmdid;
}

static int
_instr2cmd_transform(Evas_Filter_Context *ctx,
                     Evas_Filter_Instruction *instr, void *dc)
{
   Evas_Filter_Transform_Flags flags;
   const char *op;
   Buffer *src, *dst;
   int ox = 0, oy;

   op = _instruction_param_gets(instr, "op", NULL);
   src = _instruction_param_getbuf(instr, "src", NULL);
   dst = _instruction_param_getbuf(instr, "dst", NULL);
   // ox = _instruction_param_geti(instr, "ox", NULL);
   oy = _instruction_param_geti(instr, "oy", NULL);
   INSTR_PARAM_CHECK(src);
   INSTR_PARAM_CHECK(dst);

   if (!strcasecmp(op, "vflip"))
     flags = EVAS_FILTER_TRANSFORM_VFLIP;
   else
     {
        ERR("Invalid transform '%s'", op);
        return -1;
     }

   return evas_filter_command_transform_add(ctx, dc, src->cid, dst->cid, flags, ox, oy);
}

static int
_command_from_instruction(Evas_Filter_Context *ctx,
                          Evas_Filter_Instruction *instr, void *dc)
{
   int (* instr2cmd) (Evas_Filter_Context *, Evas_Filter_Instruction *, void *);

   switch (instr->type)
     {
      case EVAS_FILTER_MODE_BLEND:
        instr2cmd = _instr2cmd_blend;
        break;
      case EVAS_FILTER_MODE_BLUR:
        instr2cmd = _instr2cmd_blur;
        break;
      case EVAS_FILTER_MODE_BUMP:
        instr2cmd = _instr2cmd_bump;
        break;
      case EVAS_FILTER_MODE_DISPLACE:
        instr2cmd = _instr2cmd_displace;
        break;
      case EVAS_FILTER_MODE_FILL:
        instr2cmd = _instr2cmd_fill;
        break;
      case EVAS_FILTER_MODE_GROW:
        instr2cmd = _instr2cmd_grow;
        break;
      case EVAS_FILTER_MODE_MASK:
        instr2cmd = _instr2cmd_mask;
        break;
      case EVAS_FILTER_MODE_CURVE:
        instr2cmd = _instr2cmd_curve;
        break;
      case EVAS_FILTER_MODE_TRANSFORM:
        instr2cmd = _instr2cmd_transform;
        break;
      case EVAS_FILTER_MODE_PADDING_SET:
      case EVAS_FILTER_MODE_BUFFER:
        return EINA_TRUE;
      default:
        CRI("Invalid instruction type: %d", instr->type);
        return -1;
     }

   return instr2cmd(ctx, instr, dc);
}

#ifdef FILTERS_DEBUG
static void
_instruction_dump(Evas_Filter_Instruction *instr)
{
   Eina_Strbuf *str;
   const char *comma = "";
   Instruction_Param *param;

   if (!instr) return;

   str = eina_strbuf_new();
   eina_strbuf_append(str, instr->name);
   eina_strbuf_append(str, "({ ");
   EINA_INLIST_FOREACH(instr->params, param)
     {
        switch (param->type)
          {
           case VT_BOOL:
           case VT_INT:
             eina_strbuf_append_printf(str, "%s%s = %d", comma, param->name, param->value.i);
             break;
           case VT_COLOR:
             eina_strbuf_append_printf(str, "%s%s = 0x%08x", comma, param->name, param->value.c);
             break;
           case VT_REAL:
             eina_strbuf_append_printf(str, "%s%s = %f", comma, param->name, param->value.f);
             break;
           case VT_STRING:
             if (param->value.s)
               eina_strbuf_append_printf(str, "%s%s = \"%s\"", comma, param->name, param->value.s);
             else
               eina_strbuf_append_printf(str, "%s%s = nil", comma, param->name);
             break;
           case VT_BUFFER:
             if (param->value.buf)
               {
                  Buffer *buf = param->value.buf;
                  eina_strbuf_append_printf(str, "%s%s = Buffer[#%d %dx%d %s%s%s]",
                                            comma, param->name,
                                            buf->cid, buf->w, buf->h,
                                            buf->alpha ? "alpha" : "rgba",
                                            buf->proxy ? " src: " : "",
                                            buf->proxy ? buf->proxy : "");
               }
             else
               eina_strbuf_append_printf(str, "%s%s = nil", comma, param->name);
             break;
           case VT_NONE:
           default:
             eina_strbuf_append_printf(str, "%s%s = <INVALID>", comma, param->name);
             break;
          }

        comma = ", ";
     }
   eina_strbuf_append(str, "})");
   XDBG("%s", eina_strbuf_string_get(str));
   eina_strbuf_free(str);
}
#else
# define _instruction_dump(a) do {} while(0)
#endif

Eina_Bool
evas_filter_context_program_use(Evas_Filter_Context *ctx,
                                Evas_Filter_Program *pgm)
{
   Evas_Filter_Instruction *instr;
   Eina_Bool success = EINA_FALSE;
   void *dc = NULL;
   int cmdid;

   EINA_SAFETY_ON_NULL_RETURN_VAL(ctx, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(pgm, EINA_FALSE);
   EINA_SAFETY_ON_FALSE_RETURN_VAL(pgm->valid, EINA_FALSE);

   XDBG("Using program '%s' for context %p", pgm->name, ctx);

   // Copy current state (size, edje state val, color class, etc...)
   ctx->w = pgm->state.w;
   ctx->h = pgm->state.h;

   // Create empty context with all required buffers
   evas_filter_context_clear(ctx);

   if (pgm->changed)
     {
        pgm->changed = EINA_FALSE;
        _filter_program_reset(pgm);
        lua_getglobal(pgm->L, _lua_errfunc_name);
        lua_rawgeti(pgm->L, LUA_REGISTRYINDEX, pgm->lua_func);
        success = !lua_pcall(pgm->L, 0, LUA_MULTRET, -2);
        if (!success)
          {
             const char *msg = lua_tostring(pgm->L, -1);
             ERR("Lua execution failed: %s", msg);
             goto end;
          }
     }
   _buffers_update(ctx, pgm);

   // Compute and save padding info
   evas_filter_program_padding_get(pgm, &ctx->padl, &ctx->padr, &ctx->padt, &ctx->padb);

   dc = ENFN->context_new(ENDT);
   ENFN->context_color_set(ENDT, dc, 255, 255, 255, 255);

   // Apply all commands
   EINA_INLIST_FOREACH(pgm->instructions, instr)
     {
        _instruction_dump(instr);
        cmdid = _command_from_instruction(ctx, instr, dc);
        if (cmdid <= 0)
          goto end;
     }

   success = EINA_TRUE;
   pgm->changed = EINA_FALSE;

end:
   if (!success) evas_filter_context_clear(ctx);
   if (dc) ENFN->context_free(ENDT, dc);
   return success;
}

void
evas_filter_parser_shutdown(void)
{
   free(_lua_color_code);
   _lua_color_code = NULL;
}