summaryrefslogtreecommitdiff
path: root/src/openvg/qpaintengine_vg.cpp
blob: 249f8bf6c89cc66c76883a7d73d052d7bcd53be0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
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
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenVG module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qpaintengine_vg_p.h"
#include "qpixmapdata_vg_p.h"
#include "qpixmapfilter_vg_p.h"
#include "qvgcompositionhelper_p.h"
#include "qvgimagepool_p.h"
#if !defined(QT_NO_EGL)
#include <QtGui/private/qegl_p.h>
#include "qwindowsurface_vgegl_p.h"
#endif
#include <QtCore/qvarlengtharray.h>
#include <QtGui/private/qdrawhelper_p.h>
#include <QtGui/private/qtextureglyphcache_p.h>
#include <QtGui/private/qtextengine_p.h>
#include <QtGui/private/qfontengine_p.h>
#include <QtGui/private/qpainterpath_p.h>
#include <QDebug>
#include <QSet>

QT_BEGIN_NAMESPACE

// vgDrawGlyphs() only exists in OpenVG 1.1 and higher.
#if !defined(OPENVG_VERSION_1_1) && !defined(QVG_NO_DRAW_GLYPHS)
#define QVG_NO_DRAW_GLYPHS 1
#endif

// vgRenderToMask() only exists in OpenVG 1.1 and higher.
// Also, disable masking completely if we are using the scissor to clip.
#if !defined(OPENVG_VERSION_1_1) && !defined(QVG_NO_RENDER_TO_MASK)
#define QVG_NO_RENDER_TO_MASK 1
#endif
#if defined(QVG_SCISSOR_CLIP) && !defined(QVG_NO_RENDER_TO_MASK)
#define QVG_NO_RENDER_TO_MASK 1
#endif

#if !defined(QVG_NO_DRAW_GLYPHS)

extern int qt_defaultDpiX();
extern int qt_defaultDpiY();

class QVGPaintEnginePrivate;

class QVGFontGlyphCache
{
public:
    QVGFontGlyphCache();
    ~QVGFontGlyphCache();

    void cacheGlyphs(QVGPaintEnginePrivate *d,
                     const QTextItemInt &ti,
                     const QVarLengthArray<glyph_t> &glyphs);
    void setScaleFromText(const QTextItemInt &ti);

    VGFont font;
    VGfloat scaleX;
    VGfloat scaleY;
    
    uint cachedGlyphsMask[256 / 32];
    QSet<glyph_t> cachedGlyphs;
};

typedef QHash<QFontEngine*, QVGFontGlyphCache*> QVGFontCache;

#endif

class QVGFontEngineCleaner : public QObject
{
    Q_OBJECT
public:
    QVGFontEngineCleaner(QVGPaintEnginePrivate *d);
    ~QVGFontEngineCleaner();

public slots:
    void fontEngineDestroyed();

private:
    QVGPaintEnginePrivate *d_ptr;
};

class QVGPaintEnginePrivate : public QPaintEngineExPrivate
{
public:
    QVGPaintEnginePrivate();
    ~QVGPaintEnginePrivate();

    void init();
    void initObjects();
    void destroy();
    void setTransform(VGMatrixMode mode, const QTransform& transform);
    void updateTransform(QPaintDevice *pdev);
    void draw(VGPath path, const QPen& pen, const QBrush& brush, VGint rule = VG_EVEN_ODD);
    void stroke(VGPath path, const QPen& pen);
    void fill(VGPath path, const QBrush& brush, VGint rule = VG_EVEN_ODD);
    VGPath vectorPathToVGPath(const QVectorPath& path);
    VGPath painterPathToVGPath(const QPainterPath& path);
    VGPath roundedRectPath(const QRectF &rect, qreal xRadius, qreal yRadius, Qt::SizeMode mode);
    VGPaintType setBrush
        (VGPaint paint, const QBrush& brush, VGMatrixMode mode,
         VGPaintType prevPaintType);
    void setPenParams(const QPen& pen);
    void setBrushTransform(const QBrush& brush, VGMatrixMode mode);
    void setupColorRamp(const QGradient *grad, VGPaint paint);
    void setImageOptions();
#if !defined(QVG_SCISSOR_CLIP)
    void ensureMask(QVGPaintEngine *engine, int width, int height);
    void modifyMask
        (QVGPaintEngine *engine, VGMaskOperation op, const QRegion& region);
    void modifyMask
        (QVGPaintEngine *engine, VGMaskOperation op, const QRect& rect);
#endif

    VGint maxScissorRects;  // Maximum scissor rectangles for clipping.

    VGPaint penPaint;       // Paint for currently active pen.
    VGPaint brushPaint;     // Paint for currently active brush.
    VGPaint opacityPaint;   // Paint for drawing images with opacity.
    VGPaint fillPaint;      // Current fill paint that is active.

    QPen currentPen;        // Current pen set in "penPaint".
    QBrush currentBrush;    // Current brush set in "brushPaint".

    bool forcePenChange;    // Force a pen change, even if the same.
    bool forceBrushChange;  // Force a brush change, even if the same.

    VGPaintType penType;    // Type of the last pen that was set.
    VGPaintType brushType;  // Type of the last brush that was set.

    QPointF brushOrigin;    // Current brush origin.

    VGint fillRule;         // Last fill rule that was set.

    qreal opacity;          // Current drawing opacity.
    qreal paintOpacity;     // Opacity in opacityPaint.

#if !defined(QVG_NO_MODIFY_PATH)
    VGPath rectPath;        // Cached path for quick drawing of rectangles.
    VGPath linePath;        // Cached path for quick drawing of lines.
    VGPath roundRectPath;   // Cached path for quick drawing of rounded rects.
#endif

    QTransform transform;   // Currently active transform.
    bool simpleTransform;   // True if the transform is simple (non-projective).
    qreal penScale;         // Pen scaling factor from "transform".

    QTransform pathTransform;  // Calculated VG path transformation.
    QTransform imageTransform; // Calculated VG image transformation.
    bool pathTransformSet;  // True if path transform set in the VG context.

    bool maskValid;         // True if vgMask() contains valid data.
    bool maskIsSet;         // True if mask would be fully set if it was valid.
    bool rawVG;             // True if processing a raw VG escape.

    QRect maskRect;         // Rectangle version of mask if it is simple.

    QTransform penTransform;   // Transform for the pen.
    QTransform brushTransform; // Transform for the brush.

    VGMatrixMode matrixMode;    // Last matrix mode that was set.
    VGImageMode imageMode;      // Last image mode that was set.

    QRegion scissorRegion;  // Currently active scissor region.
    bool scissorActive;     // True if scissor region is active.

    QPaintEngine::DirtyFlags dirty;

    QColor clearColor;      // Last clear color that was set.
    VGfloat clearOpacity;   // Opacity during the last clear.

    VGBlendMode blendMode;  // Active blend mode.
    VGRenderingQuality renderingQuality; // Active rendering quality.
    VGImageQuality imageQuality;    // Active image quality.

#if !defined(QVG_NO_DRAW_GLYPHS)
    QVGFontCache fontCache;
    QVGFontEngineCleaner *fontEngineCleaner;
#endif

    QScopedPointer<QPixmapFilter> convolutionFilter;
    QScopedPointer<QPixmapFilter> colorizeFilter;
    QScopedPointer<QPixmapFilter> dropShadowFilter;
    QScopedPointer<QPixmapFilter> blurFilter;

    // Ensure that the path transform is properly set in the VG context
    // before we perform a vgDrawPath() operation.
    inline void ensurePathTransform()
    {
        if (!pathTransformSet) {
            setTransform(VG_MATRIX_PATH_USER_TO_SURFACE, pathTransform);
            pathTransformSet = true;
        }
    }

    // Ensure that a specific pen has been set into penPaint.
    inline void ensurePen(const QPen& pen) {
        if (forcePenChange || pen != currentPen) {
            currentPen = pen;
            forcePenChange = false;
            penType = setBrush
                (penPaint, pen.brush(),
                 VG_MATRIX_STROKE_PAINT_TO_USER, penType);
            setPenParams(pen);
        }
    }

    // Ensure that a specific brush has been set into brushPaint.
    inline void ensureBrush(const QBrush& brush) {
        if (forceBrushChange || brush != currentBrush) {
            currentBrush = brush;
            forceBrushChange = false;
            brushType = setBrush
                (brushPaint, brush, VG_MATRIX_FILL_PAINT_TO_USER, brushType);
        }
        if (fillPaint != brushPaint) {
            vgSetPaint(brushPaint, VG_FILL_PATH);
            fillPaint = brushPaint;
        }
    }

    // Set various modes, but only if different.
    inline void setImageMode(VGImageMode mode);
    inline void setRenderingQuality(VGRenderingQuality mode);
    inline void setImageQuality(VGImageQuality mode);
    inline void setBlendMode(VGBlendMode mode);
    inline void setFillRule(VGint mode);

    // Clear all lazily-set modes.
    void clearModes();
};

inline void QVGPaintEnginePrivate::setImageMode(VGImageMode mode)
{
    if (imageMode != mode) {
        imageMode = mode;
        vgSeti(VG_IMAGE_MODE, mode);
    }
}

inline void QVGPaintEnginePrivate::setRenderingQuality(VGRenderingQuality mode)
{
    if (renderingQuality != mode) {
        vgSeti(VG_RENDERING_QUALITY, mode);
        renderingQuality = mode;
    }
}

inline void QVGPaintEnginePrivate::setImageQuality(VGImageQuality mode)
{
    if (imageQuality != mode) {
        vgSeti(VG_IMAGE_QUALITY, mode);
        imageQuality = mode;
    }
}

inline void QVGPaintEnginePrivate::setBlendMode(VGBlendMode mode)
{
    if (blendMode != mode) {
        vgSeti(VG_BLEND_MODE, mode);
        blendMode = mode;
    }
}

inline void QVGPaintEnginePrivate::setFillRule(VGint mode)
{
    if (fillRule != mode) {
        fillRule = mode;
        vgSeti(VG_FILL_RULE, mode);
    }
}

void QVGPaintEnginePrivate::clearModes()
{
    matrixMode = (VGMatrixMode)0;
    imageMode = (VGImageMode)0;
    blendMode = (VGBlendMode)0;
    renderingQuality = (VGRenderingQuality)0;
    imageQuality = (VGImageQuality)0;
}

QVGPaintEnginePrivate::QVGPaintEnginePrivate()
{
    init();
}

void QVGPaintEnginePrivate::init()
{
    maxScissorRects = 0;

    penPaint = 0;
    brushPaint = 0;
    opacityPaint = 0;
    fillPaint = 0;

    forcePenChange = true;
    forceBrushChange = true;
    penType = (VGPaintType)0;
    brushType = (VGPaintType)0;

    brushOrigin = QPointF(0.0f, 0.0f);

    fillRule = 0;

    opacity = 1.0;
    paintOpacity = 1.0f;

#if !defined(QVG_NO_MODIFY_PATH)
    rectPath = 0;
    linePath = 0;
    roundRectPath = 0;
#endif

    simpleTransform = true;
    pathTransformSet = false;
    penScale = 1.0;

    maskValid = false;
    maskIsSet = false;
    rawVG = false;

    scissorActive = false;

    dirty = 0;

    clearOpacity = 1.0f;

#if !defined(QVG_NO_DRAW_GLYPHS)
    fontEngineCleaner = 0;
#endif

    clearModes();
}

QVGPaintEnginePrivate::~QVGPaintEnginePrivate()
{
    destroy();
}

void QVGPaintEnginePrivate::initObjects()
{
    maxScissorRects = vgGeti(VG_MAX_SCISSOR_RECTS);

    penPaint = vgCreatePaint();
    vgSetParameteri(penPaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
    vgSetPaint(penPaint, VG_STROKE_PATH);

    vgSeti(VG_MATRIX_MODE, VG_MATRIX_STROKE_PAINT_TO_USER);
    vgLoadIdentity();

    brushPaint = vgCreatePaint();
    vgSetParameteri(brushPaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
    vgSetPaint(brushPaint, VG_FILL_PATH);
    fillPaint = brushPaint;

    vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
    vgLoadIdentity();
    matrixMode = VG_MATRIX_FILL_PAINT_TO_USER;

    opacityPaint = vgCreatePaint();
    vgSetParameteri(opacityPaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
    VGfloat values[4];
    values[0] = 1.0f;
    values[1] = 1.0f;
    values[2] = 1.0f;
    values[3] = paintOpacity;
    vgSetParameterfv(opacityPaint, VG_PAINT_COLOR, 4, values);

#if !defined(QVG_NO_MODIFY_PATH)
    // Create a dummy path for rectangle drawing, which we can
    // modify later with vgModifyPathCoords().  This should be
    // faster than constantly creating and destroying paths.
    rectPath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                            VG_PATH_DATATYPE_F,
                            1.0f, // scale
                            0.0f, // bias
                            5,    // segmentCapacityHint
                            8,    // coordCapacityHint
                            VG_PATH_CAPABILITY_ALL);
    static VGubyte const segments[5] = {
        VG_MOVE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CLOSE_PATH
    };
    VGfloat coords[8];
    coords[0] = 0.0f;
    coords[1] = 0.0f;
    coords[2] = 100.0f;
    coords[3] = coords[1];
    coords[4] = coords[2];
    coords[5] = 100.0f;
    coords[6] = coords[0];
    coords[7] = coords[5];
    vgAppendPathData(rectPath, 5, segments, coords);

    // Create a dummy line drawing path as well.
    linePath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                            VG_PATH_DATATYPE_F,
                            1.0f, // scale
                            0.0f, // bias
                            2,    // segmentCapacityHint
                            4,    // coordCapacityHint
                            VG_PATH_CAPABILITY_ALL);
    vgAppendPathData(linePath, 2, segments, coords);
#endif
}

void QVGPaintEnginePrivate::destroy()
{
    if (penPaint)
        vgDestroyPaint(penPaint);
    if (brushPaint)
        vgDestroyPaint(brushPaint);
    if (opacityPaint)
        vgDestroyPaint(opacityPaint);

#if !defined(QVG_NO_MODIFY_PATH)
    if (rectPath)
        vgDestroyPath(rectPath);
    if (linePath)
        vgDestroyPath(linePath);
    if (roundRectPath)
        vgDestroyPath(roundRectPath);
#endif

#if !defined(QVG_NO_DRAW_GLYPHS)
    QVGFontCache::Iterator it;
    for (it = fontCache.begin(); it != fontCache.end(); ++it)
        delete it.value();
    fontCache.clear();
    delete fontEngineCleaner;
#endif
}

// Set a specific VG transformation matrix in the current VG context.
void QVGPaintEnginePrivate::setTransform
        (VGMatrixMode mode, const QTransform& transform)
{
    VGfloat mat[9];
    if (mode != matrixMode) {
        vgSeti(VG_MATRIX_MODE, mode);
        matrixMode = mode;
    }
    mat[0] = transform.m11();
    mat[1] = transform.m12();
    mat[2] = transform.m13();
    mat[3] = transform.m21();
    mat[4] = transform.m22();
    mat[5] = transform.m23();
    mat[6] = transform.m31();
    mat[7] = transform.m32();
    mat[8] = transform.m33();
    vgLoadMatrix(mat);
}

extern bool qt_scaleForTransform(const QTransform &transform, qreal *scale);

void QVGPaintEnginePrivate::updateTransform(QPaintDevice *pdev)
{
    VGfloat devh = pdev->height() - 1;

    // Construct the VG transform by combining the Qt transform with
    // the following viewport transformation:
    //        | 1  0  0   |   | 1 0  0.5 |   | 1  0     0.5      |
    //        | 0 -1 devh | * | 0 1 -0.5 | = | 0 -1 (0.5 + devh) |
    //        | 0  0  1   |   | 0 0   1  |   | 0  0      1       |
    // The full VG transform is effectively:
    //      1. Apply the user's transformation matrix.
    //      2. Translate by (0.5, -0.5) to correct for Qt and VG putting
    //         the centre of the pixel at different positions.
    //      3. Flip the co-ordinate system upside down.
    QTransform viewport(1.0f, 0.0f, 0.0f,
                        0.0f, -1.0f, 0.0f,
                        0.5f, devh + 0.5f, 1.0f);

    // The image transform is always the full transformation,
    // because it can be projective.
    imageTransform = transform * viewport;

    // Determine if the transformation is projective.
    bool projective = (imageTransform.m13() != 0.0f ||
                       imageTransform.m23() != 0.0f ||
                       imageTransform.m33() != 1.0f);
    if (projective) {
        // The engine cannot do projective path transforms for us,
        // so we will have to convert the co-ordinates ourselves.
        // Change the matrix to just the viewport transformation.
        pathTransform = viewport;
        simpleTransform = false;
    } else {
        pathTransform = imageTransform;
        simpleTransform = true;
    }
    pathTransformSet = false;

    // Calculate the scaling factor to use for turning cosmetic pens
    // into ordinary non-cosmetic pens.
    qt_scaleForTransform(transform, &penScale);
}

VGPath QVGPaintEnginePrivate::vectorPathToVGPath(const QVectorPath& path)
{
    int count = path.elementCount();
    const qreal *points = path.points();
    const QPainterPath::ElementType *elements = path.elements();

    VGPath vgpath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                                 VG_PATH_DATATYPE_F,
                                 1.0f,        // scale
                                 0.0f,        // bias
                                 count + 1,   // segmentCapacityHint
                                 count * 2,   // coordCapacityHint
                                 VG_PATH_CAPABILITY_ALL);

    // Size is sufficient segments for drawRoundedRect() paths.
    QVarLengthArray<VGubyte, 20> segments;

    if (sizeof(qreal) == sizeof(VGfloat) && elements && simpleTransform) {
        // If Qt was compiled with qreal the same size as VGfloat,
        // then convert the segment types and use the incoming
        // points array directly.
        for (int i = 0; i < count; ++i) {
            switch (elements[i]) {

            case QPainterPath::MoveToElement:
                segments.append(VG_MOVE_TO_ABS); break;

            case QPainterPath::LineToElement:
                segments.append(VG_LINE_TO_ABS); break;

            case QPainterPath::CurveToElement:
                segments.append(VG_CUBIC_TO_ABS); break;

            case QPainterPath::CurveToDataElement: break;

            }
        }
        if (path.hasImplicitClose())
            segments.append(VG_CLOSE_PATH);

        vgAppendPathData(vgpath, segments.count(), segments.constData(),
                         reinterpret_cast<const VGfloat *>(points));

        return vgpath;
    }

    // Sizes chosen so that drawRoundedRect() paths fit in these arrays.
    QVarLengthArray<VGfloat, 48> coords;

    int curvePos = 0;
    QPointF temp;

    if (elements && simpleTransform) {
        // Convert the members of the element array.
        for (int i = 0; i < count; ++i) {
            switch (elements[i]) {

            case QPainterPath::MoveToElement:
            {
                coords.append(points[0]);
                coords.append(points[1]);
                segments.append(VG_MOVE_TO_ABS);
            }
            break;

            case QPainterPath::LineToElement:
            {
                coords.append(points[0]);
                coords.append(points[1]);
                segments.append(VG_LINE_TO_ABS);
            }
            break;

            case QPainterPath::CurveToElement:
            {
                coords.append(points[0]);
                coords.append(points[1]);
                curvePos = 2;
            }
            break;

            case QPainterPath::CurveToDataElement:
            {
                coords.append(points[0]);
                coords.append(points[1]);
                curvePos += 2;
                if (curvePos == 6) {
                    curvePos = 0;
                    segments.append(VG_CUBIC_TO_ABS);
                }
            }
            break;

            }
            points += 2;
        }
    } else if (elements && !simpleTransform) {
        // Convert the members of the element array after applying the
        // current transform to the path locally.
        for (int i = 0; i < count; ++i) {
            switch (elements[i]) {

            case QPainterPath::MoveToElement:
            {
                temp = transform.map(QPointF(points[0], points[1]));
                coords.append(temp.x());
                coords.append(temp.y());
                segments.append(VG_MOVE_TO_ABS);
            }
            break;

            case QPainterPath::LineToElement:
            {
                temp = transform.map(QPointF(points[0], points[1]));
                coords.append(temp.x());
                coords.append(temp.y());
                segments.append(VG_LINE_TO_ABS);
            }
            break;

            case QPainterPath::CurveToElement:
            {
                temp = transform.map(QPointF(points[0], points[1]));
                coords.append(temp.x());
                coords.append(temp.y());
                curvePos = 2;
            }
            break;

            case QPainterPath::CurveToDataElement:
            {
                temp = transform.map(QPointF(points[0], points[1]));
                coords.append(temp.x());
                coords.append(temp.y());
                curvePos += 2;
                if (curvePos == 6) {
                    curvePos = 0;
                    segments.append(VG_CUBIC_TO_ABS);
                }
            }
            break;

            }
            points += 2;
        }
    } else if (count > 0 && simpleTransform) {
        // If there is no element array, then the path is assumed
        // to be a MoveTo followed by several LineTo's.
        coords.append(points[0]);
        coords.append(points[1]);
        segments.append(VG_MOVE_TO_ABS);
        while (count > 1) {
            points += 2;
            coords.append(points[0]);
            coords.append(points[1]);
            segments.append(VG_LINE_TO_ABS);
            --count;
        }
    } else if (count > 0 && !simpleTransform) {
        // Convert a simple path, and apply the transform locally.
        temp = transform.map(QPointF(points[0], points[1]));
        coords.append(temp.x());
        coords.append(temp.y());
        segments.append(VG_MOVE_TO_ABS);
        while (count > 1) {
            points += 2;
            temp = transform.map(QPointF(points[0], points[1]));
            coords.append(temp.x());
            coords.append(temp.y());
            segments.append(VG_LINE_TO_ABS);
            --count;
        }
    }

    // Close the path if specified.
    if (path.hasImplicitClose())
        segments.append(VG_CLOSE_PATH);

    vgAppendPathData(vgpath, segments.count(),
                     segments.constData(), coords.constData());

    return vgpath;
}

VGPath QVGPaintEnginePrivate::painterPathToVGPath(const QPainterPath& path)
{
    int count = path.elementCount();

    VGPath vgpath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                                 VG_PATH_DATATYPE_F,
                                 1.0f,        // scale
                                 0.0f,        // bias
                                 count + 1,   // segmentCapacityHint
                                 count * 2,   // coordCapacityHint
                                 VG_PATH_CAPABILITY_ALL);

    if (count == 0)
        return vgpath;

    const QPainterPath::Element *elements = &(path.elementAt(0));

    // Sizes chosen so that drawRoundedRect() paths fit in these arrays.
    QVarLengthArray<VGfloat, 48> coords;
    QVarLengthArray<VGubyte, 20> segments;

    int curvePos = 0;
    QPointF temp;

    // Keep track of the start and end of each sub-path.  QPainterPath
    // does not have an "implicit close" flag like QVectorPath does.
    // We therefore have to detect closed paths by looking for a LineTo
    // element that connects back to the initial MoveTo element.
    qreal startx = 0.0;
    qreal starty = 0.0;
    qreal endx = 0.0;
    qreal endy = 0.0;
    bool haveStart = false;
    bool haveEnd = false;

    if (simpleTransform) {
        // Convert the members of the element array.
        for (int i = 0; i < count; ++i) {
            switch (elements[i].type) {

            case QPainterPath::MoveToElement:
            {
                if (haveStart && haveEnd && startx == endx && starty == endy) {
                    // Implicitly close the previous sub-path.
                    segments.append(VG_CLOSE_PATH);
                }
                startx = elements[i].x;
                starty = elements[i].y;
                coords.append(startx);
                coords.append(starty);
                haveStart = true;
                haveEnd = false;
                segments.append(VG_MOVE_TO_ABS);
            }
            break;

            case QPainterPath::LineToElement:
            {
                endx = elements[i].x;
                endy = elements[i].y;
                coords.append(endx);
                coords.append(endy);
                haveEnd = true;
                segments.append(VG_LINE_TO_ABS);
            }
            break;

            case QPainterPath::CurveToElement:
            {
                coords.append(elements[i].x);
                coords.append(elements[i].y);
                haveEnd = false;
                curvePos = 2;
            }
            break;

            case QPainterPath::CurveToDataElement:
            {
                coords.append(elements[i].x);
                coords.append(elements[i].y);
                haveEnd = false;
                curvePos += 2;
                if (curvePos == 6) {
                    curvePos = 0;
                    segments.append(VG_CUBIC_TO_ABS);
                }
            }
            break;

            }
        }
    } else {
        // Convert the members of the element array after applying the
        // current transform to the path locally.
        for (int i = 0; i < count; ++i) {
            switch (elements[i].type) {

            case QPainterPath::MoveToElement:
            {
                if (haveStart && haveEnd && startx == endx && starty == endy) {
                    // Implicitly close the previous sub-path.
                    segments.append(VG_CLOSE_PATH);
                }
                temp = transform.map(QPointF(elements[i].x, elements[i].y));
                startx = temp.x();
                starty = temp.y();
                coords.append(startx);
                coords.append(starty);
                haveStart = true;
                haveEnd = false;
                segments.append(VG_MOVE_TO_ABS);
            }
            break;

            case QPainterPath::LineToElement:
            {
                temp = transform.map(QPointF(elements[i].x, elements[i].y));
                endx = temp.x();
                endy = temp.y();
                coords.append(endx);
                coords.append(endy);
                haveEnd = true;
                segments.append(VG_LINE_TO_ABS);
            }
            break;

            case QPainterPath::CurveToElement:
            {
                temp = transform.map(QPointF(elements[i].x, elements[i].y));
                coords.append(temp.x());
                coords.append(temp.y());
                haveEnd = false;
                curvePos = 2;
            }
            break;

            case QPainterPath::CurveToDataElement:
            {
                temp = transform.map(QPointF(elements[i].x, elements[i].y));
                coords.append(temp.x());
                coords.append(temp.y());
                haveEnd = false;
                curvePos += 2;
                if (curvePos == 6) {
                    curvePos = 0;
                    segments.append(VG_CUBIC_TO_ABS);
                }
            }
            break;

            }
        }
    }

    if (haveStart && haveEnd && startx == endx && starty == endy) {
        // Implicitly close the last sub-path.
        segments.append(VG_CLOSE_PATH);
    }

    vgAppendPathData(vgpath, segments.count(),
                     segments.constData(), coords.constData());

    return vgpath;
}

VGPath QVGPaintEnginePrivate::roundedRectPath(const QRectF &rect, qreal xRadius, qreal yRadius, Qt::SizeMode mode)
{
    static VGubyte roundedrect_types[] = {
        VG_MOVE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CUBIC_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CUBIC_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CUBIC_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CUBIC_TO_ABS,
        VG_CLOSE_PATH
    };

    qreal x1 = rect.left();
    qreal x2 = rect.right();
    qreal y1 = rect.top();
    qreal y2 = rect.bottom();

    if (mode == Qt::RelativeSize) {
        xRadius = xRadius * rect.width() / 200.;
        yRadius = yRadius * rect.height() / 200.;
    }

    xRadius = qMin(xRadius, rect.width() / 2);
    yRadius = qMin(yRadius, rect.height() / 2);

    VGfloat pts[] = {
        x1 + xRadius, y1,                   // MoveTo
        x2 - xRadius, y1,                   // LineTo
        x2 - (1 - KAPPA) * xRadius, y1,     // CurveTo
        x2, y1 + (1 - KAPPA) * yRadius,
        x2, y1 + yRadius,
        x2, y2 - yRadius,                   // LineTo
        x2, y2 - (1 - KAPPA) * yRadius,     // CurveTo
        x2 - (1 - KAPPA) * xRadius, y2,
        x2 - xRadius, y2,
        x1 + xRadius, y2,                   // LineTo
        x1 + (1 - KAPPA) * xRadius, y2,     // CurveTo
        x1, y2 - (1 - KAPPA) * yRadius,
        x1, y2 - yRadius,
        x1, y1 + yRadius,                   // LineTo
        x1, y1 + KAPPA * yRadius,           // CurveTo
        x1 + (1 - KAPPA) * xRadius, y1,
        x1 + xRadius, y1
    };

#if !defined(QVG_NO_MODIFY_PATH)
    VGPath vgpath = roundRectPath;
    if (!vgpath) {
        vgpath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                              VG_PATH_DATATYPE_F,
                              1.0f,        // scale
                              0.0f,        // bias
                              10,          // segmentCapacityHint
                              17 * 2,      // coordCapacityHint
                              VG_PATH_CAPABILITY_ALL);
        vgAppendPathData(vgpath, 10, roundedrect_types, pts);
        roundRectPath = vgpath;
    } else {
        vgModifyPathCoords(vgpath, 0, 9, pts);
    }
#else
    VGPath vgpath = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                                 VG_PATH_DATATYPE_F,
                                 1.0f,        // scale
                                 0.0f,        // bias
                                 10,          // segmentCapacityHint
                                 17 * 2,      // coordCapacityHint
                                 VG_PATH_CAPABILITY_ALL);
    vgAppendPathData(vgpath, 10, roundedrect_types, pts);
#endif

    return vgpath;
}

extern QImage qt_imageForBrush(int style, bool invert);

static QImage colorizeBitmap(const QImage &image, const QColor &color)
{
    QImage sourceImage = image.convertToFormat(QImage::Format_MonoLSB);
    QImage dest = QImage(sourceImage.size(), QImage::Format_ARGB32_Premultiplied);

    QRgb fg = PREMUL(color.rgba());
    QRgb bg = 0;

    int height = sourceImage.height();
    int width = sourceImage.width();
    for (int y=0; y<height; ++y) {
        uchar *source = sourceImage.scanLine(y);
        QRgb *target = reinterpret_cast<QRgb *>(dest.scanLine(y));
        for (int x=0; x < width; ++x)
            target[x] = (source[x>>3] >> (x&7)) & 1 ? fg : bg;
    }
    return dest;
}

static VGImage toVGImage
    (const QImage & image, Qt::ImageConversionFlags flags = Qt::AutoColor)
{
    QImage img(image);

    VGImageFormat format;
    switch (img.format()) {
    case QImage::Format_Mono:
        img = image.convertToFormat(QImage::Format_MonoLSB, flags);
        format = VG_BW_1;
        break;
    case QImage::Format_MonoLSB:
        format = VG_BW_1;
        break;
    case QImage::Format_RGB32:
        format = VG_sXRGB_8888;
        break;
    case QImage::Format_ARGB32:
        format = VG_sARGB_8888;
        break;
    case QImage::Format_ARGB32_Premultiplied:
        format = VG_sARGB_8888_PRE;
        break;
    case QImage::Format_RGB16:
        format = VG_sRGB_565;
        break;
    default:
        // Convert everything else into ARGB32_Premultiplied.
        img = image.convertToFormat(QImage::Format_ARGB32_Premultiplied, flags);
        format = VG_sARGB_8888_PRE;
        break;
    }

    const uchar *pixels = img.bits();

    VGImage vgImg = QVGImagePool::instance()->createPermanentImage
        (format, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
    vgImageSubData
        (vgImg, pixels, img.bytesPerLine(), format, 0, 0,
         img.width(), img.height());

    return vgImg;
}

static VGImage toVGImageSubRect
    (const QImage & image, const QRect& sr,
     Qt::ImageConversionFlags flags = Qt::AutoColor)
{
    QImage img(image);

    VGImageFormat format;
    int bpp = 4;

    switch (img.format()) {
    case QImage::Format_Mono:
    case QImage::Format_MonoLSB:
        return VG_INVALID_HANDLE;
    case QImage::Format_RGB32:
        format = VG_sXRGB_8888;
        break;
    case QImage::Format_ARGB32:
        format = VG_sARGB_8888;
        break;
    case QImage::Format_ARGB32_Premultiplied:
        format = VG_sARGB_8888_PRE;
        break;
    case QImage::Format_RGB16:
        format = VG_sRGB_565;
        bpp = 2;
        break;
    default:
        // Convert everything else into ARGB32_Premultiplied.
        img = image.convertToFormat(QImage::Format_ARGB32_Premultiplied, flags);
        format = VG_sARGB_8888_PRE;
        break;
    }

    const uchar *pixels = img.bits() + bpp * sr.x() +
                          img.bytesPerLine() * sr.y();

    VGImage vgImg = QVGImagePool::instance()->createPermanentImage
        (format, sr.width(), sr.height(), VG_IMAGE_QUALITY_FASTER);
    vgImageSubData
        (vgImg, pixels, img.bytesPerLine(), format, 0, 0,
         sr.width(), sr.height());

    return vgImg;
}

static VGImage toVGImageWithOpacity(const QImage & image, qreal opacity)
{
    QImage img(image.size(), QImage::Format_ARGB32_Premultiplied);
    img.fill(0);
    QPainter painter;
    painter.begin(&img);
    painter.setOpacity(opacity);
    painter.drawImage(0, 0, image);
    painter.end();

    const uchar *pixels = img.bits();

    VGImage vgImg = QVGImagePool::instance()->createPermanentImage
        (VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
    vgImageSubData
        (vgImg, pixels, img.bytesPerLine(), VG_sARGB_8888_PRE, 0, 0,
         img.width(), img.height());

    return vgImg;
}

static VGImage toVGImageWithOpacitySubRect
    (const QImage & image, qreal opacity, const QRect& sr)
{
    QImage img(sr.size(), QImage::Format_ARGB32_Premultiplied);
    img.fill(0);
    QPainter painter;
    painter.begin(&img);
    painter.setOpacity(opacity);
    painter.drawImage(QPoint(0, 0), image, sr);
    painter.end();

    const uchar *pixels = img.bits();

    VGImage vgImg = QVGImagePool::instance()->createPermanentImage
        (VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
    vgImageSubData
        (vgImg, pixels, img.bytesPerLine(), VG_sARGB_8888_PRE, 0, 0,
         img.width(), img.height());

    return vgImg;
}

VGPaintType QVGPaintEnginePrivate::setBrush
        (VGPaint paint, const QBrush& brush, VGMatrixMode mode,
         VGPaintType prevType)
{
    VGfloat values[5];
    setBrushTransform(brush, mode);

    // Reset the paint pattern on the brush, which will discard
    // the previous VGImage if one was set.
    if (prevType == VG_PAINT_TYPE_PATTERN || prevType == (VGPaintType)0)
        vgPaintPattern(paint, VG_INVALID_HANDLE);

    switch (brush.style()) {

    case Qt::SolidPattern: {
        // The brush is a solid color.
        QColor color(brush.color());
        values[0] = color.redF();
        values[1] = color.greenF();
        values[2] = color.blueF();
        values[3] = color.alphaF() * opacity;
        if (prevType != VG_PAINT_TYPE_COLOR)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
        vgSetParameterfv(paint, VG_PAINT_COLOR, 4, values);
        return VG_PAINT_TYPE_COLOR;
    }

    case Qt::LinearGradientPattern: {
        // The brush is a linear gradient.
        Q_ASSERT(brush.gradient()->type() == QGradient::LinearGradient);
        const QLinearGradient *grad =
            static_cast<const QLinearGradient*>(brush.gradient());
        values[0] = grad->start().x();
        values[1] = grad->start().y();
        values[2] = grad->finalStop().x();
        values[3] = grad->finalStop().y();
        if (prevType != VG_PAINT_TYPE_LINEAR_GRADIENT)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_LINEAR_GRADIENT);
        vgSetParameterfv(paint, VG_PAINT_LINEAR_GRADIENT, 4, values);
        setupColorRamp(grad, paint);
        return VG_PAINT_TYPE_LINEAR_GRADIENT;
    }

    case Qt::RadialGradientPattern: {
        // The brush is a radial gradient.
        Q_ASSERT(brush.gradient()->type() == QGradient::RadialGradient);
        const QRadialGradient *grad =
            static_cast<const QRadialGradient*>(brush.gradient());
        values[0] = grad->center().x();
        values[1] = grad->center().y();
        values[2] = grad->focalPoint().x();
        values[3] = grad->focalPoint().y();
        values[4] = grad->radius();
        if (prevType != VG_PAINT_TYPE_RADIAL_GRADIENT)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_RADIAL_GRADIENT);
        vgSetParameterfv(paint, VG_PAINT_RADIAL_GRADIENT, 5, values);
        setupColorRamp(grad, paint);
        return VG_PAINT_TYPE_RADIAL_GRADIENT;
    }

    case Qt::TexturePattern: {
        // The brush is a texture specified by a QPixmap/QImage.
        QPixmapData *pd = brush.texture().pixmapData();
        if (!pd)
            break;  // null QPixmap
        VGImage vgImg;
        bool deref = false;
        if (pd->pixelType() == QPixmapData::BitmapType) {
            // Colorize bitmaps using the brush color and opacity.
            QColor color = brush.color();
            if (opacity != 1.0)
                color.setAlphaF(color.alphaF() * opacity);
            QImage image = colorizeBitmap(*(pd->buffer()), color);
            vgImg = toVGImage(image);
            deref = true;
        } else if (opacity == 1.0) {
            if (pd->classId() == QPixmapData::OpenVGClass) {
                QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
                vgImg = vgpd->toVGImage();

                // We don't want the pool to reclaim this image
                // because we cannot predict when the paint object
                // will stop using it.  Replacing the image with
                // new data will make the paint object invalid.
                vgpd->detachImageFromPool();
            } else {
                vgImg = toVGImage(*(pd->buffer()));
                deref = true;
            }
        } else if (pd->classId() == QPixmapData::OpenVGClass) {
            QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
            vgImg = vgpd->toVGImage(opacity);
            vgpd->detachImageFromPool();
        } else {
            vgImg = toVGImageWithOpacity(*(pd->buffer()), opacity);
            deref = true;
        }
        if (vgImg == VG_INVALID_HANDLE)
            break;
        if (prevType != VG_PAINT_TYPE_PATTERN)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_PATTERN);
        vgSetParameteri(paint, VG_PAINT_PATTERN_TILING_MODE, VG_TILE_REPEAT);
        vgPaintPattern(paint, vgImg);
        if (deref)
            vgDestroyImage(vgImg); // Will be valid until pattern is destroyed.
        return VG_PAINT_TYPE_PATTERN;
    }

    case Qt::ConicalGradientPattern: {
        // Convert conical gradients into the first stop color.
        qWarning() << "QVGPaintEnginePrivate::setBrush: conical gradients are not supported by OpenVG";
        Q_ASSERT(brush.gradient()->type() == QGradient::ConicalGradient);
        const QConicalGradient *grad =
            static_cast<const QConicalGradient*>(brush.gradient());
        const QGradientStops stops = grad->stops();
        QColor color;
        if (stops.size() > 0)
            color = stops[0].second;
        values[0] = color.redF();
        values[1] = color.greenF();
        values[2] = color.blueF();
        values[3] = color.alphaF() * opacity;
        if (prevType != VG_PAINT_TYPE_COLOR)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
        vgSetParameterfv(paint, VG_PAINT_COLOR, 4, values);
        return VG_PAINT_TYPE_COLOR;
    }

    case Qt::Dense1Pattern:
    case Qt::Dense2Pattern:
    case Qt::Dense3Pattern:
    case Qt::Dense4Pattern:
    case Qt::Dense5Pattern:
    case Qt::Dense6Pattern:
    case Qt::Dense7Pattern:
    case Qt::HorPattern:
    case Qt::VerPattern:
    case Qt::CrossPattern:
    case Qt::BDiagPattern:
    case Qt::FDiagPattern:
    case Qt::DiagCrossPattern: {
        // The brush is a traditional dotted or cross-hatched pattern brush.
        QColor color = brush.color();
        if (opacity != 1.0)
            color.setAlphaF(color.alphaF() * opacity);
        QImage image = colorizeBitmap
            (qt_imageForBrush(brush.style(), true), color);
        VGImage vgImg = toVGImage(image);
        if (prevType != VG_PAINT_TYPE_PATTERN)
            vgSetParameteri(paint, VG_PAINT_TYPE, VG_PAINT_TYPE_PATTERN);
        vgSetParameteri(paint, VG_PAINT_PATTERN_TILING_MODE, VG_TILE_REPEAT);
        vgPaintPattern(paint, vgImg);
        vgDestroyImage(vgImg); // Will stay valid until pattern is destroyed.
        return VG_PAINT_TYPE_PATTERN;
    }

    default: break;
    }
    return (VGPaintType)0;
}

void QVGPaintEnginePrivate::setPenParams(const QPen& pen)
{
    // Note: OpenVG does not support zero-width or cosmetic pens,
    // so we have to simulate cosmetic pens by reversing the scale.
    VGfloat width = pen.widthF();
    if (width <= 0.0f)
        width = 1.0f;
    if (pen.isCosmetic()) {
        if (penScale != 1.0 && penScale != 0.0)
            width /= penScale;
    }
    vgSetf(VG_STROKE_LINE_WIDTH, width);

    if (pen.capStyle() == Qt::FlatCap)
        vgSetf(VG_STROKE_CAP_STYLE, VG_CAP_BUTT);
    else if (pen.capStyle() == Qt::SquareCap)
        vgSetf(VG_STROKE_CAP_STYLE, VG_CAP_SQUARE);
    else
        vgSetf(VG_STROKE_CAP_STYLE, VG_CAP_ROUND);

    if (pen.joinStyle() == Qt::MiterJoin) {
        vgSetf(VG_STROKE_JOIN_STYLE, VG_JOIN_MITER);
        vgSetf(VG_STROKE_MITER_LIMIT, pen.miterLimit());
    } else if (pen.joinStyle() == Qt::BevelJoin) {
        vgSetf(VG_STROKE_JOIN_STYLE, VG_JOIN_BEVEL);
    } else {
        vgSetf(VG_STROKE_JOIN_STYLE, VG_JOIN_ROUND);
    }

    if (pen.style() == Qt::SolidLine) {
        vgSetfv(VG_STROKE_DASH_PATTERN, 0, NULL);
    } else {
        const QVector<qreal> dashPattern = pen.dashPattern();
        QVector<VGfloat> currentDashPattern(dashPattern.count());
        for (int i = 0; i < dashPattern.count(); ++i)
            currentDashPattern[i] = dashPattern[i] * width;
        vgSetfv(VG_STROKE_DASH_PATTERN, currentDashPattern.count(), currentDashPattern.data());
        vgSetf(VG_STROKE_DASH_PHASE, pen.dashOffset());
        vgSetf(VG_STROKE_DASH_PHASE_RESET, VG_FALSE);
    }
}

void QVGPaintEnginePrivate::setBrushTransform
        (const QBrush& brush, VGMatrixMode mode)
{
    // Compute the new brush transformation matrix.
    QTransform transform(brush.transform());
    if (brushOrigin.x() != 0.0f || brushOrigin.y() != 0.0f)
        transform.translate(brushOrigin.x(), brushOrigin.y());

    // Bail out if the matrix is the same as last time, to avoid
    // updating the VG context state unless absolutely necessary.
    // Most applications won't have a brush transformation set,
    // which will leave the VG setting at its default of identity.
    // Always change the transform if coming out of raw VG mode.
    if (mode == VG_MATRIX_FILL_PAINT_TO_USER) {
        if (!rawVG && transform == brushTransform)
            return;
        brushTransform = transform;
    } else {
        if (!rawVG && transform == penTransform)
            return;
        penTransform = transform;
    }

    // Set the brush transformation matrix.
    if (mode != matrixMode) {
        vgSeti(VG_MATRIX_MODE, mode);
        matrixMode = mode;
    }
    if (transform.isIdentity()) {
        vgLoadIdentity();
    } else {
        VGfloat mat[9];
        mat[0] = transform.m11();
        mat[1] = transform.m12();
        mat[2] = transform.m13();
        mat[3] = transform.m21();
        mat[4] = transform.m22();
        mat[5] = transform.m23();
        mat[6] = transform.m31();
        mat[7] = transform.m32();
        mat[8] = transform.m33();
        vgLoadMatrix(mat);
    }
}

void QVGPaintEnginePrivate::setupColorRamp(const QGradient *grad, VGPaint paint)
{
    QGradient::Spread spread = grad->spread();
    VGColorRampSpreadMode spreadMode;
    if (spread == QGradient::ReflectSpread)
        spreadMode = VG_COLOR_RAMP_SPREAD_REFLECT;
    else if (spread == QGradient::RepeatSpread)
        spreadMode = VG_COLOR_RAMP_SPREAD_REPEAT;
    else
        spreadMode = VG_COLOR_RAMP_SPREAD_PAD;

    const QGradientStops stops = grad->stops();
    int n = 5*stops.size();
    QVector<VGfloat> fill_stops(n);

    for (int i = 0; i < stops.size(); ++i ) {
        QColor col = stops[i].second;
        fill_stops[i*5] = stops[i].first;
        fill_stops[i*5 + 1] = col.redF();
        fill_stops[i*5 + 2] = col.greenF();
        fill_stops[i*5 + 3] = col.blueF();
        fill_stops[i*5 + 4] = col.alphaF() * opacity;
    }

    vgSetParameteri(paint, VG_PAINT_COLOR_RAMP_SPREAD_MODE, spreadMode);
    vgSetParameteri(paint, VG_PAINT_COLOR_RAMP_PREMULTIPLIED, VG_FALSE);
    vgSetParameterfv(paint, VG_PAINT_COLOR_RAMP_STOPS, n, fill_stops.data());
}

QVGPainterState::QVGPainterState(QVGPainterState& other)
    : QPainterState(other),
      isNew(true), clipRegion(other.clipRegion),
      savedDirty(0)
{
}

QVGPainterState::QVGPainterState()
    : isNew(true), savedDirty(0)
{
}

QVGPainterState::~QVGPainterState()
{
}

QVGPaintEngine::QVGPaintEngine()
    : QPaintEngineEx(*new QVGPaintEnginePrivate)
{
}

QVGPaintEngine::QVGPaintEngine(QVGPaintEnginePrivate &data)
    : QPaintEngineEx(data)
{
}

QVGPaintEngine::~QVGPaintEngine()
{
}

QPainterState *QVGPaintEngine::createState(QPainterState *orig) const
{
    if (!orig) {
        return new QVGPainterState();
    } else {
        Q_D(const QVGPaintEngine);
        QVGPaintEnginePrivate *d2 = const_cast<QVGPaintEnginePrivate*>(d);
        QVGPainterState *origState = static_cast<QVGPainterState *>(orig);
        origState->savedDirty = d2->dirty;
        d2->dirty = 0;
        return new QVGPainterState(*origState);
    }
}

void QVGPaintEnginePrivate::draw
    (VGPath path, const QPen& pen, const QBrush& brush, VGint rule)
{
    VGbitfield mode = 0;
    if (pen.style() != Qt::NoPen) {
        ensurePen(pen);
        mode |= VG_STROKE_PATH;
    }
    if (brush.style() != Qt::NoBrush) {
        ensureBrush(brush);
        setFillRule(rule);
        mode |= VG_FILL_PATH;
    }
    if (mode != 0) {
        ensurePathTransform();
        vgDrawPath(path, mode);
    }
}

void QVGPaintEnginePrivate::stroke(VGPath path, const QPen& pen)
{
    if (pen.style() == Qt::NoPen)
        return;
    ensurePen(pen);
    ensurePathTransform();
    vgDrawPath(path, VG_STROKE_PATH);
}

void QVGPaintEnginePrivate::fill(VGPath path, const QBrush& brush, VGint rule)
{
    if (brush.style() == Qt::NoBrush)
        return;
    ensureBrush(brush);
    setFillRule(rule);
    ensurePathTransform();
    vgDrawPath(path, VG_FILL_PATH);
}

bool QVGPaintEngine::begin(QPaintDevice *pdev)
{
    Q_UNUSED(pdev);
    Q_D(QVGPaintEngine);

    // Initialize the VG painting objects if we haven't done it yet.
    if (!d->penPaint)
        d->initObjects();

    // The initial clip region is the entire device area.
    QVGPainterState *s = state();
    s->clipRegion = defaultClipRegion();

    // Initialize the VG state for this paint operation.
    restoreState(QPaintEngine::AllDirty);
    d->dirty = 0;
    d->rawVG = false;
    return true;
}

bool QVGPaintEngine::end()
{
    return true;
}

void QVGPaintEngine::draw(const QVectorPath &path)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    VGPath vgpath = d->vectorPathToVGPath(path);
    if (!path.hasWindingFill())
        d->draw(vgpath, s->pen, s->brush, VG_EVEN_ODD);
    else
        d->draw(vgpath, s->pen, s->brush, VG_NON_ZERO);
    vgDestroyPath(vgpath);
}

void QVGPaintEngine::fill(const QVectorPath &path, const QBrush &brush)
{
    Q_D(QVGPaintEngine);
    VGPath vgpath = d->vectorPathToVGPath(path);
    if (!path.hasWindingFill())
        d->fill(vgpath, brush, VG_EVEN_ODD);
    else
        d->fill(vgpath, brush, VG_NON_ZERO);
    vgDestroyPath(vgpath);
}

void QVGPaintEngine::stroke(const QVectorPath &path, const QPen &pen)
{
    Q_D(QVGPaintEngine);
    VGPath vgpath = d->vectorPathToVGPath(path);
    d->stroke(vgpath, pen);
    vgDestroyPath(vgpath);
}

// Determine if a co-ordinate transform is simple enough to allow
// rectangle-based clipping with vgMask().  Simple transforms most
// often result from origin translations.
static inline bool clipTransformIsSimple(const QTransform& transform)
{
    QTransform::TransformationType type = transform.type();
    return (type == QTransform::TxNone || type == QTransform::TxTranslate);
}

#if defined(QVG_SCISSOR_CLIP)

void QVGPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();

    d->dirty |= QPaintEngine::DirtyClipRegion;

    if (op == Qt::NoClip) {
        s->clipRegion = defaultClipRegion();
        updateScissor();
        return;
    }

    // We aren't using masking, so handle simple QRectF's only.
    if (path.shape() == QVectorPath::RectangleHint &&
            path.elementCount() == 4 && clipTransformIsSimple(d->transform)) {
        // Clipping region that resulted from QPainter::setClipRect(QRectF).
        // Convert it into a QRect and apply.
        const qreal *points = path.points();
        QRectF rect(points[0], points[1], points[2] - points[0],
                    points[5] - points[1]);
        clip(rect.toRect(), op);
    } else {
        // The best we can do is clip to the bounding rectangle
        // of all control points.
        clip(path.controlPointRect().toRect(), op);
    }
}

void QVGPaintEngine::clip(const QRect &rect, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();

    d->dirty |= QPaintEngine::DirtyClipRegion;

    switch (op) {
        case Qt::NoClip:
        {
            s->clipRegion = defaultClipRegion();
        }
        break;

        case Qt::ReplaceClip:
        {
            s->clipRegion = d->transform.map(QRegion(rect));
        }
        break;

        case Qt::IntersectClip:
        {
            s->clipRegion = s->clipRegion.intersect(d->transform.map(QRegion(rect)));
        }
        break;

        case Qt::UniteClip:
        {
            s->clipRegion = s->clipRegion.unite(d->transform.map(QRegion(rect)));
        }
        break;
    }

    updateScissor();
}

void QVGPaintEngine::clip(const QRegion &region, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();

    d->dirty |= QPaintEngine::DirtyClipRegion;

    switch (op) {
        case Qt::NoClip:
        {
            s->clipRegion = defaultClipRegion();
        }
        break;

        case Qt::ReplaceClip:
        {
            s->clipRegion = d->transform.map(region);
        }
        break;

        case Qt::IntersectClip:
        {
            s->clipRegion = s->clipRegion.intersect(d->transform.map(region));
        }
        break;

        case Qt::UniteClip:
        {
            s->clipRegion = s->clipRegion.unite(d->transform.map(region));
        }
        break;
    }

    updateScissor();
}

void QVGPaintEngine::clip(const QPainterPath &path, Qt::ClipOperation op)
{
    QPaintEngineEx::clip(path, op);
}

#else // !QVG_SCISSOR_CLIP

void QVGPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);

    d->dirty |= QPaintEngine::DirtyClipRegion;

    if (op == Qt::NoClip) {
        d->maskValid = false;
        d->maskIsSet = true;
        d->maskRect = QRect();
        vgSeti(VG_MASKING, VG_FALSE);
        return;
    }

#if defined(QVG_NO_RENDER_TO_MASK)
    // We don't have vgRenderToMask(), so handle simple QRectF's only.
    if (path.shape() == QVectorPath::RectangleHint &&
            path.elementCount() == 4 && clipTransformIsSimple(d->transform)) {
        // Clipping region that resulted from QPainter::setClipRect(QRectF).
        // Convert it into a QRect and apply.
        const qreal *points = path.points();
        QRectF rect(points[0], points[1], points[2] - points[0],
                    points[5] - points[1]);
        clip(rect.toRect(), op);
    }
#else
    QPaintDevice *pdev = paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    if (op == Qt::ReplaceClip) {
        vgMask(VG_INVALID_HANDLE, VG_CLEAR_MASK, 0, 0, width, height);
        d->maskRect = QRect();
    } else if (!d->maskValid) {
        d->ensureMask(this, width, height);
    }

    d->ensurePathTransform();
    VGPath vgpath = d->vectorPathToVGPath(path);
    switch (op) {
        case Qt::ReplaceClip:
        case Qt::UniteClip:
            vgRenderToMask(vgpath, VG_FILL_PATH, VG_UNION_MASK);
            break;

        case Qt::IntersectClip:
            vgRenderToMask(vgpath, VG_FILL_PATH, VG_INTERSECT_MASK);
            break;

        default: break;
    }
    vgDestroyPath(vgpath);

    vgSeti(VG_MASKING, VG_TRUE);
    d->maskValid = true;
    d->maskIsSet = false;
#endif
}

void QVGPaintEngine::clip(const QRect &rect, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);

    d->dirty |= QPaintEngine::DirtyClipRegion;

    // If we have a non-simple transform, then use path-based clipping.
    if (op != Qt::NoClip && !clipTransformIsSimple(d->transform)) {
        QPaintEngineEx::clip(rect, op);
        return;
    }

    switch (op) {
        case Qt::NoClip:
        {
            d->maskValid = false;
            d->maskIsSet = true;
            d->maskRect = QRect();
            vgSeti(VG_MASKING, VG_FALSE);
        }
        break;

        case Qt::ReplaceClip:
        {
            QRect r = d->transform.mapRect(rect);
            if (isDefaultClipRect(r)) {
                // Replacing the clip with a full-window region is the
                // same as turning off clipping.
                if (d->maskValid)
                    vgSeti(VG_MASKING, VG_FALSE);
                d->maskValid = false;
                d->maskIsSet = true;
                d->maskRect = QRect();
            } else {
                // Special case: if the intersection of the system
                // clip and "r" is a single rectangle, then use the
                // scissor for clipping.  We try to avoid allocating a
                // QRegion copy on the heap for the test if we can.
                QRegion clip = d->systemClip; // Reference-counted, no alloc.
                QRect clipRect;
                if (clip.rectCount() == 1) {
                    clipRect = clip.boundingRect().intersected(r);
                } else if (clip.isEmpty()) {
                    clipRect = r;
                } else {
                    clip = clip.intersect(r);
                    if (clip.rectCount() != 1) {
                        d->maskValid = false;
                        d->maskIsSet = false;
                        d->maskRect = QRect();
                        d->modifyMask(this, VG_FILL_MASK, r);
                        break;
                    }
                    clipRect = clip.boundingRect();
                }
                d->maskValid = false;
                d->maskIsSet = false;
                d->maskRect = clipRect;
                vgSeti(VG_MASKING, VG_FALSE);
                updateScissor();
            }
        }
        break;

        case Qt::IntersectClip:
        {
            QRect r = d->transform.mapRect(rect);
            if (d->maskIsSet && isDefaultClipRect(r)) {
                // Intersecting a full-window clip with a full-window
                // region is the same as turning off clipping.
                if (d->maskValid)
                    vgSeti(VG_MASKING, VG_FALSE);
                d->maskValid = false;
                d->maskIsSet = true;
                d->maskRect = QRect();
            } else {
                d->modifyMask(this, VG_INTERSECT_MASK, r);
            }
        }
        break;

        case Qt::UniteClip:
        {
            // If we already have a full-window clip, then uniting a
            // region with it will do nothing.  Otherwise union.
            if (!(d->maskIsSet))
                d->modifyMask(this, VG_UNION_MASK, d->transform.mapRect(rect));
        }
        break;
    }
}

void QVGPaintEngine::clip(const QRegion &region, Qt::ClipOperation op)
{
    Q_D(QVGPaintEngine);

    // Use the QRect case if the region consists of a single rectangle.
    if (region.rectCount() == 1) {
        clip(region.boundingRect(), op);
        return;
    }

    d->dirty |= QPaintEngine::DirtyClipRegion;

    // If we have a non-simple transform, then use path-based clipping.
    if (op != Qt::NoClip && !clipTransformIsSimple(d->transform)) {
        QPaintEngineEx::clip(region, op);
        return;
    }

    switch (op) {
        case Qt::NoClip:
        {
            d->maskValid = false;
            d->maskIsSet = true;
            d->maskRect = QRect();
            vgSeti(VG_MASKING, VG_FALSE);
        }
        break;

        case Qt::ReplaceClip:
        {
            QRegion r = d->transform.map(region);
            if (isDefaultClipRegion(r)) {
                // Replacing the clip with a full-window region is the
                // same as turning off clipping.
                if (d->maskValid)
                    vgSeti(VG_MASKING, VG_FALSE);
                d->maskValid = false;
                d->maskIsSet = true;
                d->maskRect = QRect();
            } else {
                // Special case: if the intersection of the system
                // clip and the region is a single rectangle, then
                // use the scissor for clipping.
                QRegion clip = d->systemClip;
                if (clip.isEmpty())
                    clip = r;
                else
                    clip = clip.intersect(r);
                if (clip.rectCount() == 1) {
                    d->maskValid = false;
                    d->maskIsSet = false;
                    d->maskRect = clip.boundingRect();
                    vgSeti(VG_MASKING, VG_FALSE);
                    updateScissor();
                } else {
                    d->maskValid = false;
                    d->maskIsSet = false;
                    d->maskRect = QRect();
                    d->modifyMask(this, VG_FILL_MASK, r);
                }
            }
        }
        break;

        case Qt::IntersectClip:
        {
            if (region.rectCount() != 1) {
                // If there is more than one rectangle, then intersecting
                // the rectangles one by one in modifyMask() will not give
                // the desired result.  So fall back to path-based clipping.
                QPaintEngineEx::clip(region, op);
                return;
            }
            QRegion r = d->transform.map(region);
            if (d->maskIsSet && isDefaultClipRegion(r)) {
                // Intersecting a full-window clip with a full-window
                // region is the same as turning off clipping.
                if (d->maskValid)
                    vgSeti(VG_MASKING, VG_FALSE);
                d->maskValid = false;
                d->maskIsSet = true;
                d->maskRect = QRect();
            } else {
                d->modifyMask(this, VG_INTERSECT_MASK, r);
            }
        }
        break;

        case Qt::UniteClip:
        {
            // If we already have a full-window clip, then uniting a
            // region with it will do nothing.  Otherwise union.
            if (!(d->maskIsSet))
                d->modifyMask(this, VG_UNION_MASK, d->transform.map(region));
        }
        break;
    }
}

#if !defined(QVG_NO_RENDER_TO_MASK)

// Copied from qpathclipper.cpp.
static bool qt_vg_pathToRect(const QPainterPath &path, QRectF *rect)
{
    if (path.elementCount() != 5)
        return false;

    const bool mightBeRect = path.elementAt(0).isMoveTo()
        && path.elementAt(1).isLineTo()
        && path.elementAt(2).isLineTo()
        && path.elementAt(3).isLineTo()
        && path.elementAt(4).isLineTo();

    if (!mightBeRect)
        return false;

    const qreal x1 = path.elementAt(0).x;
    const qreal y1 = path.elementAt(0).y;

    const qreal x2 = path.elementAt(1).x;
    const qreal y2 = path.elementAt(2).y;

    if (path.elementAt(1).y != y1)
        return false;

    if (path.elementAt(2).x != x2)
        return false;

    if (path.elementAt(3).x != x1 || path.elementAt(3).y != y2)
        return false;

    if (path.elementAt(4).x != x1 || path.elementAt(4).y != y1)
        return false;

    if (rect)
        *rect = QRectF(QPointF(x1, y1), QPointF(x2, y2));

    return true;
}

#endif

void QVGPaintEngine::clip(const QPainterPath &path, Qt::ClipOperation op)
{
#if !defined(QVG_NO_RENDER_TO_MASK)
    Q_D(QVGPaintEngine);

    // If the path is a simple rectangle, then use clip(QRect) instead.
    QRectF simpleRect;
    if (qt_vg_pathToRect(path, &simpleRect)) {
        clip(simpleRect.toRect(), op);
        return;
    }

    d->dirty |= QPaintEngine::DirtyClipRegion;

    if (op == Qt::NoClip) {
        d->maskValid = false;
        d->maskIsSet = true;
        d->maskRect = QRect();
        vgSeti(VG_MASKING, VG_FALSE);
        return;
    }

    QPaintDevice *pdev = paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    if (op == Qt::ReplaceClip) {
        vgMask(VG_INVALID_HANDLE, VG_CLEAR_MASK, 0, 0, width, height);
        d->maskRect = QRect();
    } else if (!d->maskValid) {
        d->ensureMask(this, width, height);
    }

    d->ensurePathTransform();
    VGPath vgpath = d->painterPathToVGPath(path);
    switch (op) {
        case Qt::ReplaceClip:
        case Qt::UniteClip:
            vgRenderToMask(vgpath, VG_FILL_PATH, VG_UNION_MASK);
            break;

        case Qt::IntersectClip:
            vgRenderToMask(vgpath, VG_FILL_PATH, VG_INTERSECT_MASK);
            break;

        default: break;
    }
    vgDestroyPath(vgpath);

    vgSeti(VG_MASKING, VG_TRUE);
    d->maskValid = true;
    d->maskIsSet = false;
#else
    QPaintEngineEx::clip(path, op);
#endif
}

void QVGPaintEnginePrivate::ensureMask
        (QVGPaintEngine *engine, int width, int height)
{
    if (maskIsSet) {
        vgMask(VG_INVALID_HANDLE, VG_FILL_MASK, 0, 0, width, height);
        maskRect = QRect();
    } else {
        vgMask(VG_INVALID_HANDLE, VG_CLEAR_MASK, 0, 0, width, height);
        if (maskRect.isValid()) {
            vgMask(VG_INVALID_HANDLE, VG_FILL_MASK,
                   maskRect.x(), height - maskRect.y() - maskRect.height(),
                   maskRect.width(), maskRect.height());
            maskRect = QRect();
            engine->updateScissor();
        }
    }
}

void QVGPaintEnginePrivate::modifyMask
        (QVGPaintEngine *engine, VGMaskOperation op, const QRegion& region)
{
    QPaintDevice *pdev = engine->paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    if (!maskValid)
        ensureMask(engine, width, height);

    QVector<QRect> rects = region.rects();
    for (int i = 0; i < rects.size(); ++i) {
        vgMask(VG_INVALID_HANDLE, op,
               rects[i].x(), height - rects[i].y() - rects[i].height(),
               rects[i].width(), rects[i].height());
    }

    vgSeti(VG_MASKING, VG_TRUE);
    maskValid = true;
    maskIsSet = false;
}

void QVGPaintEnginePrivate::modifyMask
        (QVGPaintEngine *engine, VGMaskOperation op, const QRect& rect)
{
    QPaintDevice *pdev = engine->paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    if (!maskValid)
        ensureMask(engine, width, height);

    if (rect.isValid()) {
        vgMask(VG_INVALID_HANDLE, op,
               rect.x(), height - rect.y() - rect.height(),
               rect.width(), rect.height());
    }

    vgSeti(VG_MASKING, VG_TRUE);
    maskValid = true;
    maskIsSet = false;
}

#endif // !QVG_SCISSOR_CLIP

void QVGPaintEngine::updateScissor()
{
    Q_D(QVGPaintEngine);

    QRegion region = d->systemClip;

#if defined(QVG_SCISSOR_CLIP)
    // Using the scissor to do clipping, so combine the systemClip
    // with the current painting clipRegion.
    QVGPainterState *s = state();
    if (s->clipEnabled) {
        if (region.isEmpty())
            region = s->clipRegion;
        else
            region = region.intersect(s->clipRegion);
        if (isDefaultClipRegion(region)) {
            // The scissor region is the entire drawing surface,
            // so there is no point doing any scissoring.
            vgSeti(VG_SCISSORING, VG_FALSE);
            d->scissorActive = false;
            return;
        }
    } else
#endif
    {
#if !defined(QVG_SCISSOR_CLIP)
        // Combine the system clip with the simple mask rectangle.
        if (!d->maskRect.isNull()) {
            if (region.isEmpty())
                region = d->maskRect;
            else
                region = region.intersect(d->maskRect);
            if (isDefaultClipRegion(region)) {
                // The scissor region is the entire drawing surface,
                // so there is no point doing any scissoring.
                vgSeti(VG_SCISSORING, VG_FALSE);
                d->scissorActive = false;
                return;
            }
        } else
#endif

        // Disable the scissor completely if the system clip is empty.
        if (region.isEmpty()) {
            vgSeti(VG_SCISSORING, VG_FALSE);
            d->scissorActive = false;
            return;
        }
    }

    if (d->scissorActive && region == d->scissorRegion)
        return;

    QVector<QRect> rects = region.rects();
    int count = rects.count();
    if (count > d->maxScissorRects)
        count = d->maxScissorRects;
    QVarLengthArray<VGint> params(count * 4);
    int height = paintDevice()->height();
    for (int i = 0; i < count; ++i) {
        params[i * 4 + 0] = rects[i].x();
        params[i * 4 + 1] = height - rects[i].y() - rects[i].height();
        params[i * 4 + 2] = rects[i].width();
        params[i * 4 + 3] = rects[i].height();
    }

    vgSetiv(VG_SCISSOR_RECTS, count * 4, params.data());
    vgSeti(VG_SCISSORING, VG_TRUE);
    d->scissorActive = true;
    d->scissorRegion = region;
}

QRegion QVGPaintEngine::defaultClipRegion()
{
    // The default clip region for a paint device is the whole drawing area.
    QPaintDevice *pdev = paintDevice();
    return QRegion(0, 0, pdev->width(), pdev->height());
}

bool QVGPaintEngine::isDefaultClipRegion(const QRegion& region)
{
    if (region.rectCount() != 1)
        return false;

    QPaintDevice *pdev = paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    QRect rect = region.boundingRect();
    return (rect.x() == 0 && rect.y() == 0 &&
            rect.width() == width && rect.height() == height);
}

bool QVGPaintEngine::isDefaultClipRect(const QRect& rect)
{
    QPaintDevice *pdev = paintDevice();
    int width = pdev->width();
    int height = pdev->height();

    return (rect.x() == 0 && rect.y() == 0 &&
            rect.width() == width && rect.height() == height);
}

void QVGPaintEngine::clipEnabledChanged()
{
#if defined(QVG_SCISSOR_CLIP)
    updateScissor();
#else
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    d->dirty |= QPaintEngine::DirtyClipEnabled;
    if (s->clipEnabled && s->clipOperation != Qt::NoClip) {
        // Replay the entire clip stack to put the mask into the right state.
        d->maskValid = false;
        d->maskIsSet = true;
        d->maskRect = QRect();
        s->clipRegion = defaultClipRegion();
        d->replayClipOperations();
        d->transform = s->transform();
        d->updateTransform(paintDevice());
    } else {
        vgSeti(VG_MASKING, VG_FALSE);
        d->maskValid = false;
        d->maskIsSet = false;
        d->maskRect = QRect();
    }
#endif
}

void QVGPaintEngine::penChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyPen;
}

void QVGPaintEngine::brushChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyBrush;
}

void QVGPaintEngine::brushOriginChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyBrushOrigin;
    d->brushOrigin = state()->brushOrigin;
    d->forcePenChange = true;
    d->forceBrushChange = true;
}

void QVGPaintEngine::opacityChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyOpacity;
    d->opacity = state()->opacity;
    d->forcePenChange = true;
    d->forceBrushChange = true;
}

void QVGPaintEngine::compositionModeChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyCompositionMode;

    VGBlendMode vgMode = VG_BLEND_SRC_OVER;

    switch (state()->composition_mode) {
    case QPainter::CompositionMode_SourceOver:
        vgMode = VG_BLEND_SRC_OVER;
        break;
    case QPainter::CompositionMode_DestinationOver:
        vgMode = VG_BLEND_DST_OVER;
        break;
    case QPainter::CompositionMode_Source:
        vgMode = VG_BLEND_SRC;
        break;
    case QPainter::CompositionMode_SourceIn:
        vgMode = VG_BLEND_SRC_IN;
        break;
    case QPainter::CompositionMode_DestinationIn:
        vgMode = VG_BLEND_DST_IN;
        break;
    case QPainter::CompositionMode_Plus:
        vgMode = VG_BLEND_ADDITIVE;
        break;
    case QPainter::CompositionMode_Multiply:
        vgMode = VG_BLEND_MULTIPLY;
        break;
    case QPainter::CompositionMode_Screen:
        vgMode = VG_BLEND_SCREEN;
        break;
    case QPainter::CompositionMode_Darken:
        vgMode = VG_BLEND_DARKEN;
        break;
    case QPainter::CompositionMode_Lighten:
        vgMode = VG_BLEND_LIGHTEN;
        break;
    default:
        qWarning() << "QVGPaintEngine::compositionModeChanged unsupported mode" << state()->composition_mode;
        break;  // Fall back to VG_BLEND_SRC_OVER.
    }

    d->setBlendMode(vgMode);
}

void QVGPaintEngine::renderHintsChanged()
{
    Q_D(QVGPaintEngine);
    d->dirty |= QPaintEngine::DirtyHints;

    QPainter::RenderHints hints = state()->renderHints;

    VGRenderingQuality rq =
            (hints & QPainter::Antialiasing)
                ? VG_RENDERING_QUALITY_BETTER
                : VG_RENDERING_QUALITY_NONANTIALIASED;
    VGImageQuality iq =
            (hints & QPainter::SmoothPixmapTransform)
                ? VG_IMAGE_QUALITY_BETTER
                : VG_IMAGE_QUALITY_NONANTIALIASED;

    d->setRenderingQuality(rq);
    d->setImageQuality(iq);
}

void QVGPaintEngine::transformChanged()
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    d->dirty |= QPaintEngine::DirtyTransform;
    d->transform = s->transform();
    qreal oldPenScale = d->penScale;
    d->updateTransform(paintDevice());
    if (d->penScale != oldPenScale)
        d->forcePenChange = true;
}

bool QVGPaintEngine::clearRect(const QRectF &rect, const QColor &color)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    if (!s->clipEnabled || s->clipOperation == Qt::NoClip) {
        // The transform will either be identity or a simple translation,
        // so do a simpler version of "r = d->transform.map(rect).toRect()".
        QRect r = QRect(qRound(rect.x() + d->transform.dx()),
                        qRound(rect.y() + d->transform.dy()),
                        qRound(rect.width()),
                        qRound(rect.height()));
        int height = paintDevice()->height();
        if (d->clearColor != color || d->clearOpacity != s->opacity) {
            VGfloat values[4];
            values[0] = color.redF();
            values[1] = color.greenF();
            values[2] = color.blueF();
            values[3] = color.alphaF() * s->opacity;
            vgSetfv(VG_CLEAR_COLOR, 4, values);
            d->clearColor = color;
            d->clearOpacity = s->opacity;
        }
        vgClear(r.x(), height - r.y() - r.height(),
                r.width(), r.height());
        return true;
    }
    return false;
}

void QVGPaintEngine::fillRect(const QRectF &rect, const QBrush &brush)
{
    Q_D(QVGPaintEngine);

    if (brush.style() == Qt::NoBrush)
        return;

    // Check to see if we can use vgClear() for faster filling.
    if (brush.style() == Qt::SolidPattern &&
            clipTransformIsSimple(d->transform) && d->opacity == 1.0f &&
            clearRect(rect, brush.color())) {
        return;
    }

#if !defined(QVG_NO_MODIFY_PATH)
    VGfloat coords[8];
    if (d->simpleTransform) {
        coords[0] = rect.x();
        coords[1] = rect.y();
        coords[2] = rect.x() + rect.width();
        coords[3] = coords[1];
        coords[4] = coords[2];
        coords[5] = rect.y() + rect.height();
        coords[6] = coords[0];
        coords[7] = coords[5];
    } else {
        QPointF tl = d->transform.map(rect.topLeft());
        QPointF tr = d->transform.map(rect.topRight());
        QPointF bl = d->transform.map(rect.bottomLeft());
        QPointF br = d->transform.map(rect.bottomRight());
        coords[0] = tl.x();
        coords[1] = tl.y();
        coords[2] = tr.x();
        coords[3] = tr.y();
        coords[4] = br.x();
        coords[5] = br.y();
        coords[6] = bl.x();
        coords[7] = bl.y();
    }
    vgModifyPathCoords(d->rectPath, 0, 4, coords);
    d->fill(d->rectPath, brush);
#else
    QPaintEngineEx::fillRect(rect, brush);
#endif
}

void QVGPaintEngine::fillRect(const QRectF &rect, const QColor &color)
{
    Q_D(QVGPaintEngine);

    // Check to see if we can use vgClear() for faster filling.
    if (clipTransformIsSimple(d->transform) && d->opacity == 1.0f &&
            clearRect(rect, color)) {
        return;
    }

#if !defined(QVG_NO_MODIFY_PATH)
    VGfloat coords[8];
    if (d->simpleTransform) {
        coords[0] = rect.x();
        coords[1] = rect.y();
        coords[2] = rect.x() + rect.width();
        coords[3] = coords[1];
        coords[4] = coords[2];
        coords[5] = rect.y() + rect.height();
        coords[6] = coords[0];
        coords[7] = coords[5];
    } else {
        QPointF tl = d->transform.map(rect.topLeft());
        QPointF tr = d->transform.map(rect.topRight());
        QPointF bl = d->transform.map(rect.bottomLeft());
        QPointF br = d->transform.map(rect.bottomRight());
        coords[0] = tl.x();
        coords[1] = tl.y();
        coords[2] = tr.x();
        coords[3] = tr.y();
        coords[4] = br.x();
        coords[5] = br.y();
        coords[6] = bl.x();
        coords[7] = bl.y();
    }
    vgModifyPathCoords(d->rectPath, 0, 4, coords);
    d->fill(d->rectPath, QBrush(color));
#else
    QPaintEngineEx::fillRect(rect, QBrush(color));
#endif
}

void QVGPaintEngine::drawRoundedRect(const QRectF &rect, qreal xrad, qreal yrad, Qt::SizeMode mode)
{
    Q_D(QVGPaintEngine);
    if (d->simpleTransform) {
        QVGPainterState *s = state();
        VGPath vgpath = d->roundedRectPath(rect, xrad, yrad, mode);
        d->draw(vgpath, s->pen, s->brush);
#if defined(QVG_NO_MODIFY_PATH)
        vgDestroyPath(vgpath);
#endif
    } else {
        QPaintEngineEx::drawRoundedRect(rect, xrad, yrad, mode);
    }
}

void QVGPaintEngine::drawRects(const QRect *rects, int rectCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    for (int i = 0; i < rectCount; ++i, ++rects) {
        VGfloat coords[8];
        if (d->simpleTransform) {
            coords[0] = rects->x();
            coords[1] = rects->y();
            coords[2] = rects->x() + rects->width();
            coords[3] = coords[1];
            coords[4] = coords[2];
            coords[5] = rects->y() + rects->height();
            coords[6] = coords[0];
            coords[7] = coords[5];
        } else {
            QPointF tl = d->transform.map(QPointF(rects->x(), rects->y()));
            QPointF tr = d->transform.map(QPointF(rects->x() + rects->width(),
                                                  rects->y()));
            QPointF bl = d->transform.map(QPointF(rects->x(),
                                                  rects->y() + rects->height()));
            QPointF br = d->transform.map(QPointF(rects->x() + rects->width(),
                                                  rects->y() + rects->height()));
            coords[0] = tl.x();
            coords[1] = tl.y();
            coords[2] = tr.x();
            coords[3] = tr.y();
            coords[4] = br.x();
            coords[5] = br.y();
            coords[6] = bl.x();
            coords[7] = bl.y();
        }
        vgModifyPathCoords(d->rectPath, 0, 4, coords);
        d->draw(d->rectPath, s->pen, s->brush);
    }
#else
    QPaintEngineEx::drawRects(rects, rectCount);
#endif
}

void QVGPaintEngine::drawRects(const QRectF *rects, int rectCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    for (int i = 0; i < rectCount; ++i, ++rects) {
        VGfloat coords[8];
        if (d->simpleTransform) {
            coords[0] = rects->x();
            coords[1] = rects->y();
            coords[2] = rects->x() + rects->width();
            coords[3] = coords[1];
            coords[4] = coords[2];
            coords[5] = rects->y() + rects->height();
            coords[6] = coords[0];
            coords[7] = coords[5];
        } else {
            QPointF tl = d->transform.map(rects->topLeft());
            QPointF tr = d->transform.map(rects->topRight());
            QPointF bl = d->transform.map(rects->bottomLeft());
            QPointF br = d->transform.map(rects->bottomRight());
            coords[0] = tl.x();
            coords[1] = tl.y();
            coords[2] = tr.x();
            coords[3] = tr.y();
            coords[4] = br.x();
            coords[5] = br.y();
            coords[6] = bl.x();
            coords[7] = bl.y();
        }
        vgModifyPathCoords(d->rectPath, 0, 4, coords);
        d->draw(d->rectPath, s->pen, s->brush);
    }
#else
    QPaintEngineEx::drawRects(rects, rectCount);
#endif
}

void QVGPaintEngine::drawLines(const QLine *lines, int lineCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    for (int i = 0; i < lineCount; ++i, ++lines) {
        VGfloat coords[4];
        if (d->simpleTransform) {
            coords[0] = lines->x1();
            coords[1] = lines->y1();
            coords[2] = lines->x2();
            coords[3] = lines->y2();
        } else {
            QPointF p1 = d->transform.map(QPointF(lines->x1(), lines->y1()));
            QPointF p2 = d->transform.map(QPointF(lines->x2(), lines->y2()));
            coords[0] = p1.x();
            coords[1] = p1.y();
            coords[2] = p2.x();
            coords[3] = p2.y();
        }
        vgModifyPathCoords(d->linePath, 0, 2, coords);
        d->stroke(d->linePath, s->pen);
    }
#else
    QPaintEngineEx::drawLines(lines, lineCount);
#endif
}

void QVGPaintEngine::drawLines(const QLineF *lines, int lineCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    for (int i = 0; i < lineCount; ++i, ++lines) {
        VGfloat coords[4];
        if (d->simpleTransform) {
            coords[0] = lines->x1();
            coords[1] = lines->y1();
            coords[2] = lines->x2();
            coords[3] = lines->y2();
        } else {
            QPointF p1 = d->transform.map(lines->p1());
            QPointF p2 = d->transform.map(lines->p2());
            coords[0] = p1.x();
            coords[1] = p1.y();
            coords[2] = p2.x();
            coords[3] = p2.y();
        }
        vgModifyPathCoords(d->linePath, 0, 2, coords);
        d->stroke(d->linePath, s->pen);
    }
#else
    QPaintEngineEx::drawLines(lines, lineCount);
#endif
}

void QVGPaintEngine::drawEllipse(const QRectF &r)
{
    // Based on the description of vguEllipse() in the OpenVG specification.
    // We don't use vguEllipse(), to avoid unnecessary library dependencies.
    Q_D(QVGPaintEngine);
    if (d->simpleTransform) {
        QVGPainterState *s = state();
        VGPath path = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                                   VG_PATH_DATATYPE_F,
                                   1.0f, // scale
                                   0.0f, // bias
                                   4,    // segmentCapacityHint
                                   12,   // coordCapacityHint
                                   VG_PATH_CAPABILITY_ALL);
        static VGubyte segments[4] = {
            VG_MOVE_TO_ABS,
            VG_SCCWARC_TO_REL,
            VG_SCCWARC_TO_REL,
            VG_CLOSE_PATH
        };
        VGfloat coords[12];
        VGfloat halfwid = r.width() / 2;
        VGfloat halfht = r.height() / 2;
        coords[0]  = r.x() + r.width();
        coords[1]  = r.y() + halfht;
        coords[2]  = halfwid;
        coords[3]  = halfht;
        coords[4]  = 0.0f;
        coords[5]  = -r.width();
        coords[6]  = 0.0f;
        coords[7]  = halfwid;
        coords[8]  = halfht;
        coords[9]  = 0.0f;
        coords[10] = r.width();
        coords[11] = 0.0f;
        vgAppendPathData(path, 4, segments, coords);
        d->draw(path, s->pen, s->brush);
        vgDestroyPath(path);
    } else {
        // The projective transform version of an ellipse is difficult.
        // Generate a QVectorPath containing cubic curves and transform that.
        QPaintEngineEx::drawEllipse(r);
    }
}

void QVGPaintEngine::drawEllipse(const QRect &r)
{
    drawEllipse(QRectF(r));
}

void QVGPaintEngine::drawPath(const QPainterPath &path)
{
    // Shortcut past the QPainterPath -> QVectorPath conversion,
    // converting the QPainterPath directly into a VGPath.
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    VGPath vgpath = d->painterPathToVGPath(path);
    if (path.fillRule() == Qt::OddEvenFill)
        d->draw(vgpath, s->pen, s->brush, VG_EVEN_ODD);
    else
        d->draw(vgpath, s->pen, s->brush, VG_NON_ZERO);
    vgDestroyPath(vgpath);
}

void QVGPaintEngine::drawPoints(const QPointF *points, int pointCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);

    // Set up a new pen if necessary.
    QPen pen = state()->pen;
    if (pen.style() == Qt::NoPen)
        return;
    if (pen.capStyle() == Qt::FlatCap)
        pen.setCapStyle(Qt::SquareCap);

    for (int i = 0; i < pointCount; ++i, ++points) {
        VGfloat coords[4];
        if (d->simpleTransform) {
            coords[0] = points->x();
            coords[1] = points->y();
            coords[2] = coords[0];
            coords[3] = coords[1];
        } else {
            QPointF p = d->transform.map(*points);
            coords[0] = p.x();
            coords[1] = p.y();
            coords[2] = coords[0];
            coords[3] = coords[1];
        }
        vgModifyPathCoords(d->linePath, 0, 2, coords);
        d->stroke(d->linePath, pen);
    }
#else
    QPaintEngineEx::drawPoints(points, pointCount);
#endif
}

void QVGPaintEngine::drawPoints(const QPoint *points, int pointCount)
{
#if !defined(QVG_NO_MODIFY_PATH)
    Q_D(QVGPaintEngine);

    // Set up a new pen if necessary.
    QPen pen = state()->pen;
    if (pen.style() == Qt::NoPen)
        return;
    if (pen.capStyle() == Qt::FlatCap)
        pen.setCapStyle(Qt::SquareCap);

    for (int i = 0; i < pointCount; ++i, ++points) {
        VGfloat coords[4];
        if (d->simpleTransform) {
            coords[0] = points->x();
            coords[1] = points->y();
            coords[2] = coords[0];
            coords[3] = coords[1];
        } else {
            QPointF p = d->transform.map(QPointF(*points));
            coords[0] = p.x();
            coords[1] = p.y();
            coords[2] = coords[0];
            coords[3] = coords[1];
        }
        vgModifyPathCoords(d->linePath, 0, 2, coords);
        d->stroke(d->linePath, pen);
    }
#else
    QPaintEngineEx::drawPoints(points, pointCount);
#endif
}

void QVGPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    VGPath path = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                               VG_PATH_DATATYPE_F,
                               1.0f,             // scale
                               0.0f,             // bias
                               pointCount + 1,   // segmentCapacityHint
                               pointCount * 2,   // coordCapacityHint
                               VG_PATH_CAPABILITY_ALL);
    QVarLengthArray<VGfloat, 16> coords;
    QVarLengthArray<VGubyte, 10> segments;
    for (int i = 0; i < pointCount; ++i, ++points) {
        if (d->simpleTransform) {
            coords.append(points->x());
            coords.append(points->y());
        } else {
            QPointF temp = d->transform.map(*points);
            coords.append(temp.x());
            coords.append(temp.y());
        }
        if (i == 0)
            segments.append(VG_MOVE_TO_ABS);
        else
            segments.append(VG_LINE_TO_ABS);
    }
    if (mode != QPaintEngine::PolylineMode)
        segments.append(VG_CLOSE_PATH);
    vgAppendPathData(path, segments.count(),
                     segments.constData(), coords.constData());
    switch (mode) {
        case QPaintEngine::WindingMode:
            d->draw(path, s->pen, s->brush, VG_NON_ZERO);
            break;

        case QPaintEngine::PolylineMode:
            d->stroke(path, s->pen);
            break;

        default:
            d->draw(path, s->pen, s->brush, VG_EVEN_ODD);
            break;
    }
    vgDestroyPath(path);
}

void QVGPaintEngine::drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
{
    Q_D(QVGPaintEngine);
    QVGPainterState *s = state();
    VGPath path = vgCreatePath(VG_PATH_FORMAT_STANDARD,
                               VG_PATH_DATATYPE_F,
                               1.0f,             // scale
                               0.0f,             // bias
                               pointCount + 1,   // segmentCapacityHint
                               pointCount * 2,   // coordCapacityHint
                               VG_PATH_CAPABILITY_ALL);
    QVarLengthArray<VGfloat, 16> coords;
    QVarLengthArray<VGubyte, 10> segments;
    for (int i = 0; i < pointCount; ++i, ++points) {
        if (d->simpleTransform) {
            coords.append(points->x());
            coords.append(points->y());
        } else {
            QPointF temp = d->transform.map(QPointF(*points));
            coords.append(temp.x());
            coords.append(temp.y());
        }
        if (i == 0)
            segments.append(VG_MOVE_TO_ABS);
        else
            segments.append(VG_LINE_TO_ABS);
    }
    if (mode != QPaintEngine::PolylineMode)
        segments.append(VG_CLOSE_PATH);
    vgAppendPathData(path, segments.count(),
                     segments.constData(), coords.constData());
    switch (mode) {
        case QPaintEngine::WindingMode:
            d->draw(path, s->pen, s->brush, VG_NON_ZERO);
            break;

        case QPaintEngine::PolylineMode:
            d->stroke(path, s->pen);
            break;

        default:
            d->draw(path, s->pen, s->brush, VG_EVEN_ODD);
            break;
    }
    vgDestroyPath(path);
}

void QVGPaintEnginePrivate::setImageOptions()
{
    if (opacity != 1.0f && simpleTransform) {
        if (opacity != paintOpacity) {
            VGfloat values[4];
            values[0] = 1.0f;
            values[1] = 1.0f;
            values[2] = 1.0f;
            values[3] = opacity;
            vgSetParameterfv(opacityPaint, VG_PAINT_COLOR, 4, values);
            paintOpacity = opacity;
        }
        if (fillPaint != opacityPaint) {
            vgSetPaint(opacityPaint, VG_FILL_PATH);
            fillPaint = opacityPaint;
        }
        setImageMode(VG_DRAW_IMAGE_MULTIPLY);
    } else {
        setImageMode(VG_DRAW_IMAGE_NORMAL);
    }
}

static void drawVGImage(QVGPaintEnginePrivate *d,
                        const QRectF& r, VGImage vgImg,
                        const QSize& imageSize, const QRectF& sr)
{
    if (vgImg == VG_INVALID_HANDLE)
        return;
    VGImage child = VG_INVALID_HANDLE;

    if (sr.topLeft().isNull() && sr.size() == imageSize) {
        child = vgImg;
    } else {
        QRect src = sr.toRect();
#if !defined(QT_SHIVAVG)
        child = vgChildImage(vgImg, src.x(), src.y(), src.width(), src.height());
#else
        child = vgImg;  // XXX: ShivaVG doesn't have vgChildImage().
#endif
    }

    QTransform transform(d->imageTransform);
    VGfloat scaleX = sr.width() == 0.0f ? 0.0f : r.width() / sr.width();
    VGfloat scaleY = sr.height() == 0.0f ? 0.0f : r.height() / sr.height();
    transform.translate(r.x(), r.y());
    transform.scale(scaleX, scaleY);
    d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);

    d->setImageOptions();
    vgDrawImage(child);

    if(child != vgImg)
        vgDestroyImage(child);
}

static void drawVGImage(QVGPaintEnginePrivate *d,
                        const QPointF& pos, VGImage vgImg)
{
    if (vgImg == VG_INVALID_HANDLE)
        return;

    QTransform transform(d->imageTransform);
    transform.translate(pos.x(), pos.y());
    d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);

    d->setImageOptions();
    vgDrawImage(vgImg);
}

// Used by qpixmapfilter_vg.cpp to draw filtered VGImage's.
void qt_vg_drawVGImage(QPainter *painter, const QPointF& pos, VGImage vgImg)
{
    QVGPaintEngine *engine =
        static_cast<QVGPaintEngine *>(painter->paintEngine());
    drawVGImage(engine->vgPrivate(), pos, vgImg);
}

// Used by qpixmapfilter_vg.cpp to draw filtered VGImage's as a stencil.
void qt_vg_drawVGImageStencil
    (QPainter *painter, const QPointF& pos, VGImage vgImg, const QBrush& brush)
{
    QVGPaintEngine *engine =
        static_cast<QVGPaintEngine *>(painter->paintEngine());

    QVGPaintEnginePrivate *d = engine->vgPrivate();

    QTransform transform(d->imageTransform);
    transform.translate(pos.x(), pos.y());
    d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);

    d->ensureBrush(brush);
    d->setImageMode(VG_DRAW_IMAGE_STENCIL);
    vgDrawImage(vgImg);
}

void QVGPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
{
    QPixmapData *pd = pm.pixmapData();
    if (!pd)
        return; // null QPixmap
    if (pd->classId() == QPixmapData::OpenVGClass) {
        Q_D(QVGPaintEngine);
        QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
        if (!vgpd->isValid())
            return;
        if (d->simpleTransform)
            drawVGImage(d, r, vgpd->toVGImage(), vgpd->size(), sr);
        else
            drawVGImage(d, r, vgpd->toVGImage(d->opacity), vgpd->size(), sr);
    } else {
        drawImage(r, *(pd->buffer()), sr, Qt::AutoColor);
    }
}

void QVGPaintEngine::drawPixmap(const QPointF &pos, const QPixmap &pm)
{
    QPixmapData *pd = pm.pixmapData();
    if (!pd)
        return; // null QPixmap
    if (pd->classId() == QPixmapData::OpenVGClass) {
        Q_D(QVGPaintEngine);
        QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
        if (!vgpd->isValid())
            return;
        if (d->simpleTransform)
            drawVGImage(d, pos, vgpd->toVGImage());
        else
            drawVGImage(d, pos, vgpd->toVGImage(d->opacity));
    } else {
        drawImage(pos, *(pd->buffer()));
    }
}

void QVGPaintEngine::drawImage
        (const QRectF &r, const QImage &image, const QRectF &sr,
         Qt::ImageConversionFlags flags)
{
    Q_D(QVGPaintEngine);
    VGImage vgImg;
    if (d->simpleTransform || d->opacity == 1.0f)
        vgImg = toVGImageSubRect(image, sr.toRect(), flags);
    else
        vgImg = toVGImageWithOpacitySubRect(image, d->opacity, sr.toRect());
    if (vgImg != VG_INVALID_HANDLE) {
        if (r.size() == sr.size()) {
            drawVGImage(d, r.topLeft(), vgImg);
        } else {
            drawVGImage(d, r, vgImg, sr.size().toSize(),
                        QRectF(QPointF(0, 0), sr.size()));
        }
    } else {
        // Monochrome images need to use the vgChildImage() path.
        vgImg = toVGImage(image, flags);
        drawVGImage(d, r, vgImg, image.size(), sr);
    }
    vgDestroyImage(vgImg);
}

void QVGPaintEngine::drawImage(const QPointF &pos, const QImage &image)
{
    Q_D(QVGPaintEngine);
    VGImage vgImg;
    if (d->simpleTransform || d->opacity == 1.0f)
        vgImg = toVGImage(image);
    else
        vgImg = toVGImageWithOpacity(image, d->opacity);
    drawVGImage(d, pos, vgImg);
    vgDestroyImage(vgImg);
}

void QVGPaintEngine::drawTiledPixmap
        (const QRectF &r, const QPixmap &pixmap, const QPointF &s)
{
    QBrush brush(state()->pen.color(), pixmap);
    QTransform xform;
    xform.translate(-s.x(), -s.y());
    brush.setTransform(xform);
    fillRect(r, brush);
}

// Best performance will be achieved with QDrawPixmaps::OpaqueHint
// (i.e. no opacity), no rotation or scaling, and drawing the full
// pixmap rather than parts of the pixmap.  Even having just one of
// these conditions will improve performance.
void QVGPaintEngine::drawPixmaps
    (const QDrawPixmaps::Data *drawingData, int dataCount,
     const QPixmap &pixmap, QFlags<QDrawPixmaps::DrawingHint> hints)
{
#if !defined(QT_SHIVAVG)
    Q_D(QVGPaintEngine);

    // If the pixmap is not VG, or the transformation is projective,
    // then fall back to the default implementation.
    QPixmapData *pd = pixmap.pixmapData();
    if (!pd)
        return; // null QPixmap
    if (pd->classId() != QPixmapData::OpenVGClass || !d->simpleTransform) {
        QPaintEngineEx::drawPixmaps(drawingData, dataCount, pixmap, hints);
        return;
    }

    // Bail out if nothing to do.
    if (dataCount <= 0)
        return;

    // Bail out if we don't have a usable VGImage for the pixmap.
    QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
    if (!vgpd->isValid())
        return;
    VGImage vgImg = vgpd->toVGImage();
    if (vgImg == VG_INVALID_HANDLE)
        return;

    // We cache the results of any vgChildImage() calls because the
    // same child is very likely to be used over and over in particle
    // systems.  However, performance is even better if vgChildImage()
    // isn't needed at all, so use full source rects where possible.
    QVarLengthArray<VGImage> cachedImages;
    QVarLengthArray<QRect> cachedSources;

    // Select the opacity paint object.
    if ((hints & QDrawPixmaps::OpaqueHint) != 0 && d->opacity == 1.0f) {
        d->setImageMode(VG_DRAW_IMAGE_NORMAL);
    }  else {
        hints = 0;
        if (d->fillPaint != d->opacityPaint) {
            vgSetPaint(d->opacityPaint, VG_FILL_PATH);
            d->fillPaint = d->opacityPaint;
        }
    }

    for (int i = 0; i < dataCount; ++i) {
        QTransform transform(d->imageTransform);
        transform.translate(drawingData[i].point.x(), drawingData[i].point.y());
        transform.rotate(drawingData[i].rotation);

        VGImage child;
        QSize imageSize = vgpd->size();
        QRectF sr = drawingData[i].source;
        if (sr.topLeft().isNull() && sr.size() == imageSize) {
            child = vgImg;
        } else {
            // Look for a previous child with the same source rectangle
            // to avoid constantly calling vgChildImage()/vgDestroyImage().
            QRect src = sr.toRect();
            int j;
            for (j = 0; j < cachedSources.size(); ++j) {
                if (cachedSources[j] == src)
                    break;
            }
            if (j < cachedSources.size()) {
                child = cachedImages[j];
            } else {
                child = vgChildImage
                    (vgImg, src.x(), src.y(), src.width(), src.height());
                cachedImages.append(child);
                cachedSources.append(src);
            }
        }

        VGfloat scaleX = drawingData[i].scaleX;
        VGfloat scaleY = drawingData[i].scaleY;
        transform.translate(-0.5 * scaleX * sr.width(),
                            -0.5 * scaleY * sr.height());
        transform.scale(scaleX, scaleY);
        d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);

        if ((hints & QDrawPixmaps::OpaqueHint) == 0) {
            qreal opacity = d->opacity * drawingData[i].opacity;
            if (opacity != 1.0f) {
                if (d->paintOpacity != opacity) {
                    VGfloat values[4];
                    values[0] = 1.0f;
                    values[1] = 1.0f;
                    values[2] = 1.0f;
                    values[3] = opacity;
                    d->paintOpacity = opacity;
                    vgSetParameterfv
                        (d->opacityPaint, VG_PAINT_COLOR, 4, values);
                }
                d->setImageMode(VG_DRAW_IMAGE_MULTIPLY);
            } else {
                d->setImageMode(VG_DRAW_IMAGE_NORMAL);
            }
        }

        vgDrawImage(child);
    }

    // Destroy the cached child sub-images.
    for (int i = 0; i < cachedImages.size(); ++i)
        vgDestroyImage(cachedImages[i]);
#else
    QPaintEngineEx::drawPixmaps(drawingData, dataCount, pixmap, hints);
#endif
}

QVGFontEngineCleaner::QVGFontEngineCleaner(QVGPaintEnginePrivate *d)
    : QObject(), d_ptr(d)
{
}

QVGFontEngineCleaner::~QVGFontEngineCleaner()
{
}

void QVGFontEngineCleaner::fontEngineDestroyed()
{
#if !defined(QVG_NO_DRAW_GLYPHS)
    QFontEngine *engine = static_cast<QFontEngine *>(sender());
    QVGFontCache::Iterator it = d_ptr->fontCache.find(engine);
    if (it != d_ptr->fontCache.end()) {
        delete it.value();
        d_ptr->fontCache.erase(it);
    }
#endif
}

#if !defined(QVG_NO_DRAW_GLYPHS)

QVGFontGlyphCache::QVGFontGlyphCache()
{
    font = vgCreateFont(0);
    scaleX = scaleY = 0.0;
    memset(cachedGlyphsMask, 0, sizeof(cachedGlyphsMask));
}

QVGFontGlyphCache::~QVGFontGlyphCache()
{
    if (font != VG_INVALID_HANDLE)
        vgDestroyFont(font);
}

void QVGFontGlyphCache::setScaleFromText(const QTextItemInt &ti)
{
    QFontInfo fi(ti.font());
    qreal pixelSize = fi.pixelSize();
    qreal emSquare = ti.fontEngine->properties().emSquare.toReal();
    scaleX = scaleY = static_cast<VGfloat>(pixelSize / emSquare);
}

void QVGFontGlyphCache::cacheGlyphs
        (QVGPaintEnginePrivate *d, const QTextItemInt &ti,
         const QVarLengthArray<glyph_t> &glyphs)
{
    VGfloat origin[2];
    VGfloat escapement[2];
    const glyph_t *g = glyphs.constData();
    int count = glyphs.size();
    glyph_metrics_t metrics;
    // Some Qt font engines don't set yoff in getUnscaledGlyph().
    // Zero the metric structure so that everything has a default value.
    memset(&metrics, 0, sizeof(metrics));
    while (count-- > 0) {
        // Skip this glyph if we have already cached it before.
        glyph_t glyph = *g++;
        if (glyph < 256) {
            if ((cachedGlyphsMask[glyph / 32] & (1 << (glyph % 32))) != 0)
                continue;
            cachedGlyphsMask[glyph / 32] |= (1 << (glyph % 32));
        } else if (cachedGlyphs.contains(glyph)) {
            continue;
        } else {
            cachedGlyphs.insert(glyph);
        }
#if !defined(QVG_NO_IMAGE_GLYPHS)
        Q_UNUSED(d);
        QImage scaledImage = ti.fontEngine->alphaMapForGlyph(glyph);
        VGImage vgImage = VG_INVALID_HANDLE;
        metrics = ti.fontEngine->boundingBox(glyph);
        if (!scaledImage.isNull()) {  // Not a space character
            if (scaledImage.format() == QImage::Format_Indexed8) {
                vgImage = vgCreateImage(VG_A_8, scaledImage.width(), scaledImage.height(), VG_IMAGE_QUALITY_FASTER);
                vgImageSubData(vgImage, scaledImage.bits(), scaledImage.bytesPerLine(), VG_A_8, 0, 0, scaledImage.width(), scaledImage.height());
            } else if (scaledImage.format() == QImage::Format_Mono) {
                QImage img = scaledImage.convertToFormat(QImage::Format_Indexed8);
                vgImage = vgCreateImage(VG_A_8, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
                vgImageSubData(vgImage, img.bits(), img.bytesPerLine(), VG_A_8, 0, 0, img.width(), img.height());
            } else {
                QImage img = scaledImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
                vgImage = vgCreateImage(VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
                vgImageSubData(vgImage, img.bits(), img.bytesPerLine(), VG_sARGB_8888_PRE, 0, 0, img.width(), img.height());
            }
        }
        origin[0] = -metrics.x.toReal() + 0.5f;
        origin[1] = -metrics.y.toReal() + 0.5f;
        escapement[0] = metrics.xoff.toReal();
        escapement[1] = metrics.yoff.toReal();
        vgSetGlyphToImage(font, glyph, vgImage, origin, escapement);
        vgDestroyImage(vgImage);    // Reduce reference count.
#else
        // Calculate the path for the glyph and cache it.
        QPainterPath path;
        ti.fontEngine->getUnscaledGlyph(glyph, &path, &metrics);
        VGPath vgPath;
        if (!path.isEmpty()) {
            vgPath = d->painterPathToVGPath(path);
        } else {
            // Probably a "space" character with no visible outline.
            vgPath = VG_INVALID_HANDLE;
        }
        origin[0] = 0;
        origin[1] = 0;
        escapement[0] = metrics.xoff.toReal();
        escapement[1] = metrics.yoff.toReal();
        vgSetGlyphToPath(font, glyph, vgPath, VG_FALSE, origin, escapement);
        vgDestroyPath(vgPath);      // Reduce reference count.
#endif // !defined(QVG_NO_IMAGE_GLYPHS)
    }
}

#endif // !defined(QVG_NO_DRAW_GLYPHS)

void QVGPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
{
#if !defined(QVG_NO_DRAW_GLYPHS)
    Q_D(QVGPaintEngine);
    const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);

    // If we are not using a simple transform, then fall back
    // to the default Qt path stroking algorithm.
    if (!d->simpleTransform) {
        QPaintEngineEx::drawTextItem(p, textItem);
        return;
    }
 
    // Get the glyphs and positions associated with the text item.
    QVarLengthArray<QFixedPoint> positions;
    QVarLengthArray<glyph_t> glyphs;
    QTransform matrix = d->transform;
    matrix.translate(p.x(), p.y());
    ti.fontEngine->getGlyphPositions
        (ti.glyphs, matrix, ti.flags, glyphs, positions);

    // Find the glyph cache for this font.
    QVGFontCache::ConstIterator it = d->fontCache.constFind(ti.fontEngine);
    QVGFontGlyphCache *glyphCache;
    if (it != d->fontCache.constEnd()) {
        glyphCache = it.value();
    } else {
        glyphCache = new QVGFontGlyphCache();
        if (glyphCache->font == VG_INVALID_HANDLE) {
            qWarning("QVGPaintEngine::drawTextItem: OpenVG fonts are not supported by the OpenVG engine");
            delete glyphCache;
            QPaintEngineEx::drawTextItem(p, textItem);
            return;
        }
        glyphCache->setScaleFromText(ti);
        d->fontCache.insert(ti.fontEngine, glyphCache);
        if (!d->fontEngineCleaner)
            d->fontEngineCleaner = new QVGFontEngineCleaner(d);
        QObject::connect(ti.fontEngine, SIGNAL(destroyed()),
                         d->fontEngineCleaner, SLOT(fontEngineDestroyed()));
    }

    // Set the transformation to use for drawing the current glyphs.
    QTransform glyphTransform(d->pathTransform);
    glyphTransform.translate(p.x(), p.y());
#if defined(QVG_NO_IMAGE_GLYPHS)
    glyphTransform.scale(glyphCache->scaleX, glyphCache->scaleY);
#endif
    d->setTransform(VG_MATRIX_GLYPH_USER_TO_SURFACE, glyphTransform);

    // Add the glyphs from the text item into the glyph cache.
    glyphCache->cacheGlyphs(d, ti, glyphs);

    // Set the glyph drawing origin.
    VGfloat origin[2];
    origin[0] = 0;
    origin[1] = 0;
    vgSetfv(VG_GLYPH_ORIGIN, 2, origin);

    // Fast anti-aliasing for paths, better for images.
#if !defined(QVG_NO_IMAGE_GLYPHS)
    d->setImageQuality(VG_IMAGE_QUALITY_BETTER);
    d->setImageMode(VG_DRAW_IMAGE_STENCIL);
#else
    d->setRenderingQuality(VG_RENDERING_QUALITY_FASTER);
#endif

    // Draw the glyphs.  We need to fill with the brush associated with
    // the Qt pen, not the Qt brush.
    d->ensureBrush(state()->pen.brush());
    vgDrawGlyphs(glyphCache->font, glyphs.size(), (VGuint*)glyphs.data(),
                 NULL, NULL, VG_FILL_PATH, VG_TRUE);
#else
    // OpenGL 1.0 does not have support for VGFont and glyphs,
    // so fall back to the default Qt path stroking algorithm.
    QPaintEngineEx::drawTextItem(p, textItem);
#endif
}

void QVGPaintEngine::setState(QPainterState *s)
{
    Q_D(QVGPaintEngine);
    QPaintEngineEx::setState(s);
    QVGPainterState *ps = static_cast<QVGPainterState *>(s);
    if (ps->isNew) {
        // Newly created state object.  The call to setState()
        // will either be followed by a call to begin(), or we are
        // setting the state as part of a save().
        ps->isNew = false;
    } else {
        // This state object was set as part of a restore().
        restoreState(d->dirty);
        d->dirty = ps->savedDirty;
    }
}

void QVGPaintEngine::beginNativePainting()
{
    Q_D(QVGPaintEngine);

    // About to enter raw VG mode: flush pending changes and make
    // sure that all matrices are set to the current transformation.
    QVGPainterState *s = this->state();
    d->ensurePen(s->pen);
    d->ensureBrush(s->brush);
    d->ensurePathTransform();
    d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, d->imageTransform);
#if !defined(QVG_NO_DRAW_GLYPHS)
    d->setTransform(VG_MATRIX_GLYPH_USER_TO_SURFACE, d->pathTransform);
#endif
    d->rawVG = true;
}

void QVGPaintEngine::endNativePainting()
{
    Q_D(QVGPaintEngine);
    // Exiting raw VG mode: force all state values to be
    // explicitly set on the VG engine to undo any changes
    // that were made by the raw VG function calls.
    QPaintEngine::DirtyFlags dirty = d->dirty;
    d->clearModes();
    d->forcePenChange = true;
    d->forceBrushChange = true;
    d->penType = (VGPaintType)0;
    d->brushType = (VGPaintType)0;
    d->clearColor = QColor();
    d->fillPaint = d->brushPaint;
    restoreState(QPaintEngine::AllDirty);
    d->dirty = dirty;
    d->rawVG = false;
    vgSetPaint(d->penPaint, VG_STROKE_PATH);
    vgSetPaint(d->brushPaint, VG_FILL_PATH);
}

QPixmapFilter *QVGPaintEngine::pixmapFilter(int type, const QPixmapFilter *prototype)
{
#if !defined(QT_SHIVAVG)
    Q_D(QVGPaintEngine);
    switch (type) {
        case QPixmapFilter::ConvolutionFilter:
            if (!d->convolutionFilter)
                d->convolutionFilter.reset(new QVGPixmapConvolutionFilter);
            return d->convolutionFilter.data();
        case QPixmapFilter::ColorizeFilter:
            if (!d->colorizeFilter)
                d->colorizeFilter.reset(new QVGPixmapColorizeFilter);
            return d->colorizeFilter.data();
        case QPixmapFilter::DropShadowFilter:
            if (!d->dropShadowFilter)
                d->dropShadowFilter.reset(new QVGPixmapDropShadowFilter);
            return d->dropShadowFilter.data();
        case QPixmapFilter::BlurFilter:
            if (!d->blurFilter)
                d->blurFilter.reset(new QVGPixmapBlurFilter);
            return d->blurFilter.data();
        default: break;
    }
#endif
    return QPaintEngineEx::pixmapFilter(type, prototype);
}

void QVGPaintEngine::restoreState(QPaintEngine::DirtyFlags dirty)
{
    Q_D(QVGPaintEngine);

    // Restore the pen, brush, and other settings.
    if ((dirty & QPaintEngine::DirtyBrushOrigin) != 0)
        brushOriginChanged();
    d->fillRule = 0;
    if ((dirty & QPaintEngine::DirtyOpacity) != 0)
        opacityChanged();
    if ((dirty & QPaintEngine::DirtyTransform) != 0)
        transformChanged();
    if ((dirty & QPaintEngine::DirtyCompositionMode) != 0)
        compositionModeChanged();
    if ((dirty & QPaintEngine::DirtyHints) != 0)
        renderHintsChanged();
    if ((dirty & (QPaintEngine::DirtyClipRegion |
                  QPaintEngine::DirtyClipPath |
                  QPaintEngine::DirtyClipEnabled)) != 0) {
        d->maskValid = false;
        d->maskIsSet = false;
        d->maskRect = QRect();
        clipEnabledChanged();
    }

#if defined(QVG_SCISSOR_CLIP)
    if ((dirty & (QPaintEngine::DirtyClipRegion |
                  QPaintEngine::DirtyClipPath |
                  QPaintEngine::DirtyClipEnabled)) == 0) {
        updateScissor();
    }
#else
    updateScissor();
#endif
}

void QVGPaintEngine::fillRegion
    (const QRegion& region, const QColor& color, const QSize& surfaceSize)
{
    Q_D(QVGPaintEngine);
    if (d->clearColor != color || d->clearOpacity != 1.0f) {
        VGfloat values[4];
        values[0] = color.redF();
        values[1] = color.greenF();
        values[2] = color.blueF();
        values[3] = color.alphaF();
        vgSetfv(VG_CLEAR_COLOR, 4, values);
        d->clearColor = color;
        d->clearOpacity = 1.0f;
    }
    if (region.rectCount() == 1) {
        QRect r = region.boundingRect();
        vgClear(r.x(), surfaceSize.height() - r.y() - r.height(),
                r.width(), r.height());
    } else {
        const QVector<QRect> rects = region.rects();
        for (int i = 0; i < rects.size(); ++i) {
            QRect r = rects.at(i);
            vgClear(r.x(), surfaceSize.height() - r.y() - r.height(),
                    r.width(), r.height());
        }
    }
}

#if !defined(QVG_NO_SINGLE_CONTEXT) && !defined(QT_NO_EGL)

QVGCompositionHelper::QVGCompositionHelper()
{
    d = qt_vg_create_paint_engine()->vgPrivate();
}

QVGCompositionHelper::~QVGCompositionHelper()
{
}

void QVGCompositionHelper::startCompositing(const QSize& screenSize)
{
    this->screenSize = screenSize;
    clearScissor();
    d->setBlendMode(VG_BLEND_SRC_OVER);
}

void QVGCompositionHelper::endCompositing()
{
    clearScissor();
}

void QVGCompositionHelper::blitWindow
    (VGImage image, const QSize& imageSize,
     const QRect& rect, const QPoint& topLeft, int opacity)
{
    if (image == VG_INVALID_HANDLE)
        return;

    // Determine which sub rectangle of the window to draw.
    QRect sr = rect.translated(-topLeft);

    if (opacity >= 255) {
        // Fully opaque: use vgSetPixels() to directly copy the sub-region.
        int y = screenSize.height() - (rect.bottom() + 1);
        vgSetPixels(rect.x(), y, image, sr.x(),
                    imageSize.height() - (sr.y() + sr.height()),
                    sr.width(), sr.height());
    } else {
        // Extract the child image that we want to draw.
        VGImage child;
        if (sr.topLeft().isNull() && sr.size() == imageSize)
            child = image;
        else {
            child = vgChildImage
                (image, sr.x(), imageSize.height() - (sr.y() + sr.height()),
                 sr.width(), sr.height());
        }

        // Set the image transform.
        QTransform transform;
        int y = screenSize.height() - (rect.bottom() + 1);
        transform.translate(rect.x() - 0.5f, y - 0.5f);
        d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);

        // Enable opacity for image drawing if necessary.
        if (opacity != d->paintOpacity) {
            VGfloat values[4];
            values[0] = 1.0f;
            values[1] = 1.0f;
            values[2] = 1.0f;
            values[3] = ((VGfloat)opacity) / 255.0f;
            vgSetParameterfv(d->opacityPaint, VG_PAINT_COLOR, 4, values);
            d->paintOpacity = values[3];
        }
        if (d->fillPaint != d->opacityPaint) {
            vgSetPaint(d->opacityPaint, VG_FILL_PATH);
            d->fillPaint = d->opacityPaint;
        }
        d->setImageMode(VG_DRAW_IMAGE_MULTIPLY);

        // Draw the child image.
        vgDrawImage(child);

        // Destroy the child image.
        if(child != image)
            vgDestroyImage(child);
    }
}

static void fillBackgroundRect(const QRect& rect, QVGPaintEnginePrivate *d)
{
    VGfloat coords[8];
    coords[0] = rect.x();
    coords[1] = rect.y();
    coords[2] = rect.x() + rect.width();
    coords[3] = coords[1];
    coords[4] = coords[2];
    coords[5] = rect.y() + rect.height();
    coords[6] = coords[0];
    coords[7] = coords[5];
#if !defined(QVG_NO_MODIFY_PATH)
    vgModifyPathCoords(d->rectPath, 0, 4, coords);
    vgDrawPath(d->rectPath, VG_FILL_PATH);
#else
    Q_UNUSED(d);
    VGPath rectPath = vgCreatePath
            (VG_PATH_FORMAT_STANDARD,
             VG_PATH_DATATYPE_F,
             1.0f, // scale
             0.0f, // bias
             5,    // segmentCapacityHint
             8,    // coordCapacityHint
             VG_PATH_CAPABILITY_ALL);
    static VGubyte const segments[5] = {
        VG_MOVE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_LINE_TO_ABS,
        VG_CLOSE_PATH
    };
    vgAppendPathData(rectPath, 5, segments, coords);
    vgDrawPath(rectPath, VG_FILL_PATH);
    vgDestroyPath(rectPath);
#endif
}

void QVGCompositionHelper::fillBackground
    (const QRegion& region, const QBrush& brush)
{
    if (brush.style() == Qt::SolidPattern) {
        // Use vgClear() to quickly fill the background.
        QColor color = brush.color();
        if (d->clearColor != color || d->clearOpacity != 1.0f) {
            VGfloat values[4];
            values[0] = color.redF();
            values[1] = color.greenF();
            values[2] = color.blueF();
            values[3] = color.alphaF();
            vgSetfv(VG_CLEAR_COLOR, 4, values);
            d->clearColor = color;
            d->clearOpacity = 1.0f;
        }
        if (region.rectCount() == 1) {
            QRect r = region.boundingRect();
            vgClear(r.x(), screenSize.height() - r.y() - r.height(),
                    r.width(), r.height());
        } else {
            const QVector<QRect> rects = region.rects();
            for (int i = 0; i < rects.size(); ++i) {
                QRect r = rects.at(i);
                vgClear(r.x(), screenSize.height() - r.y() - r.height(),
                        r.width(), r.height());
            }
        }

    } else {
        // Set the path transform to the default viewport transformation.
        VGfloat devh = screenSize.height() - 1;
        QTransform viewport(1.0f, 0.0f, 0.0f,
                            0.0f, -1.0f, 0.0f,
                            -0.5f, devh + 0.5f, 1.0f);
        d->setTransform(VG_MATRIX_PATH_USER_TO_SURFACE, viewport);

        // Set the brush to use to fill the background.
        d->ensureBrush(brush);
        d->setFillRule(VG_EVEN_ODD);

        if (region.rectCount() == 1) {
            fillBackgroundRect(region.boundingRect(), d);
        } else {
            const QVector<QRect> rects = region.rects();
            for (int i = 0; i < rects.size(); ++i)
                fillBackgroundRect(rects.at(i), d);
        }

        // We will need to reset the path transform during the next paint.
        d->pathTransformSet = false;
    }
}

void QVGCompositionHelper::drawCursorPixmap
    (const QPixmap& pixmap, const QPoint& offset)
{
    VGImage vgImage = VG_INVALID_HANDLE;

    // Fetch the VGImage from the pixmap if possible.
    QPixmapData *pd = pixmap.pixmapData();
    if (!pd)
        return; // null QPixmap
    if (pd->classId() == QPixmapData::OpenVGClass) {
        QVGPixmapData *vgpd = static_cast<QVGPixmapData *>(pd);
        if (vgpd->isValid())
            vgImage = vgpd->toVGImage();
    }

    // Set the image transformation and modes.
    VGfloat devh = screenSize.height() - 1;
    QTransform transform(1.0f, 0.0f, 0.0f,
                         0.0f, -1.0f, 0.0f,
                         -0.5f, devh + 0.5f, 1.0f);
    transform.translate(offset.x(), offset.y());
    d->setTransform(VG_MATRIX_IMAGE_USER_TO_SURFACE, transform);
    d->setImageMode(VG_DRAW_IMAGE_NORMAL);

    // Draw the VGImage.
    if (vgImage != VG_INVALID_HANDLE) {
        vgDrawImage(vgImage);
    } else {
        QImage img = pixmap.toImage().convertToFormat
            (QImage::Format_ARGB32_Premultiplied);

        vgImage = vgCreateImage
            (VG_sARGB_8888_PRE, img.width(), img.height(),
             VG_IMAGE_QUALITY_FASTER);
        if (vgImage == VG_INVALID_HANDLE)
            return;
        vgImageSubData
            (vgImage, img.bits() + img.bytesPerLine() * (img.height() - 1),
             -(img.bytesPerLine()), VG_sARGB_8888_PRE, 0, 0,
             img.width(), img.height());

        vgDrawImage(vgImage);
        vgDestroyImage(vgImage);
    }
}

void QVGCompositionHelper::setScissor(const QRegion& region)
{
    QVector<QRect> rects = region.rects();
    int count = rects.count();
    if (count > d->maxScissorRects)
        count = d->maxScissorRects;
    QVarLengthArray<VGint> params(count * 4);
    int height = screenSize.height();
    for (int i = 0; i < count; ++i) {
        params[i * 4 + 0] = rects[i].x();
        params[i * 4 + 1] = height - rects[i].y() - rects[i].height();
        params[i * 4 + 2] = rects[i].width();
        params[i * 4 + 3] = rects[i].height();
    }

    vgSetiv(VG_SCISSOR_RECTS, count * 4, params.data());
    vgSeti(VG_SCISSORING, VG_TRUE);
    d->scissorActive = true;
    d->scissorRegion = region;
}

void QVGCompositionHelper::clearScissor()
{
    if (d->scissorActive) {
        vgSeti(VG_SCISSORING, VG_FALSE);
        d->scissorActive = false;
    }
}

#endif // !QVG_NO_SINGLE_CONTEXT && !QT_NO_EGL

VGImageFormat qt_vg_image_to_vg_format(QImage::Format format)
{
    switch (format) {
        case QImage::Format_MonoLSB:
            return VG_BW_1;
        case QImage::Format_ARGB32_Premultiplied:
            return VG_sARGB_8888_PRE;
        case QImage::Format_RGB32:
            return VG_sXRGB_8888;
        case QImage::Format_ARGB32:
            return VG_sARGB_8888;
        case QImage::Format_RGB16:
            return VG_sRGB_565;
        case QImage::Format_ARGB4444_Premultiplied:
            return VG_sARGB_4444;
        default: break;
    }
    return VG_sARGB_8888;   // XXX
}

QT_END_NAMESPACE

#include "qpaintengine_vg.moc"