summaryrefslogtreecommitdiff
path: root/css/css.c
blob: 133b9ec92b7aad74763e879e3003172ad29eb9ac (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
/*
 * Copyright 2004 James Bursa <bursa@users.sourceforge.net>
 * Copyright 2004 John M Bell <jmb202@ecs.soton.ac.uk>
 * Copyright 2008 Michael Drake <tlsa@netsurf-browser.org>
 *
 * This file is part of NetSurf, http://www.netsurf-browser.org/
 *
 * NetSurf is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * NetSurf is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/** \file
 * CSS handling (implementation).
 *
 * See CSS 2.1 chapter 5 for the terms used here.
 *
 * CSS style sheets are stored as a hash table mapping selectors to styles.
 * Selectors are hashed by the <em>type selector</em> of the last <em>simple
 * selector</em> in the selector. The <em>universal selector</em> is hashed to
 * chain 0.
 *
 * A <em>simple selector</em> is a struct css_selector with type
 * CSS_SELECTOR_ELEMENT. The data field is the <em>type selector</em>, or 0 for
 * the <em>universal selector</em>. Any <em>attribute selectors</em>, <em>ID
 * selectors</em>, or <em>pseudo-classes</em> form a linked list of
 * css_selector hanging from detail.
 *
 * A <em>selector</em> is a linked list by the combiner field of these simple
 * selectors, in reverse order that they appear in the concrete syntax. The last
 * simple selector is first, then the previous one is linked at combiner and has
 * relationship comb to the last, etc.
 *
 * Selectors are then linked in each hash chain by next, in order of increasing
 * specificity.
 *
 * As an example, the stylesheet
 * \code
 *   th { [1] }
 *   div#id1 > h4.class1 { [2] }
 *   center * { [3] }                                                  \endcode
 *
 * would result in a struct css_stylesheet (content::data.css.css) like this
 * \dot
 *   digraph example {
 *     node [shape=record, fontname=Helvetica, fontsize=9];
 *     edge [fontname=Helvetica, fontsize=9];
 *     css -> n0 [label="rule[0]"];
 *     css -> n2 [label="rule[29]"];
 *
 *     n0 [label="css_selector\ntype CSS_SELECTOR_ELEMENT\ldata 0\lcomb CSS_COMB_ANCESTOR\lspecificity 2\l"];
 *     n0 -> n1 [label="combiner"];
 *     n0 -> n0style [label="style"]; n0style [label="[3]"];
 *
 *     n1 [label="css_selector\ntype CSS_SELECTOR_ELEMENT\ldata \"center\"\lcomb CSS_COMB_NONE\lspecificity 1\l"];
 *
 *     n2 [label="css_selector\ntype CSS_SELECTOR_ELEMENT\ldata \"th\"\lcomb CSS_COMB_NONE\lspecificity 1\l"];
 *     n2 -> n3 [label="next"];
 *     n2 -> n2style [label="style"]; n2style [label="[1]"];
 *
 *     n3 [label="css_selector\ntype CSS_SELECTOR_ELEMENT\ldata \"h4\"\lcomb CSS_COMB_PARENT\lspecificity 0x10102\l"];
 *     n3 -> n4 [label="detail"];
 *     n3 -> n5 [label="combiner"];
 *     n3 -> n3style [label="style"]; n3style [label="[2]"];
 *
 *     n4 [label="css_selector\ntype CSS_SELECTOR_CLASS\ldata \"class1\"\lcomb CSS_COMB_NONE\lspecificity 0x100\l"];
 *
 *     n5 [label="css_selector\ntype CSS_SELECTOR_ELEMENT\ldata \"div\"\lcomb CSS_COMB_NONE\lspecificity 0x10001\l"];
 *     n5 -> n6 [label="detail"];
 *
 *     n6 [label="css_selector\ntype CSS_SELECTOR_ID\ldata \"#id1\"\lcomb CSS_COMB_NONE\lspecificity 0x10000\l"];
 *   }
 * \enddot
 *
 * (any fields not shown are 0). In this example the first two rules happen to
 * have hashed to the same value.
 */

#define _GNU_SOURCE  /* for strndup */
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <limits.h>
#define CSS_INTERNALS
#include "utils/config.h"
#include "content/content.h"
#include "content/fetch.h"
#include "content/fetchcache.h"
#include "css/css.h"
#include "css/parser.h"
#include "desktop/gui.h"
#include "desktop/options.h"
#include "utils/log.h"
#include "utils/messages.h"
#include "utils/talloc.h"
#include "utils/url.h"
#include "utils/utils.h"

/* Define this to debug the working stylesheet */
#undef DEBUG_WORKING_STYLESHEET
struct css_working_stylesheet {
	struct css_selector **rule[HASH_SIZE];
};


static void css_deep_free_style(struct css_style *style);
static void css_atimport_callback(content_msg msg, struct content *css,
		intptr_t p1, intptr_t p2, union content_msg_data data);
static bool css_working_list_imports(struct content **import,
		unsigned int import_count,
		struct content ***css, unsigned int *css_count);
static bool css_working_merge_chains(
		struct css_working_stylesheet *working_stylesheet,
		struct content **css, unsigned int css_count,
		unsigned int chain,
		struct css_selector **rule);
static bool css_match_rule(struct css_selector *rule, xmlNode *element);
static bool css_match_detail(const struct css_selector *detail,
		xmlNode *element);
static bool css_match_first_child(const struct css_selector *detail,
		xmlNode *element);
static void css_dump_length(FILE *stream,
		const struct css_length * const length);
static void css_dump_selector(const struct css_selector *r);
#ifdef DEBUG_WORKING_STYLESHEET
static void css_dump_working_stylesheet(
		const struct css_working_stylesheet *ws);
#endif
static void css_importance_reset(struct css_importance *i);

/** Default style for a document. These are the 'Initial values' from the
 *  spec. */
const struct css_style css_base_style = {
	CSS_BACKGROUND_ATTACHMENT_SCROLL,
	0xffffff,
	{ CSS_BACKGROUND_IMAGE_NONE, 0 },
	{ { CSS_BACKGROUND_POSITION_PERCENT, { 0.0 } },
	  { CSS_BACKGROUND_POSITION_PERCENT, { 0.0 } } },
	CSS_BACKGROUND_REPEAT_REPEAT,
	{ { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE } },
	CSS_BORDER_COLLAPSE_SEPARATE,
	{ CSS_BORDER_SPACING_LENGTH,
	  { 0, CSS_UNIT_PX }, { 0, CSS_UNIT_PX } },
	CSS_CAPTION_SIDE_TOP,
	CSS_CLEAR_NONE,
	{ CSS_CLIP_AUTO, { { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } } } },
	0x000000,
	{ CSS_CONTENT_NORMAL, 0 },
	{ CSS_COUNTER_RESET_NONE, 0 },
	{ CSS_COUNTER_INCREMENT_NONE, 0 },
	CSS_CURSOR_AUTO,
	CSS_DIRECTION_LTR,
	CSS_DISPLAY_BLOCK,
	CSS_EMPTY_CELLS_SHOW,
	CSS_FLOAT_NONE,
	CSS_FONT_FAMILY_SANS_SERIF,
	{ CSS_FONT_SIZE_LENGTH, { { 10, CSS_UNIT_PT } } },
	CSS_FONT_STYLE_NORMAL,
	CSS_FONT_VARIANT_NORMAL,
	CSS_FONT_WEIGHT_NORMAL,
	{ CSS_HEIGHT_AUTO, { { 1, CSS_UNIT_EM } } },
	{ CSS_LETTER_SPACING_NORMAL, { 0, CSS_UNIT_PX } },
	{ CSS_LINE_HEIGHT_ABSOLUTE, { 1.33 } },
	{ CSS_LIST_STYLE_IMAGE_NONE, 0 },
	CSS_LIST_STYLE_POSITION_OUTSIDE,
	CSS_LIST_STYLE_TYPE_DISC,
	{ { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } } },
	{ CSS_MAX_HEIGHT_NONE, { { 0, CSS_UNIT_PX } } },
	{ CSS_MAX_WIDTH_NONE, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_HEIGHT_LENGTH, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_WIDTH_LENGTH, { { 0, CSS_UNIT_PX } } },
	{ CSS_ORPHANS_INTEGER, 2 },
	{ { CSS_OUTLINE_COLOR_INVERT, 0x000000 },
	  { CSS_BORDER_WIDTH_LENGTH, { 2, CSS_UNIT_PX } },
	  CSS_BORDER_STYLE_NONE },
	CSS_OVERFLOW_VISIBLE,
	{ { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } } },
	CSS_PAGE_BREAK_AFTER_AUTO,
	CSS_PAGE_BREAK_BEFORE_AUTO,
	CSS_PAGE_BREAK_INSIDE_AUTO,
	{ { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } } },
	CSS_POSITION_STATIC,
	CSS_TABLE_LAYOUT_AUTO,
	CSS_TEXT_ALIGN_LEFT,
	CSS_TEXT_DECORATION_NONE,
	{ CSS_TEXT_INDENT_LENGTH, { { 0, CSS_UNIT_EM } } },
	CSS_TEXT_TRANSFORM_NONE,
	CSS_UNICODE_BIDI_NORMAL,
	{ CSS_VERTICAL_ALIGN_BASELINE, { { 0, CSS_UNIT_PX } } },
	CSS_VISIBILITY_VISIBLE,
	CSS_WHITE_SPACE_NORMAL,
	{ CSS_WIDOWS_INTEGER, 2 },
	{ CSS_WIDTH_AUTO, { { 1, CSS_UNIT_EM } } },
	{ CSS_WORD_SPACING_NORMAL, { 0, CSS_UNIT_PX } },
	{ CSS_Z_INDEX_AUTO, 0 }
};

/** Style with no values set. */
const struct css_style css_empty_style = {
	CSS_BACKGROUND_ATTACHMENT_NOT_SET,
	CSS_COLOR_NOT_SET,
	{ CSS_BACKGROUND_IMAGE_NOT_SET, 0 },
	{ { CSS_BACKGROUND_POSITION_NOT_SET, { 0.0 } },
	  { CSS_BACKGROUND_POSITION_NOT_SET, { 0.0 } } },
	CSS_BACKGROUND_REPEAT_NOT_SET,
	{ { CSS_COLOR_NOT_SET, { CSS_BORDER_WIDTH_NOT_SET,
	    { 0, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NOT_SET },
	  { CSS_COLOR_NOT_SET, { CSS_BORDER_WIDTH_NOT_SET,
	    { 0, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NOT_SET },
	  { CSS_COLOR_NOT_SET, { CSS_BORDER_WIDTH_NOT_SET,
	    { 0, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NOT_SET },
	  { CSS_COLOR_NOT_SET, { CSS_BORDER_WIDTH_NOT_SET,
	    { 0, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NOT_SET } },
	CSS_BORDER_COLLAPSE_NOT_SET,
	{ CSS_BORDER_SPACING_NOT_SET,
	  { 0, CSS_UNIT_PX }, { 0, CSS_UNIT_PX } },
	CSS_CAPTION_SIDE_NOT_SET,
	CSS_CLEAR_NOT_SET,
	{ CSS_CLIP_NOT_SET, { { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } } } },
	CSS_COLOR_NOT_SET,
	{ CSS_CONTENT_NOT_SET, 0 },
	{ CSS_COUNTER_RESET_NOT_SET, 0 },
	{ CSS_COUNTER_INCREMENT_NOT_SET, 0 },
	CSS_CURSOR_NOT_SET,
	CSS_DIRECTION_NOT_SET,
	CSS_DISPLAY_NOT_SET,
	CSS_EMPTY_CELLS_NOT_SET,
	CSS_FLOAT_NOT_SET,
	CSS_FONT_FAMILY_NOT_SET,
	{ CSS_FONT_SIZE_NOT_SET, { { 1, CSS_UNIT_PT } } },
	CSS_FONT_STYLE_NOT_SET,
	CSS_FONT_VARIANT_NOT_SET,
	CSS_FONT_WEIGHT_NOT_SET,
	{ CSS_HEIGHT_NOT_SET, { { 1, CSS_UNIT_EM } } },
	{ CSS_LETTER_SPACING_NOT_SET, { 0, CSS_UNIT_PX } },
	{ CSS_LINE_HEIGHT_NOT_SET, { 1.33 } },
	{ CSS_LIST_STYLE_IMAGE_NOT_SET, 0 },
	CSS_LIST_STYLE_POSITION_NOT_SET,
	CSS_LIST_STYLE_TYPE_NOT_SET,
	{ { CSS_MARGIN_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_NOT_SET, { { 0, CSS_UNIT_PX } } } },
	{ CSS_MAX_HEIGHT_NOT_SET, { { 0, CSS_UNIT_PX } } },
	{ CSS_MAX_WIDTH_NOT_SET, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_HEIGHT_NOT_SET, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_WIDTH_NOT_SET, { { 0, CSS_UNIT_PX } } },
	{ CSS_ORPHANS_NOT_SET, 0 },
	{ { CSS_OUTLINE_COLOR_NOT_SET, CSS_COLOR_NOT_SET },
	  { CSS_BORDER_WIDTH_NOT_SET, { 0, CSS_UNIT_PX } },
	  CSS_BORDER_STYLE_NOT_SET },
	CSS_OVERFLOW_NOT_SET,
	{ { CSS_PADDING_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_NOT_SET, { { 0, CSS_UNIT_PX } } } },
	CSS_PAGE_BREAK_AFTER_NOT_SET,
	CSS_PAGE_BREAK_BEFORE_NOT_SET,
	CSS_PAGE_BREAK_INSIDE_NOT_SET,
	{ { CSS_POS_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_NOT_SET, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_NOT_SET, { { 0, CSS_UNIT_PX } } } },
	CSS_POSITION_NOT_SET,
	CSS_TABLE_LAYOUT_NOT_SET,
	CSS_TEXT_ALIGN_NOT_SET,
	CSS_TEXT_DECORATION_NOT_SET,
	{ CSS_TEXT_INDENT_NOT_SET, { { 0, CSS_UNIT_EM } } },
	CSS_TEXT_TRANSFORM_NOT_SET,
	CSS_UNICODE_BIDI_NOT_SET,
	{ CSS_VERTICAL_ALIGN_NOT_SET, { { 0, CSS_UNIT_PX } } },
	CSS_VISIBILITY_NOT_SET,
	CSS_WHITE_SPACE_NOT_SET,
	{ CSS_WIDOWS_NOT_SET, 0 },
	{ CSS_WIDTH_NOT_SET, { { 1, CSS_UNIT_EM } } },
	{ CSS_WORD_SPACING_NOT_SET, { 0, CSS_UNIT_PX } },
	{ CSS_Z_INDEX_NOT_SET, 0 }
};

/** Default style for an element. These should be INHERIT if 'Inherited' is yes,
 *  and the 'Initial value' otherwise. */
const struct css_style css_blank_style = {
	CSS_BACKGROUND_ATTACHMENT_SCROLL,
	TRANSPARENT,
	{ CSS_BACKGROUND_IMAGE_NONE, 0 },
	{ { CSS_BACKGROUND_POSITION_PERCENT, { 0.0 } },
	  { CSS_BACKGROUND_POSITION_PERCENT, { 0.0 } } },
	CSS_BACKGROUND_REPEAT_REPEAT,
	{ { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE },
	  { 0x000000, { CSS_BORDER_WIDTH_LENGTH,
	    { 2, CSS_UNIT_PX } }, CSS_BORDER_STYLE_NONE } },
	CSS_BORDER_COLLAPSE_INHERIT,
	{ CSS_BORDER_SPACING_INHERIT,
	  { 0, CSS_UNIT_PX }, { 0, CSS_UNIT_PX } },
	CSS_CAPTION_SIDE_INHERIT,
	CSS_CLEAR_NONE,
	{ CSS_CLIP_AUTO, { { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } },
	  { CSS_CLIP_RECT_AUTO, { 0, CSS_UNIT_PX } } } },
	CSS_COLOR_INHERIT,
	{ CSS_CONTENT_NORMAL, 0 },
	{ CSS_COUNTER_RESET_NONE, 0 },
	{ CSS_COUNTER_INCREMENT_NONE, 0 },
	CSS_CURSOR_INHERIT,
	CSS_DIRECTION_INHERIT,
	CSS_DISPLAY_INLINE,
	CSS_EMPTY_CELLS_INHERIT,
	CSS_FLOAT_NONE,
	CSS_FONT_FAMILY_INHERIT,
	{ CSS_FONT_SIZE_INHERIT, { { 1, CSS_UNIT_EM } } },
	CSS_FONT_STYLE_INHERIT,
	CSS_FONT_VARIANT_INHERIT,
	CSS_FONT_WEIGHT_INHERIT,
	{ CSS_HEIGHT_AUTO, { { 1, CSS_UNIT_EM } } },
	{ CSS_LETTER_SPACING_INHERIT, { 0, CSS_UNIT_PX } },
	{ CSS_LINE_HEIGHT_INHERIT, { 1.33 } },
	{ CSS_LIST_STYLE_IMAGE_INHERIT, 0 },
	CSS_LIST_STYLE_POSITION_INHERIT,
	CSS_LIST_STYLE_TYPE_INHERIT,
	{ { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_MARGIN_LENGTH, { { 0, CSS_UNIT_PX } } } },
	{ CSS_MAX_HEIGHT_NONE, { { 0, CSS_UNIT_PX } } },
	{ CSS_MAX_WIDTH_NONE, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_HEIGHT_LENGTH, { { 0, CSS_UNIT_PX } } },
	{ CSS_MIN_WIDTH_LENGTH, { { 0, CSS_UNIT_PX } } },
	{ CSS_ORPHANS_INHERIT, 0 },
	{ { CSS_OUTLINE_COLOR_INVERT, 0x000000 },
	  { CSS_BORDER_WIDTH_LENGTH, { 2, CSS_UNIT_PX } },
	  CSS_BORDER_STYLE_NONE },
	CSS_OVERFLOW_VISIBLE,
	{ { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } },
	  { CSS_PADDING_LENGTH, { { 0, CSS_UNIT_PX } } } },
	CSS_PAGE_BREAK_AFTER_AUTO,
	CSS_PAGE_BREAK_BEFORE_AUTO,
	CSS_PAGE_BREAK_INSIDE_INHERIT,
	{ { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } },
	  { CSS_POS_AUTO, { { 0, CSS_UNIT_PX } } } },
	CSS_POSITION_STATIC,
	CSS_TABLE_LAYOUT_AUTO,
	CSS_TEXT_ALIGN_INHERIT,
	CSS_TEXT_DECORATION_NONE,
	{ CSS_TEXT_INDENT_INHERIT, { { 0, CSS_UNIT_EM } } },
	CSS_TEXT_TRANSFORM_INHERIT,
	CSS_UNICODE_BIDI_NORMAL,
	{ CSS_VERTICAL_ALIGN_BASELINE, { { 0, CSS_UNIT_PX } } },
	CSS_VISIBILITY_INHERIT,
	CSS_WHITE_SPACE_INHERIT,
	{ CSS_WIDOWS_INHERIT, 0 },
	{ CSS_WIDTH_AUTO, { { 1, CSS_UNIT_EM } } },
	{ CSS_WORD_SPACING_INHERIT, { 0, CSS_UNIT_PX } },
	{ CSS_Z_INDEX_AUTO, 0 }
};

/** Dots per inch for the display device.
 *
 * This is the number of pixels per inch of the display device.
 * This variable should be treated as constant during the runtime of
 * the program unless the core can be persuaded to re-layout fully
 * on change.
 *
 * We default to 90.0 because RISC OS defaults to 90.0 dpi.
 */
float css_screen_dpi = 90.0;

/**
 * Convert a CONTENT_CSS for use.
 */

bool css_convert(struct content *c, int width, int height)
{
	unsigned char *source_data;
	unsigned char *current, *end, *token_text;
	unsigned int i;
	int token;
	void *parser;
	struct css_parser_params param = {false, c, 0, false, false, false};
	struct css_parser_token token_data;
	union content_msg_data msg_data;

	/* css_parser_Trace(stderr, "CSS: "); */

	c->data.css.css = malloc(sizeof *c->data.css.css);
	parser = css_parser_Alloc(malloc);
	source_data = (unsigned char *) talloc_realloc(c, c->source_data, char,
			c->source_size + 10);

	if (!c->data.css.css || !parser || !source_data) {
		free(c->data.css.css);
		css_parser_Free(parser, free);

		msg_data.error = messages_get("NoMemory");
		content_broadcast(c, CONTENT_MSG_ERROR, msg_data);
		return false;
	}

	for (i = 0; i != HASH_SIZE; i++)
		c->data.css.css->rule[i] = 0;
	c->data.css.import_count = 0;
	c->data.css.import_content = 0;
	c->data.css.origin = CSS_ORIGIN_UA;
	c->active = 0;
	c->source_data = (char *) source_data;

	for (i = 0; i != 10; i++)
		source_data[c->source_size + i] = 0;

	current = source_data;
	end = source_data + c->source_size;
	while (current < end
			&& (token = css_tokenise(&current, end + 10,
			&token_text))) {
		token_data.text = (char *) token_text;
		token_data.length = current - token_text;
		css_parser_(parser, token, token_data, &param);
		if (param.syntax_error) {
			LOG(("syntax error near offset %li (%s)",
				(unsigned long) (token_text - source_data),
				c->url));
			param.syntax_error = false;
		} else if (param.memory_error) {
			LOG(("out of memory"));
			break;
		}
	}

	css_parser_(parser, 0, token_data, &param);
	css_parser_Free(parser, free);

	if (param.memory_error) {
		msg_data.error = messages_get("NoMemory");
		content_broadcast(c, CONTENT_MSG_ERROR, msg_data);
		return false;
	}

	/*css_dump_stylesheet(c->data.css.css);*/

	/* complete fetch of any imported stylesheets */
	while (c->active != 0) {
		fetch_poll();
		gui_multitask();
	}

	c->status = CONTENT_STATUS_DONE;
	return true;
}


/**
 * Destroy a CONTENT_CSS and free all resources it owns.
 */

void css_destroy(struct content *c)
{
	unsigned int i;
	struct css_selector *r;

	if (c->data.css.css) {
		for (i = 0; i != HASH_SIZE; i++) {
			for (r = c->data.css.css->rule[i]; r != 0;
					r = r->next) {
				css_deep_free_style(r->style);
			}
			css_free_selector(c->data.css.css->rule[i]);
		}
		free(c->data.css.css);
	}

	/* imported stylesheets */
	for (i = 0; i != c->data.css.import_count; i++)
		if (c->data.css.import_content[i] != 0) {
			content_remove_user(c->data.css.import_content[i],
					css_atimport_callback, (intptr_t) c, i);
		}
	free(c->data.css.import_content);
}


/**
 * Set the origin of a stylesheet.
 *
 * \param  c       content of type CONTENT_CSS
 * \param  origin  new origin
 *
 * This may only be called once per stylesheet.
 */

void css_set_origin(struct content *c, css_origin origin)
{
	unsigned int chain, i;
	unsigned long specificity = 0;
	struct css_selector *selector;

	assert(c->type == CONTENT_CSS);

	if (origin == c->data.css.origin)
		return;

	switch (origin)
	{
	case CSS_ORIGIN_AUTHOR: specificity = CSS_SPECIFICITY_AUTHOR; break;
	case CSS_ORIGIN_USER:   specificity = CSS_SPECIFICITY_USER; break;
	case CSS_ORIGIN_UA:     specificity = CSS_SPECIFICITY_UA; break;
	}

	for (chain = 0; chain != HASH_SIZE; chain++)
		for (selector = c->data.css.css->rule[chain];
				selector;
				selector = selector->next)
			selector->specificity += specificity;
	c->data.css.origin = origin;

	for (i = 0; i != c->data.css.import_count; i++)
		if (c->data.css.import_content[i])
			css_set_origin(c->data.css.import_content[i], origin);
}


/**
 * Duplicate a CSS style struct.
 *
 * \param style The style to duplicate
 * \return The duplicate style, or NULL if out of memory.
 */

struct css_style *css_duplicate_style(const struct css_style * const style)
{
	struct css_style *dup;

	assert(style);

	/* create duplicated style */
	dup = malloc(sizeof (struct css_style));
	if (!dup)
		return NULL;

	/* copy all style information into duplicate style */
	memcpy(dup, style, sizeof(struct css_style));

	return dup;
}


/**
 * Free a CSS style.
 *
 * \param style The style to free
 */

void css_free_style(struct css_style *style)
{
	assert(style);

	free(style);
}


/**
 * Free a CSS style, deleting all alloced elements.
 *
 * \param style The style to free
 */

void css_deep_free_style(struct css_style *style)
{
	assert(style);

	if (style->background_image.type == CSS_BACKGROUND_IMAGE_URI)
		free(style->background_image.uri);

	if (style->list_style_image.type == CSS_LIST_STYLE_IMAGE_URI)
		free(style->list_style_image.uri);

	if (style->content.type == CSS_CONTENT_INTERPRET)
		css_deep_free_content(style->content.content);

	if (style->counter_reset.type == CSS_COUNTER_RESET_INTERPRET)
		css_deep_free_counter_control(style->counter_reset.data);

	if (style->counter_increment.type == CSS_COUNTER_INCREMENT_INTERPRET)
		css_deep_free_counter_control(style->counter_increment.data);

	free(style);
}


/**
 * Free all auto-generated content data.
 *
 * \param  content  the auto-generated content data to free
 */

void css_deep_free_content(struct css_content *content)
{
	struct css_content *next;

	while (content) {
		next = content->next;
		switch (content->type) {
			case CSS_CONTENT_STRING:
				free(content->data.string);
				break;
			case CSS_CONTENT_URI:
				free(content->data.uri);
				break;
			case CSS_CONTENT_COUNTER:
				free(content->data.counter.name);
				free(content->data.counter.separator);
				break;
			case CSS_CONTENT_ATTR:
				free(content->data.attr);
				break;
			case CSS_CONTENT_OPEN_QUOTE:
			case CSS_CONTENT_CLOSE_QUOTE:
			case CSS_CONTENT_NO_OPEN_QUOTE:
			case CSS_CONTENT_NO_CLOSE_QUOTE:
				break;
		}
		free(content);
		content = next;
	}
}


/**
 * Free all counter control data.
 *
 * \param counter  the counter control data to free
 */

void css_deep_free_counter_control(struct css_counter_control *control)
{
	struct css_counter_control *next;

	while (control) {
		next = control->next;
		free(control->name);
		free(control);
		control = next;
	}
}


/**
 * Create a new struct css_node.
 *
 * \param  stylesheet  content of type CONTENT_CSS
 * \param  type  type of node
 * \param  data  string for data, not copied
 * \param  data_length  length of data
 * \return  allocated node, or 0 if memory exhausted
 *
 * Used by the parser.
 */

struct css_node * css_new_node(struct content *stylesheet,
                css_node_type type,
		const char *data, unsigned int data_length)
{
	struct css_node *node = malloc(sizeof *node);
	if (!node)
		return 0;
	node->type = type;
	node->data = data;
	node->data_length = data_length;
	node->value = 0;
	node->next = 0;
	node->comb = CSS_COMB_NONE;
	node->style = 0;
	node->specificity = 0;
	node->stylesheet = stylesheet;

	return node;
}


/**
 * Free a struct css_node recursively.
 *
 * \param  node  css_node to free
 *
 * Used by the parser.
 */

void css_free_node(struct css_node *node)
{
	if (!node)
		return;
	if (node->value)
		css_free_node(node->value);
	if (node->next)
		css_free_node(node->next);
	free(node);
}


/**
 * Create a new struct css_selector.
 *
 * \param  type  type of selector
 * \param  data  string for data, not copied
 * \param  data_length  length of data
 * \return  allocated selector, or 0 if memory exhausted
 */

struct css_selector * css_new_selector(css_selector_type type,
		const char *data, unsigned int data_length)
{
	struct css_selector *node = malloc(sizeof *node);
	if (!node)
		return 0;
	node->type = type;
	node->data = data;
	node->data_length = data_length;
	node->data2 = 0;
	node->detail = 0;
	node->combiner = 0;
	node->next = 0;
	node->comb = CSS_COMB_NONE;
	node->style = 0;
	node->specificity = 0;
	return node;
}


/**
 * Free a struct css_selector recursively.
 *
 * \param  node  css_selector to free
 */

void css_free_selector(struct css_selector *node)
{
	if (!node)
		return;
	if (node->detail)
		css_free_selector(node->detail);
	if (node->combiner)
		css_free_selector(node->combiner);
	if (node->next)
		css_free_selector(node->next);
	free(node);
}


/**
 * Process an \@import rule.
 */

void css_atimport(struct content *c, struct css_node *node)
{
	const char *s;
	char *t, *url, *url1;
	bool string = false, screen = true;
	unsigned int i;
	struct content **import_content;
	url_func_result res;

	LOG(("@import rule"));

	import_content = realloc(c->data.css.import_content,
			(c->data.css.import_count + 1) *
			sizeof(*c->data.css.import_content));
	if (!import_content)  {
		/** \todo report to user */
		return;
	}
	c->data.css.import_content = import_content;

	/* uri(...) or "..." */
	switch (node->type) {
		case CSS_NODE_URI:
			LOG(("URI '%.*s'", node->data_length, node->data));
			for (s = node->data + 4;
					*s == ' ' || *s == '\t' || *s == '\r' ||
					*s == '\n' || *s == '\f';
					s++)
				;
			if (*s == '\'' || *s == '"') {
				string = true;
				s++;
			}
			url = strndup(s, node->data_length - (s - node->data));
			if (!url) {
				/** \todo report to user */
				return;
			}
			for (t = url + strlen(url) - 2;
					*t == ' ' || *t == '\t' || *t == '\r' ||
					*t == '\n' || *t == '\f';
					t--)
				;
			if (string)
				*t = 0;
			else
				*(t + 1) = 0;
			break;
		case CSS_NODE_STRING:
			LOG(("STRING '%.*s'", node->data_length, node->data));
			url = strndup(node->data, node->data_length);
			if (!url) {
				/** \todo report to user */
				return;
			}
			break;
		default:
			return;
	}

	/* media not specified, 'screen', or 'all' */
	for (node = node->next; node != 0; node = node->next) {
		screen = false;
		if (node->type != CSS_NODE_IDENT) {
			free(url);
			return;
		}
		LOG(("medium '%s'", node->data));
		if ((node->data_length == 6 &&
				strncmp(node->data, "screen", 6) == 0) ||
				(node->data_length == 3 &&
				strncmp(node->data, "all", 3) == 0)) {
			screen = true;
			break;
		}
		node = node->next;
		if (node == 0 || node->type != CSS_NODE_COMMA) {
			free(url);
			return;
		}
	}
	if (!screen) {
		free(url);
		return;
	}

	/* Make URL absolute */
	res = url_join(url, c->url, &url1);
	if (res != URL_FUNC_OK) {
		free(url);
		return;
	}

	/* Destroy raw url data */
	free(url);

	/* URL must be normalized */
	res = url_normalize(url1, &url);
	if (res != URL_FUNC_OK) {
		free(url1);
		return;
	}

	/* Destroy non-normalized data */
	free(url1);

	/* start the fetch */
	c->data.css.import_count++;
	i = c->data.css.import_count - 1;
	c->data.css.import_content[i] = fetchcache(url,
			css_atimport_callback, (intptr_t) c, i,
			c->width, c->height, true, 0, 0, false, false);
	if (c->data.css.import_content[i]) {
		c->active++;
		fetchcache_go(c->data.css.import_content[i], c->url,
				css_atimport_callback, (intptr_t) c, i,
				c->width, c->height,
				0, 0, false, c->url);
	}

	free(url);
}


/**
 * Fetchcache callback for imported stylesheets.
 */

void css_atimport_callback(content_msg msg, struct content *css,
		intptr_t p1, intptr_t p2, union content_msg_data data)
{
	struct content *c = (struct content *) p1;
	unsigned int i = p2;

	switch (msg) {
		case CONTENT_MSG_LOADING:
			if (css->type != CONTENT_CSS) {
				content_remove_user(css, css_atimport_callback,
						(intptr_t) c, i);
				if (!css->user_list->next) {
					/* We were only user and we don't
					 * want this content, so stop it
					 * fetching and mark it as having
					 * an error so it gets removed from
					 * the cache next time
					 * content_clean() gets called */
					fetch_abort(css->fetch);
					css->fetch = 0;
					css->status = CONTENT_STATUS_ERROR;
				}
				c->data.css.import_content[i] = 0;
				c->active--;
				content_add_error(c, "NotCSS", 0);
			}
			break;

		case CONTENT_MSG_READY:
			break;

		case CONTENT_MSG_DONE:
			LOG(("got imported stylesheet '%s'", css->url));
			/*css_dump_stylesheet(css->data.css);*/
			c->active--;
			break;

		case CONTENT_MSG_AUTH:
		case CONTENT_MSG_SSL:
			/* todo: handle AUTH and SSL */
		case CONTENT_MSG_LAUNCH:
			/* Fall through */
		case CONTENT_MSG_ERROR:
			/* The stylesheet we were fetching may have been
			 * redirected, in that case, the object pointers
			 * will differ, so ensure that the object that's
			 * in error is still in use by us before invalidating
			 * the pointer */
			if (c->data.css.import_content[i] == css) {
				c->data.css.import_content[i] = 0;
				c->active--;
				content_add_error(c, "?", 0);
			}
			break;

		case CONTENT_MSG_STATUS:
			break;

		case CONTENT_MSG_NEWPTR:
			c->data.css.import_content[i] = css;
			break;

		default:
			assert(0);
	}
}


/**
 * Prepare a working stylesheet with pre-sorted lists of selectors from an
 * array of stylesheets.
 *
 * \param  stylesheet_content  array of contents of type CONTENT_CSS (each may
 *                             be 0)
 * \param  stylesheet_count    number of entries in css
 * \return  working stylesheet, or 0 on memory exhaustion
 *
 * See CSS 2.1 6.4.
 */

struct css_working_stylesheet *css_make_working_stylesheet(
		struct content **stylesheet_content,
		unsigned int stylesheet_count)
{
	struct content **css = 0;
	unsigned int css_count = 0;
	struct css_working_stylesheet *working_stylesheet;
	unsigned int chain;
	struct css_selector **rule_scratch;

	working_stylesheet = talloc(0, struct css_working_stylesheet);
	if (!working_stylesheet)
		return 0;

	/* make a complete list of stylesheets involved by walking @imports */
	css_working_list_imports(stylesheet_content, stylesheet_count,
			&css, &css_count);

	rule_scratch = talloc_array(working_stylesheet, struct css_selector *,
			css_count);
	if (!rule_scratch) {
		free(css);
		talloc_free(working_stylesheet);
		return 0;
	}

	/* merge the corresponding sorted hash chains from each stylesheet */
	for (chain = 0; chain != HASH_SIZE; chain++) {
		if (!css_working_merge_chains(working_stylesheet, css,
				css_count, chain, rule_scratch)) {
			free(css);
			talloc_free(working_stylesheet);
			return 0;
		}
	}

	free(css);
	talloc_free(rule_scratch);

#ifdef DEBUG_WORKING_STYLESHEET
	css_dump_working_stylesheet(working_stylesheet);
#endif

	return working_stylesheet;
}


/**
 * Recursively make a list of stylesheets and their imports.
 *
 * \param  import        array of contents of type CONTENT_CSS
 * \param  import_count  number of elements in import
 * \param  css           pointer to array of contents for result
 * \param  css_count     number of elements used so far in *css
 */

bool css_working_list_imports(struct content **import,
		unsigned int import_count,
		struct content ***css, unsigned int *css_count)
{
	unsigned int i, j;
	struct content **css2;
	for (i = 0; i != import_count; i++) {
		if (!import[i])
			continue;
		/* search for import[i] in css[0..css_count) */
		for (j = 0; j != *css_count && (*css)[j] != import[i]; j++)
			;
		if (j != *css_count)
			/* we've seen this stylesheet already */
			continue;
		/* recurse into imports of import[i] */
		if (!css_working_list_imports(import[i]->data.css.
				import_content,
				import[i]->data.css.import_count,
				css, css_count))
			return false;
		css2 = realloc(*css, sizeof *css * (*css_count + 1));
		if (!css2)
			return false;
		*css = css2;
		(*css)[*css_count] = import[i];
		(*css_count)++;
	}
	return true;
}


/**
 * Merge hash chains of rules into an array of pointers ordered by specificity.
 *
 * \param  working_stylesheet  working stylesheet to add array to
 * \param  css        array of contents of type CONTENT_CSS
 * \param  css_count  number of elements in css
 * \param  chain      hash chain index to merge
 * \param  rule       scratch array of css_selector with css_count entries
 * \return  true on success, false if memory exhausted
 */

bool css_working_merge_chains(struct css_working_stylesheet *working_stylesheet,
		struct content **css, unsigned int css_count,
		unsigned int chain,
		struct css_selector **rule)
{
	unsigned int sheet, rules, rules_done = 0;
	struct css_selector *selector;
	unsigned int best = 0;
	unsigned long min;

	/* count total rules */
	rules = 0;
	for (sheet = 0; sheet != css_count; sheet++)
		for (selector = css[sheet]->data.css.css->rule[chain];
				selector;
				selector = selector->next)
			rules++;
	working_stylesheet->rule[chain] = talloc_array(working_stylesheet,
			struct css_selector *, rules + 1);
	if (!working_stylesheet->rule[chain])
		return false;

	/* mergesort by specificity (increasing) */
	for (sheet = 0; sheet != css_count; sheet++) {
		rule[sheet] = 0;
		rule[sheet] = css[sheet]->data.css.css->rule[chain];
	}
	for (; rules_done != rules; rules_done++) {
		/* find rule with lowest specificity */
 		min = ULONG_MAX;
 		for (sheet = 0; sheet != css_count; sheet++) {
 			if (rule[sheet] && rule[sheet]->specificity < min) {
 				min = rule[sheet]->specificity;
 				best = sheet;
 			}
 		}
 		assert(min != ULONG_MAX);
 		working_stylesheet->rule[chain][rules_done] = rule[best];
 		rule[best] = rule[best]->next;
 	}
	assert(rules_done == rules);
	working_stylesheet->rule[chain][rules] = 0;

	return true;
}


/**
 * Find the style which applies to an element.
 *
 * \param  working_stylesheet  working stylesheet
 * \param  element  element in xml tree to match
 * \param  style    style to update
 * \pram   author   updated to indicate properties with author level css
 *                  importance
 *
 * The style is updated with any rules that match the element.
 */

void css_get_style(struct css_working_stylesheet *working_stylesheet,
		xmlNode *element, struct css_style *style,
		struct css_importance *author)
{
	unsigned int hash, rule_0 = 0, rule_h = 0;
	struct css_selector *rule;
	css_importance_reset(author); /* initialise to sub-author level */

	hash = css_hash((const char *) element->name,
			strlen((const char *) element->name));

	/* merge sort rules from special hash chain 0 (universal selector) and
	 * rules from hash chain for element name */
	while (working_stylesheet->rule[0] &&
			working_stylesheet->rule[0][rule_0] &&
			working_stylesheet->rule[hash] &&
			working_stylesheet->rule[hash][rule_h]) {
		if (working_stylesheet->rule[0][rule_0]->specificity <
				working_stylesheet->rule[hash][rule_h]->
				specificity) {
			rule = working_stylesheet->rule[0][rule_0];
			rule_0++;
                } else {
			rule = working_stylesheet->rule[hash][rule_h];
			rule_h++;
		}
		if (css_match_rule(rule, element))
			css_merge(style, rule->style, rule->specificity,
									author);
	}

	/* remaining rules from hash chain 0 */
	while (working_stylesheet->rule[0] &&
			working_stylesheet->rule[0][rule_0]) {
		rule = working_stylesheet->rule[0][rule_0];
		rule_0++;
		if (css_match_rule(rule, element))
			css_merge(style, rule->style, rule->specificity,
									author);
	}

	/* remaining rules from hash chain for element name */
	while (working_stylesheet->rule[hash] &&
			working_stylesheet->rule[hash][rule_h]) {
		rule = working_stylesheet->rule[hash][rule_h];
		rule_h++;
		if (css_match_rule(rule, element))
			css_merge(style, rule->style, rule->specificity,
									author);
	}
}


/**
 * Determine if a rule applies to an element.
 */

bool css_match_rule(struct css_selector *rule, xmlNode *element)
{
	struct css_selector *detail;
	xmlNode *anc, *prev;

	assert(element->type == XML_ELEMENT_NODE);

	if (rule->data && (rule->data_length !=
			strlen((const char *) element->name) ||
			strncasecmp(rule->data, (const char *) element->name,
				rule->data_length) != 0))
		return false;

	for (detail = rule->detail; detail; detail = detail->next) {
		if (!css_match_detail(detail, element))
			return false;
	}

	if (!rule->combiner)
		return true;

	switch (rule->comb) {
		case CSS_COMB_ANCESTOR:
			for (anc = element->parent; anc; anc = anc->parent)
				if (anc->type == XML_ELEMENT_NODE &&
						css_match_rule(rule->combiner, anc))
					return true;
			break;

		case CSS_COMB_PRECEDED:
			for (prev = element->prev;
					prev && prev->type != XML_ELEMENT_NODE;
					prev = prev->prev)
				;
			if (!prev)
				return false;
			return css_match_rule(rule->combiner, prev);
			break;

		case CSS_COMB_PARENT:
			for (anc = element->parent;
					anc && anc->type != XML_ELEMENT_NODE;
					anc = anc->parent)
				;
			if (!anc)
				return false;
			return css_match_rule(rule->combiner, anc);
			break;

		default:
			assert(0);
	}

	return false;
}


/**
 * Determine if a selector detail matches an element.
 *
 * \param  detail   a css_selector of type other than CSS_SELECTOR_ELEMENT
 * \param  element  element in xml tree to match
 * \return  true if the selector matches the element
 */

bool css_match_detail(const struct css_selector *detail,
		xmlNode *element)
{
	bool match = false;
	char *s = 0;
	char *space, *word;
	size_t length;

	switch (detail->type) {
		case CSS_SELECTOR_ID:
			s = (char *) xmlGetProp(element,
					(const xmlChar *) "id");
			/* case sensitive, according to HTML4.01 */
			if (s && strlen(s) == detail->data_length &&
					strncmp(detail->data, s,
					detail->data_length) == 0)
				match = true;
			break;

		case CSS_SELECTOR_CLASS:
			s = (char *) xmlGetProp(element,
					(const xmlChar *) "class");
			if (!s)
				break;
			word = s;
			do {
				space = strchr(word, ' ');
				if (space)
					length = space - word;
				else
					length = strlen(word);
				/* case sensitive, according to HTML4.01 */
				if (length == detail->data_length &&
						strncmp(word, detail->data,
						length) == 0) {
					match = true;
					break;
				}
				word = space + 1;
			} while (space);
			break;

		case CSS_SELECTOR_ATTRIB:
			/* matches if an attribute is present */
			word = strndup(detail->data, detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *) xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (s)
				match = true;
			break;

		case CSS_SELECTOR_ATTRIB_EQ:
			/* matches if an attribute has a certain value*/
			word = strndup(detail->data, detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *) xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (s && strlen(s) == detail->data2_length &&
					strncasecmp(detail->data2, s,
					detail->data2_length) == 0)
				match = true;
			break;

		case CSS_SELECTOR_ATTRIB_INC:
			/* matches if one of the space separated words
			 * in the attribute is equal */
			word = strndup(detail->data,
					detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *) xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (!s)
				break;
			word = s;
			do {
				space = strchr(word, ' ');
				if (space)
					length = space - word;
				else
					length = strlen(word);
				if (length == detail->data2_length &&
						strncasecmp(word, detail->data2,
						length) == 0) {
					match = true;
					break;
				}
				word = space + 1;
			} while (space);
			break;

		case CSS_SELECTOR_ATTRIB_DM:
			/* matches if a prefix up to a hyphen matches */
			word = strndup(detail->data,
					detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *) xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (!s)
				break;
			length = detail->data2_length;
			if (strncasecmp(detail->data2, s, length) == 0 &&
					(s[length] == '-' || s[length] == 0))
				match = true;
			break;

		case CSS_SELECTOR_ATTRIB_PRE:
			/* matches if the attribute begins with a certain
			 * value (CSS3) */
			word = strndup(detail->data, detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *)xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (s && strncasecmp(detail->data2, s,
					detail->data2_length) == 0)
				match = true;
			break;

		case CSS_SELECTOR_ATTRIB_SUF:
			/* matches if the attribute ends with a certain
			 * value (CSS3) */
			word = strndup(detail->data, detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *)xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (!s)
				break;
			length = strlen(s);
			if (detail->data2_length <= length) {
				word = s + (length - detail->data2_length);
				if (s && strncasecmp(detail->data2, word,
						detail->data2_length) == 0)
					match = true;
			}
			break;

		case CSS_SELECTOR_ATTRIB_SUB:
			/* matches if the attribute contains a certain
			 * value (CSS3) */
			word = strndup(detail->data, detail->data_length);
			if (!word) {
				/** \todo report to user */
				return false;
			}
			s = (char *)xmlGetProp(element,
					(const xmlChar *) word);
			free(word);
			if (!s)
				break;
			/* case insensitive strstr follows */
			/* space -> last possible start position */
			/* word -> start of string to search */
			space = s + (strlen(s) - detail->data2_length);
			word = s;
			while (word <= space) {
				if (strncasecmp(detail->data2, word,
						detail->data2_length) == 0) {
					match = true;
					break;
				}
				word++;
			}
			break;

		case CSS_SELECTOR_PSEUDO:
			if (detail->data_length == 11 &&
				strncasecmp(detail->data,
						"first-child", 11) == 0) {
				match = css_match_first_child(detail,
								element);
			}
			break;

		default:
			assert(0);
	}

	if (s)
		xmlFree(s);

	return match;
}


/**
 * Handle :first-child pseudo-class.
 *
 * \param  detail   a css_selector of type other than CSS_SELECTOR_ELEMENT
 * \param  element  element in xml tree to match
 * \return  true if the selector matches the element
 */

bool css_match_first_child(const struct css_selector *detail,
		xmlNode *element)
{
	xmlNode *prev;

	for (prev = element->prev; prev && prev->type != XML_ELEMENT_NODE;
						prev = prev->prev)
		;

	if (!prev)
		return true;

	return false;
}


/**
 * Parse a stand-alone CSS property list.
 *
 * \param  c      parent content
 * \param  style  css_style to update
 * \param  str    property list, as found in HTML style attributes
 */

void css_parse_property_list(struct content *c, struct css_style * style,
                            char * str)
{
	unsigned char *source_data;
	unsigned char *current, *end, *token_text;
	size_t length;
	unsigned int i;
	int token;
	void *parser;
	struct css_parser_params param = {true, c, 0, false, false, false};
	struct css_parser_token token_data;
	const struct css_parser_token token_start = { "{", 1 };
	const struct css_parser_token token_end = { "}", 1 };

	length = strlen(str);

	parser = css_parser_Alloc(malloc);
	source_data = malloc(length + 10);

	if (!parser || !source_data) {
		free(parser);
		css_parser_Free(parser, free);
		return;
	}

	strcpy((char *) source_data, str);
	for (i = 0; i != 10; i++)
		source_data[length + i] = 0;

	css_parser_(parser, LBRACE, token_start, &param);

	current = source_data;
	end = source_data + strlen(str);
	while (current < end
			&& (token = css_tokenise(&current, end + 10,
			&token_text))) {
		token_data.text = (char *) token_text;
		token_data.length = current - token_text;
		css_parser_(parser, token, token_data, &param);
		if (param.syntax_error) {
			LOG(("syntax error near offset %li",
				(unsigned long) (token_text - source_data)));
			param.syntax_error = false;
		} else if (param.memory_error) {
			LOG(("out of memory"));
			break;
		}
	}
	css_parser_(parser, RBRACE, token_end, &param);
	css_parser_(parser, 0, token_data, &param);

	css_parser_Free(parser, free);

	if (param.memory_error) {
		css_free_node(param.declaration);
		return;
	}

	css_add_declarations(style, param.declaration);

	css_free_node(param.declaration);

	free(source_data);
}


/**
 * Dump a css_style to stderr in CSS-like syntax.
 */

void css_dump_style(FILE *stream, const struct css_style * const style)
{
	unsigned int i;
	fprintf(stream, "{ ");

#define DUMP_COLOR(z, s) \
	if (style->z != CSS_COLOR_NOT_SET) {				\
		if (style->z == TRANSPARENT)				\
			fprintf(stream, s ": transparent; ");		\
		else if (style->z == CSS_COLOR_NONE)			\
			fprintf(stream, s ": none; ");			\
		else							\
			fprintf(stream, s ": #%.6x; ", style->z);	\
	}

#define DUMP_KEYWORD(z, s, n) \
	if (style->z != css_empty_style.z)				\
		fprintf(stream, s ": %s; ", n[style->z]);

	DUMP_COLOR(background_color, "background-color");
	if (style->background_attachment !=
			css_empty_style.background_attachment ||
			style->background_image.type !=
			css_empty_style.background_image.type ||
			style->background_position.horz.pos !=
			css_empty_style.background_position.horz.pos ||
			style->background_position.vert.pos !=
			css_empty_style.background_position.vert.pos ||
			style->background_repeat !=
			css_empty_style.background_repeat) {
		fprintf(stream, "background:");
		switch (style->background_image.type) {
		case CSS_BACKGROUND_IMAGE_NONE:
			fprintf(stream, " none");
			break;
		case CSS_BACKGROUND_IMAGE_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_BACKGROUND_IMAGE_URI:
			fprintf(stream, " (%p) \"%s\"",
					style->background_image.uri,
					style->background_image.uri);
			break;
		case CSS_BACKGROUND_IMAGE_NOT_SET:
			;
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}

		if (style->background_repeat ==
				CSS_BACKGROUND_REPEAT_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->background_repeat ==
				CSS_BACKGROUND_REPEAT_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_background_repeat_name[
						style->background_repeat]);

		if (style->background_attachment ==
				CSS_BACKGROUND_ATTACHMENT_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->background_attachment == CSS_BACKGROUND_ATTACHMENT_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_background_attachment_name[
					style->background_attachment]);

		switch (style->background_position.horz.pos) {
		case CSS_BACKGROUND_POSITION_LENGTH:
			fprintf(stream, " ");
			css_dump_length(stream, &style->background_position.
					horz.value.length);
			break;
		case CSS_BACKGROUND_POSITION_PERCENT:
			fprintf(stream, " %g%%",
					style->background_position.
					horz.value.percent);
			break;
		case CSS_BACKGROUND_POSITION_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_BACKGROUND_POSITION_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}
		switch (style->background_position.vert.pos) {
		case CSS_BACKGROUND_POSITION_LENGTH:
			fprintf(stream, " ");
			css_dump_length(stream, &style->background_position.
					vert.value.length);
			break;
		case CSS_BACKGROUND_POSITION_PERCENT:
			fprintf(stream, " %g%%",
					style->background_position.
					vert.value.percent);
			break;
		case CSS_BACKGROUND_POSITION_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_BACKGROUND_POSITION_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}
	for (i = 0; i != 4; i++) {
		if (style->border[i].color != CSS_COLOR_NOT_SET ||
				style->border[i].width.width !=
				CSS_BORDER_WIDTH_NOT_SET ||
				style->border[i].style !=
				CSS_BORDER_STYLE_NOT_SET) {
			fprintf(stream, "border-");
			switch (i) {
			case TOP:
				fprintf(stream, "top:");
				break;
			case RIGHT:
				fprintf(stream, "right:");
				break;
			case BOTTOM:
				fprintf(stream, "bottom:");
				break;
			case LEFT:
				fprintf(stream, "left:");
				break;
			}
			switch (style->border[i].width.width) {
			case CSS_BORDER_WIDTH_INHERIT:
				fprintf(stream, " inherit");
				break;
			case CSS_BORDER_WIDTH_LENGTH:
				fprintf(stream, " ");
				css_dump_length(stream,
						&style->border[i].width.value);
				break;
			case CSS_BORDER_WIDTH_NOT_SET:
				break;
			default:
				fprintf(stream, " UNKNOWN");
				break;
			}

			if (style->border[i].style ==
					CSS_BORDER_STYLE_UNKNOWN)
				fprintf(stream, " UNKNOWN");
			else if (style->border[i].style ==
					CSS_BORDER_STYLE_NOT_SET)
				;
			else
				fprintf(stream, " %s",
					css_border_style_name[
						style->border[i].style]);

			if (style->border[i].color == TRANSPARENT)
				fprintf(stream, " transparent");
			else if (style->border[i].color == CSS_COLOR_NONE)
				fprintf(stream, " none");
			else if (style->border[i].color == CSS_COLOR_INHERIT)
				fprintf(stream, " inherit");
			else if (style->border[i].color == CSS_COLOR_NOT_SET)
				;
			else
				fprintf(stream, " #%.6x",
						style->border[i].color);
			fprintf(stream, "; ");
		}
	}
	DUMP_KEYWORD(border_collapse, "border-collapse",
			css_border_collapse_name);
	if (style->border_spacing.border_spacing !=
			CSS_BORDER_SPACING_NOT_SET) {
		fprintf(stream, "border-spacing: ");
		css_dump_length(stream, &style->border_spacing.horz);
		fprintf(stream, " ");
		css_dump_length(stream, &style->border_spacing.vert);
		fprintf(stream, "; ");
	}

	DUMP_KEYWORD(caption_side, "caption-side", css_caption_side_name);
	DUMP_KEYWORD(clear, "clear", css_clear_name);

	if (style->clip.clip != CSS_CLIP_NOT_SET) {
		fprintf(stream, "clip: ");
		switch (style->clip.clip) {
		case CSS_CLIP_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_CLIP_AUTO:
			fprintf(stream, "auto");
			break;
		case CSS_CLIP_RECT:
			fprintf(stream, "rect(");
			for (i = 0; i != 4; i++) {
				switch (style->clip.rect[i].rect) {
				case CSS_CLIP_RECT_AUTO:
					fprintf(stream, "auto");
					break;
				case CSS_CLIP_RECT_LENGTH:
					css_dump_length(stream,
						&style->clip.rect[i].value);
					break;
				}
				if (i != 3)
					fprintf(stream, ", ");
			}
			fprintf(stream, ")");
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}
	DUMP_COLOR(color, "color");
	DUMP_KEYWORD(cursor, "cursor", css_cursor_name);
	DUMP_KEYWORD(direction, "direction", css_direction_name);
	DUMP_KEYWORD(display, "display", css_display_name);
	DUMP_KEYWORD(empty_cells, "empty-cells", css_empty_cells_name);
	DUMP_KEYWORD(float_, "float", css_float_name);

	if (style->font_style != CSS_FONT_STYLE_NOT_SET ||
			style->font_weight != CSS_FONT_WEIGHT_NOT_SET ||
			style->font_size.size != CSS_FONT_SIZE_NOT_SET ||
			style->line_height.size != CSS_LINE_HEIGHT_NOT_SET ||
			style->font_family != CSS_FONT_FAMILY_NOT_SET ||
			style->font_variant != CSS_FONT_VARIANT_NOT_SET) {
		fprintf(stream, "font:");

		if (style->font_style == CSS_FONT_STYLE_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->font_style == CSS_FONT_STYLE_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_font_style_name[style->font_style]);

		if (style->font_weight == CSS_FONT_WEIGHT_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->font_weight == CSS_FONT_WEIGHT_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_font_weight_name[style->font_weight]);

		switch (style->font_size.size) {
		case CSS_FONT_SIZE_ABSOLUTE:
			fprintf(stream, " [%g]",
				style->font_size.value.absolute);
			break;
		case CSS_FONT_SIZE_LENGTH:
			fprintf(stream, " ");
			css_dump_length(stream, &style->font_size.value.length);
			break;
		case CSS_FONT_SIZE_PERCENT:
			fprintf(stream, " %g%%",
				style->font_size.value.percent);
			break;
		case CSS_FONT_SIZE_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_FONT_SIZE_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}
		switch (style->line_height.size) {
		case CSS_LINE_HEIGHT_ABSOLUTE:
			fprintf(stream, "/[%g]",
				style->line_height.value.absolute);
				break;
		case CSS_LINE_HEIGHT_LENGTH:
			fprintf(stream, "/");
			css_dump_length(stream,
					&style->line_height.value.length);
			break;
		case CSS_LINE_HEIGHT_PERCENT:
			fprintf(stream, "/%g%%",
				style->line_height.value.percent);
				break;
		case CSS_LINE_HEIGHT_INHERIT:
			fprintf(stream, "/inherit");
			break;
		case CSS_LINE_HEIGHT_NOT_SET:
			break;
		default:
			fprintf(stream, "/UNKNOWN");
			break;
		}
		if (style->font_family == CSS_FONT_FAMILY_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->font_family == CSS_FONT_FAMILY_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_font_family_name[style->font_family]);

		if (style->font_variant == CSS_FONT_VARIANT_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->font_variant == CSS_FONT_VARIANT_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_font_variant_name[style->font_variant]);
		fprintf(stream, "; ");
	}

	if (style->height.height != CSS_HEIGHT_NOT_SET) {
		fprintf(stream, "height: ");
		switch (style->height.height) {
		case CSS_HEIGHT_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_HEIGHT_AUTO:
			fprintf(stream, "auto");
			break;
		case CSS_HEIGHT_LENGTH:
			css_dump_length(stream, &style->height.value.length);
			break;
		case CSS_HEIGHT_PERCENT:
			fprintf(stream, "%g%%",
				style->height.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->letter_spacing.letter_spacing !=
			CSS_LETTER_SPACING_NOT_SET) {
		fprintf(stream, "letter-spacing: ");
		switch (style->letter_spacing.letter_spacing) {
		case CSS_LETTER_SPACING_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_LETTER_SPACING_NORMAL:
			fprintf(stream, "normal");
			break;
		case CSS_LETTER_SPACING_LENGTH:
			css_dump_length(stream, &style->letter_spacing.length);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->list_style_type != CSS_LIST_STYLE_TYPE_NOT_SET ||
			style->list_style_position !=
			CSS_LIST_STYLE_POSITION_NOT_SET ||
			style->list_style_image.type !=
			CSS_LIST_STYLE_IMAGE_NOT_SET) {
		fprintf(stream, "list-style:");

		if (style->list_style_type == CSS_LIST_STYLE_TYPE_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->list_style_type == CSS_LIST_STYLE_TYPE_NOT_SET)
			;
		else
			fprintf(stream, " %s",
					css_list_style_type_name[
						style->list_style_type]);

		if (style->list_style_position ==
				CSS_LIST_STYLE_POSITION_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->list_style_position ==
				CSS_LIST_STYLE_POSITION_NOT_SET)
			;
		else
			fprintf(stream, " %s",
					css_list_style_position_name[
						style->list_style_position]);

		switch (style->list_style_image.type) {
		case CSS_LIST_STYLE_IMAGE_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_LIST_STYLE_IMAGE_NONE:
			fprintf(stream, " none");
			break;
		case CSS_LIST_STYLE_IMAGE_URI:
			fprintf(stream, " url('%s')",
				style->list_style_image.uri);
			break;
		case CSS_LIST_STYLE_IMAGE_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
		}
		fprintf(stream, "; ");
	}

	if (style->margin[0].margin != CSS_MARGIN_NOT_SET ||
			style->margin[1].margin != CSS_MARGIN_NOT_SET ||
			style->margin[2].margin != CSS_MARGIN_NOT_SET ||
			style->margin[3].margin != CSS_MARGIN_NOT_SET) {
		fprintf(stream, "margin:");
		for (i = 0; i != 4; i++) {
			switch (style->margin[i].margin) {
			case CSS_MARGIN_INHERIT:
				fprintf(stream, " inherit");
				break;
			case CSS_MARGIN_LENGTH:
				fprintf(stream, " ");
				css_dump_length(stream,
						&style->margin[i].value.length);
				break;
			case CSS_MARGIN_PERCENT:
				fprintf(stream, " %g%%",
					style->margin[i].value.percent);
				break;
			case CSS_MARGIN_AUTO:
				fprintf(stream, " auto");
				break;
			case CSS_MARGIN_NOT_SET:
				fprintf(stream, " .");
				break;
			default:
				fprintf(stream, " UNKNOWN");
				break;
			}
		}
		fprintf(stream, "; ");
	}

	if (style->max_height.max_height != CSS_MAX_HEIGHT_NOT_SET) {
		fprintf(stream, "max-height: ");
		switch (style->max_height.max_height) {
		case CSS_MAX_HEIGHT_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_MAX_HEIGHT_NONE:
			fprintf(stream, "none");
			break;
		case CSS_MAX_HEIGHT_LENGTH:
			css_dump_length(stream,
					&style->max_height.value.length);
			break;
		case CSS_MAX_HEIGHT_PERCENT:
			fprintf(stream, "%g%%",
				style->max_height.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->max_width.max_width != CSS_MAX_WIDTH_NOT_SET) {
		fprintf(stream, "max-width: ");
		switch (style->max_width.max_width) {
		case CSS_MAX_WIDTH_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_MAX_WIDTH_NONE:
			fprintf(stream, "none");
			break;
		case CSS_MAX_WIDTH_LENGTH:
			css_dump_length(stream, &style->max_width.value.length);
			break;
		case CSS_MAX_WIDTH_PERCENT:
			fprintf(stream, "%g%%",
				style->max_width.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->min_height.min_height != CSS_MIN_HEIGHT_NOT_SET) {
		fprintf(stream, "min-height: ");
		switch (style->min_height.min_height) {
		case CSS_MIN_HEIGHT_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_MIN_HEIGHT_LENGTH:
			css_dump_length(stream,
					&style->min_height.value.length);
			break;
		case CSS_MIN_HEIGHT_PERCENT:
			fprintf(stream, "%g%%",
				style->min_height.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->min_width.min_width != CSS_MIN_WIDTH_NOT_SET) {
		fprintf(stream, "min-width: ");
		switch (style->min_width.min_width) {
		case CSS_MIN_WIDTH_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_MIN_WIDTH_LENGTH:
			css_dump_length(stream, &style->min_width.value.length);
			break;
		case CSS_MIN_WIDTH_PERCENT:
			fprintf(stream, "%g%%",
				style->min_width.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->orphans.orphans != CSS_ORPHANS_NOT_SET) {
		fprintf(stream, "orphans: ");
		switch (style->orphans.orphans) {
		case CSS_ORPHANS_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_ORPHANS_INTEGER:
			fprintf(stream, "%d",
				style->orphans.value);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->outline.color.color != CSS_OUTLINE_COLOR_NOT_SET ||
		style->outline.width.width != CSS_BORDER_WIDTH_NOT_SET ||
		style->outline.style != CSS_BORDER_STYLE_NOT_SET) {
		fprintf(stream, "outline:");
		switch (style->outline.color.color) {
		case CSS_OUTLINE_COLOR_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_OUTLINE_COLOR_INVERT:
			fprintf(stream, " invert");
			break;
		case CSS_OUTLINE_COLOR_COLOR:
			if (style->outline.color.value == TRANSPARENT)
				fprintf(stream, " transparent");
			else if (style->outline.color.value == CSS_COLOR_NONE)
				fprintf(stream, " none");
			else if (style->outline.color.value == CSS_COLOR_INHERIT)
				fprintf(stream, " inherit");
			else if (style->outline.color.value == CSS_COLOR_NOT_SET)
				fprintf(stream, " .");
			else
				fprintf(stream, " #%.6x", style->outline.color.value);
			break;
		case CSS_OUTLINE_COLOR_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}

		if (style->outline.style == CSS_BORDER_STYLE_UNKNOWN)
			fprintf(stream, " UNKNOWN");
		else if (style->outline.style == CSS_BORDER_STYLE_NOT_SET)
			;
		else
			fprintf(stream, " %s",
				css_border_style_name[style->outline.style]);

		switch (style->outline.width.width) {
		case CSS_BORDER_WIDTH_INHERIT:
			fprintf(stream, " inherit");
			break;
		case CSS_BORDER_WIDTH_LENGTH:
			fprintf(stream, " ");
			css_dump_length(stream, &style->outline.width.value);
			break;
		case CSS_BORDER_WIDTH_NOT_SET:
			break;
		default:
			fprintf(stream, " UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	DUMP_KEYWORD(overflow, "overflow", css_overflow_name);

	if (style->padding[0].padding != CSS_PADDING_NOT_SET ||
			style->padding[1].padding != CSS_PADDING_NOT_SET ||
			style->padding[2].padding != CSS_PADDING_NOT_SET ||
			style->padding[3].padding != CSS_PADDING_NOT_SET) {
		fprintf(stream, "padding:");
		for (i = 0; i != 4; i++) {
			switch (style->padding[i].padding) {
			case CSS_PADDING_INHERIT:
				fprintf(stream, " inherit");
				break;
			case CSS_PADDING_LENGTH:
				fprintf(stream, " ");
				css_dump_length(stream,
					&style->padding[i].value.length);
				break;
			case CSS_PADDING_PERCENT:
				fprintf(stream, " %g%%",
					style->padding[i].value.percent);
				break;
			case CSS_PADDING_NOT_SET:
				fprintf(stream, " .");
				break;
			default:
				fprintf(stream, " UNKNOWN");
				break;
			}
		}
		fprintf(stream, "; ");
	}

	DUMP_KEYWORD(page_break_after, "page-break-after",
			css_page_break_after_name);
	DUMP_KEYWORD(page_break_before, "page-break-before",
			css_page_break_before_name);
	DUMP_KEYWORD(page_break_inside, "page-break-inside",
			css_page_break_inside_name);

	for (i = 0; i != 4; i++) {
		if (style->pos[i].pos != CSS_POS_NOT_SET) {
			switch (i) {
			case TOP:
				fprintf(stream, "top: ");
				break;
			case RIGHT:
				fprintf(stream, "right: ");
				break;
			case BOTTOM:
				fprintf(stream, "bottom: ");
				break;
			case LEFT:
				fprintf(stream, "left: ");
				break;
			}
			switch (style->pos[i].pos) {
			case CSS_POS_INHERIT:
				fprintf(stream, "inherit");
				break;
			case CSS_POS_AUTO:
				fprintf(stream, "auto");
				break;
			case CSS_POS_PERCENT:
				fprintf(stream, "%g%%",
						style->pos[i].value.percent);
				break;
			case CSS_POS_LENGTH:
				css_dump_length(stream,
						&style->pos[i].value.length);
				break;
			default:
				fprintf(stream, "UNKNOWN");
				break;
			}
			fprintf(stream, "; ");
		}
	}
	DUMP_KEYWORD(position, "position", css_position_name);

	DUMP_KEYWORD(table_layout, "table-layout", css_table_layout_name);
	DUMP_KEYWORD(text_align, "text-align", css_text_align_name);

	if (style->text_decoration != CSS_TEXT_DECORATION_NOT_SET) {
		fprintf(stream, "text-decoration:");
		if (style->text_decoration == CSS_TEXT_DECORATION_NONE)
			fprintf(stream, " none");
		if (style->text_decoration == CSS_TEXT_DECORATION_INHERIT)
			fprintf(stream, " inherit");
		if (style->text_decoration & CSS_TEXT_DECORATION_UNDERLINE)
			fprintf(stream, " underline");
		if (style->text_decoration & CSS_TEXT_DECORATION_OVERLINE)
			fprintf(stream, " overline");
		if (style->text_decoration & CSS_TEXT_DECORATION_LINE_THROUGH)
			fprintf(stream, " line-through");
		if (style->text_decoration & CSS_TEXT_DECORATION_BLINK)
			fprintf(stream, " blink");
		fprintf(stream, "; ");
	}

	if (style->text_indent.size != CSS_TEXT_INDENT_NOT_SET) {
		fprintf(stream, "text-indent: ");
		switch (style->text_indent.size) {
		case CSS_TEXT_INDENT_LENGTH:
			css_dump_length(stream,
					&style->text_indent.value.length);
			break;
		case CSS_TEXT_INDENT_PERCENT:
			fprintf(stream, "%g%%",
				style->text_indent.value.percent);
			break;
		case CSS_TEXT_INDENT_INHERIT:
			fprintf(stream, "inherit");
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	DUMP_KEYWORD(text_transform, "text-transform", css_text_transform_name);

	DUMP_KEYWORD(unicode_bidi, "unicode-bidi", css_unicode_bidi_name);

	if (style->vertical_align.type != CSS_VERTICAL_ALIGN_NOT_SET) {
		fprintf(stream, "vertical-align: ");
		switch (style->vertical_align.type) {
		case CSS_VERTICAL_ALIGN_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_VERTICAL_ALIGN_BASELINE:
			fprintf(stream, "baseline");
			break;
		case CSS_VERTICAL_ALIGN_SUB:
			fprintf(stream, "sub");
			break;
		case CSS_VERTICAL_ALIGN_SUPER:
			fprintf(stream, "super");
			break;
		case CSS_VERTICAL_ALIGN_TOP:
			fprintf(stream, "top");
			break;
		case CSS_VERTICAL_ALIGN_TEXT_TOP:
			fprintf(stream, "text-top");
			break;
		case CSS_VERTICAL_ALIGN_MIDDLE:
			fprintf(stream, "middle");
			break;
		case CSS_VERTICAL_ALIGN_BOTTOM:
			fprintf(stream, "bottom");
			break;
		case CSS_VERTICAL_ALIGN_TEXT_BOTTOM:
			fprintf(stream, "text-bottom");
			break;
		case CSS_VERTICAL_ALIGN_LENGTH:
			css_dump_length(stream,
					&style->vertical_align.value.length);
			break;
		case CSS_VERTICAL_ALIGN_PERCENT:
			fprintf(stream, "%g%%",
				style->vertical_align.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	DUMP_KEYWORD(visibility, "visibility", css_visibility_name);
	DUMP_KEYWORD(white_space, "white-space", css_white_space_name);

	if (style->widows.widows != CSS_WIDOWS_NOT_SET) {
		fprintf(stream, "widows: ");
		switch (style->widows.widows) {
		case CSS_WIDOWS_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_WIDOWS_INTEGER:
			fprintf(stream, "%d",
				style->widows.value);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->width.width != CSS_WIDTH_NOT_SET) {
		fprintf(stream, "width: ");
		switch (style->width.width) {
		case CSS_WIDTH_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_WIDTH_AUTO:
			fprintf(stream, "auto");
			break;
		case CSS_WIDTH_LENGTH:
			css_dump_length(stream, &style->width.value.length);
			break;
		case CSS_WIDTH_PERCENT:
			fprintf(stream, "%g%%", style->width.value.percent);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->word_spacing.word_spacing != CSS_WORD_SPACING_NOT_SET) {
		fprintf(stream, "word-spacing: ");
		switch (style->word_spacing.word_spacing) {
		case CSS_WORD_SPACING_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_WORD_SPACING_NORMAL:
			fprintf(stream, "normal");
			break;
		case CSS_WORD_SPACING_LENGTH:
			css_dump_length(stream, &style->word_spacing.length);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	if (style->z_index.z_index != CSS_Z_INDEX_NOT_SET) {
		fprintf(stream, "z-index: ");
		switch (style->z_index.z_index) {
		case CSS_Z_INDEX_INHERIT:
			fprintf(stream, "inherit");
			break;
		case CSS_Z_INDEX_AUTO:
			fprintf(stream, "auto");
			break;
		case CSS_Z_INDEX_INTEGER:
			fprintf(stream, "%d",
				style->z_index.value);
			break;
		default:
			fprintf(stream, "UNKNOWN");
			break;
		}
		fprintf(stream, "; ");
	}

	fprintf(stream, "}");
}


/**
 * Dump a css_length to the given stream
 */

void css_dump_length(FILE *stream, const struct css_length * const length)
{
	if (fabs(length->value) < 0.0001)
		fprintf(stream, "0");
	else
		fprintf(stream, "%g%s", length->value,
				css_unit_name[length->unit]);
}

#ifdef DEBUG_WORKING_STYLESHEET
/**
 * Dump a complete css_working_stylesheet to stderr in CSS syntax.
 */

void css_dump_working_stylesheet(const struct css_working_stylesheet *ws)
{
	unsigned int i, j;

	for (i = 0; i != HASH_SIZE; i++) {
		/*fprintf(stderr, "hash %i:\n", i);*/
		for (j = 0; ws->rule[i][j]; j++) {
			css_dump_selector(ws->rule[i][j]);
			fprintf(stderr, " <%lx> ", ws->rule[i][j]->specificity);
			css_dump_style(ws->rule[i][j]->style);
			fprintf(stderr, "\n");
		}
	}
}
#endif

/**
 * Set all members to false
 */
void css_importance_reset(struct css_importance *i) {
	int j;
	i->background_color = false;
	i->background_image = false;
	i->border_spacing = false;
	i->color = false;
	i->height = false;
	i->width = false;

	/**< top, right, bottom, left */
	for (j = 0; j < 4; j++) {
		i->border_color[j] = false;
		i->border_style[j] = false;
		i->border_width[j] = false;
		i->margin[j] = false;
		i->padding[j] = false;
	}
}

/**
 * Dump a complete css_stylesheet to stderr in CSS syntax.
 */

void css_dump_stylesheet(const struct css_stylesheet * stylesheet)
{
	unsigned int i;
	struct css_selector *r;
	for (i = 0; i != HASH_SIZE; i++) {
		/*fprintf(stderr, "hash %i:\n", i);*/
		for (r = stylesheet->rule[i]; r != 0; r = r->next) {
			css_dump_selector(r);
			fprintf(stderr, " <%lx> ", r->specificity);
			css_dump_style(stderr, r->style);
			fprintf(stderr, "\n");
		}
	}
}


/**
 * Dump a css_selector to stderr in CSS syntax.
 */

void css_dump_selector(const struct css_selector *r)
{
	struct css_selector *m;

	if (r->combiner)
		css_dump_selector(r->combiner);

	switch (r->comb) {
		case CSS_COMB_NONE:     break;
		case CSS_COMB_ANCESTOR: fprintf(stderr, " "); break;
		case CSS_COMB_PARENT:   fprintf(stderr, " > "); break;
		case CSS_COMB_PRECEDED: fprintf(stderr, " + "); break;
	}

	if (r->data)
		fprintf(stderr, "%.*s", r->data_length, r->data);
	else
		fprintf(stderr, "*");

	for (m = r->detail; m; m = m->next) {
		switch (m->type) {
			case CSS_SELECTOR_ID:
				fprintf(stderr, "#%.*s",
						m->data_length, m->data);
				break;
			case CSS_SELECTOR_CLASS:
				fprintf(stderr, ".%.*s",
						m->data_length,	m->data);
				break;
			case CSS_SELECTOR_ATTRIB:
				fprintf(stderr, "[%.*s]",
						m->data_length, m->data);
				break;
			case CSS_SELECTOR_ATTRIB_EQ:
				fprintf(stderr, "[%.*s=%.*s]",
						m->data_length,	m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_ATTRIB_INC:
				fprintf(stderr, "[%.*s~=%.*s]",
						m->data_length, m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_ATTRIB_DM:
				fprintf(stderr, "[%.*s|=%.*s]",
						m->data_length, m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_ATTRIB_PRE:
				fprintf(stderr, "[%.*s^=%.*s]",
						m->data_length, m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_ATTRIB_SUF:
				fprintf(stderr, "[%.*s$=%.*s]",
						m->data_length, m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_ATTRIB_SUB:
				fprintf(stderr, "[%.*s*=%.*s]",
						m->data_length, m->data,
						m->data2_length, m->data2);
				break;
			case CSS_SELECTOR_PSEUDO:
				fprintf(stderr, ":%.*s",
						m->data_length, m->data);
				break;
			default:
				fprintf(stderr, "(unexpected detail)");
		}
	}
}


/**
 * Cascade styles.
 *
 * \param  style	   css_style to modify
 * \param  apply	   css_style to cascade onto style
 * \param  author	   updated to indicate which properties have greater
 *			   than author level CSS importance. (NULL if
 *			   importance isn't required.)
 *
 * Attributes which have the value 'inherit' or 'unset' in apply are
 * unchanged in style.
 * Other attributes are copied to style, calculating percentages relative to
 * style where applicable.
 */

void css_cascade(struct css_style * const style,
		const struct css_style * const apply,
		struct css_importance * const author)
{
	unsigned int i;
	float f;

	if (apply->background_attachment !=
			CSS_BACKGROUND_ATTACHMENT_INHERIT &&
				apply->background_attachment !=
					CSS_BACKGROUND_ATTACHMENT_NOT_SET)
		style->background_attachment = apply->background_attachment;
	if (apply->background_color != CSS_COLOR_INHERIT &&
			apply->background_color != CSS_COLOR_NOT_SET)
		style->background_color = apply->background_color;
	if (apply->background_image.type != CSS_BACKGROUND_IMAGE_INHERIT &&
			apply->background_image.type !=
				CSS_BACKGROUND_IMAGE_NOT_SET)
		style->background_image = apply->background_image;
	if (apply->background_repeat != CSS_BACKGROUND_REPEAT_INHERIT &&
			apply->background_repeat !=
				CSS_BACKGROUND_REPEAT_NOT_SET)
		style->background_repeat = apply->background_repeat;
	if (apply->border_collapse != CSS_BORDER_COLLAPSE_INHERIT &&
			apply->border_collapse != CSS_BORDER_COLLAPSE_NOT_SET)
		style->border_collapse = apply->border_collapse;
	if (apply->border_spacing.border_spacing !=
			CSS_BORDER_SPACING_INHERIT &&
				apply->border_spacing.border_spacing !=
					CSS_BORDER_SPACING_NOT_SET)
		style->border_spacing = apply->border_spacing;
	if (apply->caption_side != CSS_CAPTION_SIDE_INHERIT &&
			apply->caption_side != CSS_CAPTION_SIDE_NOT_SET)
		style->caption_side = apply->caption_side;
	if (apply->clear != CSS_CLEAR_INHERIT &&
			apply->clear != CSS_CLEAR_NOT_SET)
		style->clear = apply->clear;
	if (apply->color != CSS_COLOR_INHERIT &&
			apply->color != CSS_COLOR_NOT_SET)
		style->color = apply->color;
	if (apply->content.type != CSS_CONTENT_INHERIT &&
			apply->content.type != CSS_CONTENT_NOT_SET)
		style->content = apply->content;
	if (apply->counter_reset.type != CSS_COUNTER_RESET_INHERIT &&
			apply->counter_reset.type != CSS_COUNTER_RESET_NOT_SET)
		style->counter_reset = apply->counter_reset;
	if (apply->counter_increment.type != CSS_COUNTER_INCREMENT_INHERIT &&
			apply->counter_increment.type != CSS_COUNTER_INCREMENT_NOT_SET)
		style->counter_increment = apply->counter_increment;
	if (apply->cursor != CSS_CURSOR_INHERIT &&
			apply->cursor != CSS_CURSOR_NOT_SET)
		style->cursor = apply->cursor;
	if (apply->direction != CSS_DIRECTION_INHERIT &&
			apply->direction != CSS_DIRECTION_NOT_SET)
		style->direction = apply->direction;
	if (apply->display != CSS_DISPLAY_INHERIT &&
			apply->display != CSS_DISPLAY_NOT_SET)
		style->display = apply->display;
	if (apply->empty_cells != CSS_EMPTY_CELLS_INHERIT &&
			apply->empty_cells != CSS_EMPTY_CELLS_NOT_SET)
		style->empty_cells = apply->empty_cells;
	if (apply->float_ != CSS_FLOAT_INHERIT &&
			apply->float_ != CSS_FLOAT_NOT_SET)
		style->float_ = apply->float_;
	if (apply->font_family != CSS_FONT_FAMILY_INHERIT &&
			apply->font_family != CSS_FONT_FAMILY_NOT_SET)
		style->font_family = apply->font_family;
	if (apply->font_style != CSS_FONT_STYLE_INHERIT &&
			apply->font_style != CSS_FONT_STYLE_NOT_SET)
		style->font_style = apply->font_style;
	if (apply->font_variant != CSS_FONT_VARIANT_INHERIT &&
			apply->font_variant != CSS_FONT_VARIANT_NOT_SET)
		style->font_variant = apply->font_variant;
	if (apply->font_weight != CSS_FONT_WEIGHT_INHERIT &&
			apply->font_weight != CSS_FONT_WEIGHT_NOT_SET)
		style->font_weight = apply->font_weight;
	if (apply->height.height != CSS_HEIGHT_INHERIT &&
			apply->height.height != CSS_HEIGHT_NOT_SET)
		style->height = apply->height;
	if (apply->letter_spacing.letter_spacing !=
			CSS_LETTER_SPACING_INHERIT &&
				apply->letter_spacing.letter_spacing !=
					CSS_LETTER_SPACING_NOT_SET)
		style->letter_spacing = apply->letter_spacing;
	if (apply->line_height.size != CSS_LINE_HEIGHT_INHERIT &&
			apply->line_height.size != CSS_LINE_HEIGHT_NOT_SET)
		style->line_height = apply->line_height;
	if (apply->list_style_image.type != CSS_LIST_STYLE_IMAGE_INHERIT &&
			apply->list_style_image.type !=
				CSS_LIST_STYLE_IMAGE_NOT_SET)
		style->list_style_image = apply->list_style_image;
	if (apply->list_style_position != CSS_LIST_STYLE_POSITION_INHERIT &&
			apply->list_style_position !=
				CSS_LIST_STYLE_POSITION_NOT_SET)
		style->list_style_position = apply->list_style_position;
	if (apply->list_style_type != CSS_LIST_STYLE_TYPE_INHERIT &&
			apply->list_style_type != CSS_LIST_STYLE_TYPE_NOT_SET)
		style->list_style_type = apply->list_style_type;
	if (apply->max_height.max_height != CSS_MAX_HEIGHT_INHERIT &&
			apply->max_height.max_height != CSS_MAX_HEIGHT_NOT_SET)
		style->max_height = apply->max_height;
	if (apply->max_width.max_width != CSS_MAX_WIDTH_INHERIT &&
			apply->max_width.max_width != CSS_MAX_WIDTH_NOT_SET)
		style->max_width = apply->max_width;
	if (apply->min_height.min_height != CSS_MIN_HEIGHT_INHERIT &&
			apply->min_height.min_height != CSS_MIN_HEIGHT_NOT_SET)
		style->min_height = apply->min_height;
	if (apply->min_width.min_width != CSS_MIN_WIDTH_INHERIT &&
			apply->min_width.min_width != CSS_MIN_WIDTH_NOT_SET)
		style->min_width = apply->min_width;
	if (apply->orphans.orphans != CSS_ORPHANS_INHERIT &&
			apply->orphans.orphans != CSS_ORPHANS_NOT_SET)
		style->orphans = apply->orphans;
	if (apply->overflow != CSS_OVERFLOW_INHERIT &&
			apply->overflow != CSS_OVERFLOW_NOT_SET)
		style->overflow = apply->overflow;
	if (apply->page_break_after != CSS_PAGE_BREAK_AFTER_INHERIT &&
			apply->page_break_after !=
				CSS_PAGE_BREAK_AFTER_NOT_SET)
		style->page_break_after = apply->page_break_after;
	if (apply->page_break_before != CSS_PAGE_BREAK_BEFORE_INHERIT &&
			apply->page_break_before !=
				CSS_PAGE_BREAK_BEFORE_NOT_SET)
		style->page_break_before = apply->page_break_before;
	if (apply->page_break_inside != CSS_PAGE_BREAK_INSIDE_INHERIT &&
			apply->page_break_inside !=
				CSS_PAGE_BREAK_INSIDE_NOT_SET)
		style->page_break_inside = apply->page_break_inside;
	if (apply->position != CSS_POSITION_INHERIT &&
			apply->position != CSS_POSITION_NOT_SET)
		style->position = apply->position;
	if (apply->table_layout != CSS_TABLE_LAYOUT_INHERIT &&
			apply->table_layout != CSS_TABLE_LAYOUT_NOT_SET)
		style->table_layout = apply->table_layout;
	if (apply->text_align != CSS_TEXT_ALIGN_INHERIT &&
			apply->text_align != CSS_TEXT_ALIGN_NOT_SET)
		style->text_align = apply->text_align;
	/* text-decoration: approximate CSS 2.1 by inheriting into inline elements */
	if (apply->text_decoration != CSS_TEXT_DECORATION_INHERIT &&
			apply->text_decoration != CSS_TEXT_DECORATION_NOT_SET)
		style->text_decoration = apply->text_decoration;
	if (apply->text_indent.size != CSS_TEXT_INDENT_INHERIT &&
			apply->text_indent.size != CSS_TEXT_INDENT_NOT_SET)
		style->text_indent = apply->text_indent;
	if (apply->text_transform != CSS_TEXT_TRANSFORM_INHERIT &&
			apply->text_transform != CSS_TEXT_TRANSFORM_NOT_SET)
		style->text_transform = apply->text_transform;
	if (apply->unicode_bidi != CSS_UNICODE_BIDI_INHERIT &&
			apply->unicode_bidi != CSS_UNICODE_BIDI_NOT_SET)
		style->unicode_bidi = apply->unicode_bidi;
	if (apply->vertical_align.type != CSS_VERTICAL_ALIGN_INHERIT &&
			apply->vertical_align.type !=
				CSS_VERTICAL_ALIGN_NOT_SET)
		style->vertical_align = apply->vertical_align;
	if (apply->visibility != CSS_VISIBILITY_INHERIT &&
			apply->visibility != CSS_VISIBILITY_NOT_SET)
		style->visibility = apply->visibility;
	if (apply->white_space != CSS_WHITE_SPACE_INHERIT &&
			apply->white_space != CSS_WHITE_SPACE_NOT_SET)
		style->white_space = apply->white_space;
	if (apply->widows.widows != CSS_WIDOWS_INHERIT &&
			apply->widows.widows != CSS_WIDOWS_NOT_SET)
		style->widows = apply->widows;
	if (apply->width.width != CSS_WIDTH_INHERIT &&
			apply->width.width != CSS_WIDTH_NOT_SET)
		style->width = apply->width;
	if (apply->word_spacing.word_spacing != CSS_WORD_SPACING_INHERIT &&
			apply->word_spacing.word_spacing !=
				CSS_WORD_SPACING_NOT_SET)
		style->word_spacing = apply->word_spacing;
	if (apply->z_index.z_index != CSS_Z_INDEX_INHERIT &&
			apply->z_index.z_index != CSS_Z_INDEX_NOT_SET)
		style->z_index = apply->z_index;


	/* clip */
	if (apply->clip.clip != CSS_CLIP_INHERIT &&
			apply->clip.clip != CSS_CLIP_NOT_SET) {
		for (i = 0; i != 4; i++) {
			style->clip.rect[i] = apply->clip.rect[i];
		}
	}


        /* background-position */
	if (apply->background_position.horz.pos !=
			CSS_BACKGROUND_POSITION_INHERIT &&
				apply->background_position.horz.pos !=
					CSS_BACKGROUND_POSITION_NOT_SET) {
		style->background_position.horz =
				apply->background_position.horz;
	}
	if (apply->background_position.vert.pos !=
			CSS_BACKGROUND_POSITION_INHERIT &&
				apply->background_position.vert.pos !=
					CSS_BACKGROUND_POSITION_NOT_SET) {
		style->background_position.vert =
				apply->background_position.vert;
	}

	/* font-size */
	f = apply->font_size.value.percent / 100;
	switch (apply->font_size.size) {
		case CSS_FONT_SIZE_ABSOLUTE:
			style->font_size = apply->font_size;
			break;
		case CSS_FONT_SIZE_LENGTH:
			switch (apply->font_size.value.length.unit) {
				case CSS_UNIT_EM:
					f = apply->font_size.value.length.value;
					break;
				case CSS_UNIT_EX:
					f = apply->font_size.value.length.value * 0.6 /*?*/;
					break;
				default:
					style->font_size = apply->font_size;
			}
			if ((apply->font_size.value.length.unit != CSS_UNIT_EM) &&
			    (apply->font_size.value.length.unit != CSS_UNIT_EX))
				break;
			/* drop through if EM or EX */
		case CSS_FONT_SIZE_PERCENT:
			switch (style->font_size.size) {
				case CSS_FONT_SIZE_ABSOLUTE:
					style->font_size.value.absolute *= f;
					break;
				case CSS_FONT_SIZE_LENGTH:
					style->font_size.value.length.value *= f;
					break;
				default:
					die("attempting percentage of unknown font-size");
			}
			break;
		case CSS_FONT_SIZE_INHERIT:
		case CSS_FONT_SIZE_NOT_SET:
		default:                     /* leave unchanged */
			break;
	}

	/* outline */
	if (apply->outline.color.color != CSS_OUTLINE_COLOR_INHERIT &&
			apply->outline.color.color !=
				CSS_OUTLINE_COLOR_NOT_SET)
		style->outline.color = apply->outline.color;
	if (apply->outline.width.width != CSS_BORDER_WIDTH_INHERIT &&
			apply->outline.width.width != CSS_BORDER_WIDTH_NOT_SET)
		style->outline.width = apply->outline.width;
	if (apply->outline.style != CSS_BORDER_STYLE_INHERIT &&
			apply->outline.style != CSS_BORDER_STYLE_NOT_SET)
		style->outline.style = apply->outline.style;

	/* borders, margins, padding and box position */
	for (i = 0; i != 4; i++) {
		if (apply->border[i].color != CSS_COLOR_INHERIT &&
				apply->border[i].color != CSS_COLOR_NOT_SET)
			style->border[i].color = apply->border[i].color;
		if (apply->border[i].width.width !=
				CSS_BORDER_WIDTH_INHERIT &&
					apply->border[i].width.width !=
						CSS_BORDER_WIDTH_NOT_SET)
			style->border[i].width = apply->border[i].width;
		if (apply->border[i].style != CSS_BORDER_STYLE_INHERIT &&
				apply->border[i].style !=
					CSS_BORDER_STYLE_NOT_SET)
			style->border[i].style = apply->border[i].style;

		if (apply->margin[i].margin != CSS_MARGIN_INHERIT &&
				apply->margin[i].margin != CSS_MARGIN_NOT_SET)
			style->margin[i] = apply->margin[i];

		if (apply->padding[i].padding != CSS_PADDING_INHERIT &&
				apply->padding[i].padding !=
					CSS_PADDING_NOT_SET)
			style->padding[i] = apply->padding[i];

		if (apply->pos[i].pos != CSS_POS_INHERIT &&
				apply->pos[i].pos != CSS_POS_NOT_SET)
			style->pos[i] = apply->pos[i];
	}

	/* Set author level CSS importance (used for HTML style attribute) */
	if (author) {
		if (apply->background_color != CSS_COLOR_NOT_SET)
			author->background_color = true;
		if (apply->background_image.type !=
					CSS_BACKGROUND_IMAGE_NOT_SET)
			author->background_image = true;
		if (apply->border_spacing.border_spacing !=
					CSS_BORDER_SPACING_NOT_SET)
			author->border_spacing = true;
		if (apply->color != CSS_COLOR_NOT_SET)
			author->color = true;
		if (apply->height.height != CSS_HEIGHT_NOT_SET)
			author->height = true;
		if (apply->width.width != CSS_WIDTH_NOT_SET)
			author->width = true;

		for (i = 0; i != 4; i++) {
			if (apply->border[i].color != CSS_COLOR_NOT_SET)
				author->border_color[i] = true;
			if (apply->border[i].width.width !=
						CSS_BORDER_WIDTH_NOT_SET)
				author->border_width[i] = true;
			if (apply->border[i].style != CSS_BORDER_STYLE_NOT_SET)
				author->border_style[i] = true;

			if (apply->margin[i].margin != CSS_MARGIN_NOT_SET)
				author->margin[i] = true;

			if (apply->padding[i].padding != CSS_PADDING_NOT_SET)
				author->padding[i] = true;
		}
	}
}


/**
 * Merge styles.
 *
 * \param  style        css_style to modify
 * \param  apply        css_style to merge onto style
 * \param  specificity  specificity of current CSS rule
 * \param  author       updated to indicate which properties have greater than
 *                      author level CSS importance
 *
 * Attributes which have the value 'unset' in apply are unchanged in style.
 * Other attributes are copied to style, overwriting it.
 */

void css_merge(struct css_style * const style,
		const struct css_style * const apply,
		const unsigned long specificity,
		struct css_importance * const author)
{
	unsigned int i;

	if (apply->background_attachment != CSS_BACKGROUND_ATTACHMENT_NOT_SET)
		style->background_attachment = apply->background_attachment;
	if (apply->background_color != CSS_COLOR_NOT_SET) {
		style->background_color = apply->background_color;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->background_color = true;
	}
	if (apply->background_image.type != CSS_BACKGROUND_IMAGE_NOT_SET) {
		style->background_image = apply->background_image;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->background_image = true;
	}
	if (apply->background_repeat != CSS_BACKGROUND_REPEAT_NOT_SET)
		style->background_repeat = apply->background_repeat;
	if (apply->border_collapse != CSS_BORDER_COLLAPSE_NOT_SET)
		style->border_collapse = apply->border_collapse;
	if (apply->border_spacing.border_spacing != CSS_BORDER_SPACING_NOT_SET){
		style->border_spacing = apply->border_spacing;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->border_spacing = true;
	}
	if (apply->caption_side != CSS_CAPTION_SIDE_NOT_SET)
		style->caption_side = apply->caption_side;
	if (apply->clear != CSS_CLEAR_NOT_SET)
		style->clear = apply->clear;
	if (apply->color != CSS_COLOR_NOT_SET) {
		style->color = apply->color;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->color = true;
	}
	if (apply->content.type != CSS_CONTENT_NOT_SET)
		style->content = apply->content;
	if (apply->counter_reset.type != CSS_COUNTER_RESET_NOT_SET)
		style->counter_reset = apply->counter_reset;
	if (apply->counter_increment.type != CSS_COUNTER_INCREMENT_NOT_SET)
		style->counter_increment = apply->counter_increment;
	if (apply->cursor != CSS_CURSOR_NOT_SET)
		style->cursor = apply->cursor;
	if (apply->direction != CSS_DIRECTION_NOT_SET)
		style->direction = apply->direction;
	if (apply->display != CSS_DISPLAY_NOT_SET)
		style->display = apply->display;
	if (apply->empty_cells != CSS_EMPTY_CELLS_NOT_SET)
		style->empty_cells = apply->empty_cells;
	if (apply->float_ != CSS_FLOAT_NOT_SET)
		style->float_ = apply->float_;
	if (apply->font_family != CSS_FONT_FAMILY_NOT_SET)
		style->font_family = apply->font_family;
	if (apply->font_size.size != CSS_FONT_SIZE_NOT_SET)
		style->font_size = apply->font_size;
	if (apply->font_style != CSS_FONT_STYLE_NOT_SET)
		style->font_style = apply->font_style;
	if (apply->font_variant != CSS_FONT_VARIANT_NOT_SET)
		style->font_variant = apply->font_variant;
	if (apply->font_weight != CSS_FONT_WEIGHT_NOT_SET)
		style->font_weight = apply->font_weight;
	if (apply->height.height != CSS_HEIGHT_NOT_SET) {
		style->height = apply->height;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->height = true;
	}
	if (apply->letter_spacing.letter_spacing != CSS_LETTER_SPACING_NOT_SET)
		style->letter_spacing = apply->letter_spacing;
	if (apply->line_height.size != CSS_LINE_HEIGHT_NOT_SET)
		style->line_height = apply->line_height;
	if (apply->list_style_image.type != CSS_LIST_STYLE_IMAGE_NOT_SET)
		style->list_style_image = apply->list_style_image;
	if (apply->list_style_position != CSS_LIST_STYLE_POSITION_NOT_SET)
		style->list_style_position = apply->list_style_position;
	if (apply->list_style_type != CSS_LIST_STYLE_TYPE_NOT_SET)
		style->list_style_type = apply->list_style_type;
	if (apply->max_height.max_height != CSS_MAX_HEIGHT_NOT_SET)
		style->max_height = apply->max_height;
	if (apply->max_width.max_width != CSS_MAX_WIDTH_NOT_SET)
		style->max_width = apply->max_width;
	if (apply->min_height.min_height != CSS_MIN_HEIGHT_NOT_SET)
		style->min_height = apply->min_height;
	if (apply->min_width.min_width != CSS_MIN_WIDTH_NOT_SET)
		style->min_width = apply->min_width;
	if (apply->orphans.orphans != CSS_ORPHANS_NOT_SET)
		style->orphans = apply->orphans;
	if (apply->overflow != CSS_OVERFLOW_NOT_SET)
		style->overflow = apply->overflow;
	if (apply->page_break_after != CSS_PAGE_BREAK_AFTER_NOT_SET)
		style->page_break_after = apply->page_break_after;
	if (apply->page_break_before != CSS_PAGE_BREAK_BEFORE_NOT_SET)
		style->page_break_before = apply->page_break_before;
	if (apply->page_break_inside != CSS_PAGE_BREAK_INSIDE_NOT_SET)
		style->page_break_inside = apply->page_break_inside;
	if (apply->position != CSS_POSITION_NOT_SET)
		style->position = apply->position;
	if (apply->table_layout != CSS_TABLE_LAYOUT_NOT_SET)
		style->table_layout = apply->table_layout;
	if (apply->text_align != CSS_TEXT_ALIGN_NOT_SET)
		style->text_align = apply->text_align;
	/* text-decoration: approximate CSS 2.1 by inheriting into inline elements */
	if (apply->text_decoration != CSS_TEXT_DECORATION_NOT_SET)
		style->text_decoration = apply->text_decoration;
	if (apply->text_indent.size != CSS_TEXT_INDENT_NOT_SET)
		style->text_indent = apply->text_indent;
	if (apply->text_transform != CSS_TEXT_TRANSFORM_NOT_SET)
		style->text_transform = apply->text_transform;
	if (apply->unicode_bidi != CSS_UNICODE_BIDI_NOT_SET)
		style->unicode_bidi = apply->unicode_bidi;
	if (apply->vertical_align.type != CSS_VERTICAL_ALIGN_NOT_SET)
		style->vertical_align = apply->vertical_align;
	if (apply->visibility != CSS_VISIBILITY_NOT_SET)
		style->visibility = apply->visibility;
	if (apply->white_space != CSS_WHITE_SPACE_NOT_SET)
		style->white_space = apply->white_space;
	if (apply->widows.widows != CSS_WIDOWS_NOT_SET)
		style->widows = apply->widows;
	if (apply->width.width != CSS_WIDTH_NOT_SET) {
		style->width = apply->width;
		if (specificity >= CSS_SPECIFICITY_AUTHOR)
			author->width = true;
	}
	if (apply->word_spacing.word_spacing != CSS_WORD_SPACING_NOT_SET)
		style->word_spacing = apply->word_spacing;
	if (apply->z_index.z_index != CSS_Z_INDEX_NOT_SET)
		style->z_index = apply->z_index;


	/* clip */
	if (apply->clip.clip != CSS_CLIP_NOT_SET) {
		for (i = 0; i != 4; i++) {
			style->clip.rect[i] = apply->clip.rect[i];
		}
	}

	/* background-position */
	if (apply->background_position.horz.pos !=
			CSS_BACKGROUND_POSITION_NOT_SET) {
		style->background_position.horz =
				apply->background_position.horz;
	}
	if (apply->background_position.vert.pos !=
			CSS_BACKGROUND_POSITION_NOT_SET) {
		style->background_position.vert =
				apply->background_position.vert;
	}

	/* outline */
	if (apply->outline.color.color != CSS_OUTLINE_COLOR_NOT_SET)
		style->outline.color = apply->outline.color;
	if (apply->outline.width.width != CSS_BORDER_WIDTH_NOT_SET)
		style->outline.width = apply->outline.width;
	if (apply->outline.style != CSS_BORDER_STYLE_NOT_SET)
		style->outline.style = apply->outline.style;

	/* borders, margins, padding and box position */
	for (i = 0; i != 4; i++) {
		if (apply->border[i].color != CSS_COLOR_NOT_SET) {
			style->border[i].color = apply->border[i].color;
			if (specificity >= CSS_SPECIFICITY_AUTHOR)
				author->border_color[i] = true;
		}
		if (apply->border[i].width.width != CSS_BORDER_WIDTH_NOT_SET) {
			style->border[i].width = apply->border[i].width;
			if (specificity >= CSS_SPECIFICITY_AUTHOR)
				author->border_width[i] = true;
		}
		if (apply->border[i].style != CSS_BORDER_STYLE_NOT_SET) {
			style->border[i].style = apply->border[i].style;
			if (specificity >= CSS_SPECIFICITY_AUTHOR)
				author->border_style[i] = true;
		}

		if (apply->margin[i].margin != CSS_MARGIN_NOT_SET) {
			style->margin[i] = apply->margin[i];
			if (specificity >= CSS_SPECIFICITY_AUTHOR)
				author->margin[i] = true;
		}

		if (apply->padding[i].padding != CSS_PADDING_NOT_SET) {
			style->padding[i] = apply->padding[i];
			if (specificity >= CSS_SPECIFICITY_AUTHOR)
				author->padding[i] = true;
		}

		if (apply->pos[i].pos != CSS_POS_NOT_SET)
			style->pos[i] = apply->pos[i];
	}
}


/**
 * Calculate a hash for an element name.
 *
 * The hash is case-insensitive.
 */

unsigned int css_hash(const char *s, int length)
{
	int i;
	unsigned int z = 0;
	if (s == 0)
		return 0;
	for (i = 0; i != length; i++)
		z += s[i] & 0x1f;  /* lower 5 bits, case insensitive */
	return (z % (HASH_SIZE - 1)) + 1;
}


/**
 * Convert a struct css_length to pixels.
 *
 * \param  length  css_length to convert
 * \param  style   css_style applying to length. may be 0 if the length's
 *		   unit is em or ex
 * \return	   length in pixels
 *
 * If a length's unit is em or ex, the returned length is subject to the
 * configured option_font_min_size.
 */

float css_len2px(const struct css_length *length,
		const struct css_style *style)
{
	struct css_length font;
	font.unit = CSS_UNIT_PT;

	assert(!((length->unit == CSS_UNIT_EM || length->unit == CSS_UNIT_EX) &&
			style == 0));
	switch (length->unit) {
		case CSS_UNIT_EM:
			if ((font.value = css_len2pt(&style->
					font_size.value.length, style)) <
					option_font_min_size / 10) {
				/* min font size is greater than given length so
				 * use min font size for conversion to px */
				font.value = option_font_min_size / 10;
				return length->value * css_len2px(&font, style);
			} else
				/* use given length for conversion to px */
				return length->value * css_len2px(&style->
						font_size.value.length, 0);
		case CSS_UNIT_EX:
			if ((font.value = css_len2pt(&style->
					font_size.value.length, style)) <
					option_font_min_size / 10) {
				/* min font size is greater than given length so
				 * use min font size for conversion to px */
				font.value = option_font_min_size / 10;
				return length->value * css_len2px(&font,
						style) * 0.6;
			} else
				/* use given length for conversion to px */
				return length->value * css_len2px(&style->
						font_size.value.length, 0) *
						0.6;
		case CSS_UNIT_PX: return length->value;
		/* We assume the screen and any other output has the same dpi */
		case CSS_UNIT_IN: return length->value * css_screen_dpi;
		case CSS_UNIT_CM: return length->value * css_screen_dpi / 2.54;
		case CSS_UNIT_MM: return length->value * css_screen_dpi / 25.4;
		/* 1pt = 1in/72 */
		case CSS_UNIT_PT: return length->value * css_screen_dpi / 72;
		/* 1pc = 1pt * 12 */
		case CSS_UNIT_PC: return length->value * css_screen_dpi / 6;
		default: break;
	}
	return 0;
}

/**
 * Convert a struct css_length to points.
 *
 * \param  length  css_length to convert
 * \param  style   css_style applying to length. may be 0 if the length's
 *		   unit is em or ex
 * \return	   length in points
 */

float css_len2pt(const struct css_length *length,
		const struct css_style *style)
{
	assert(!((length->unit == CSS_UNIT_EM || length->unit == CSS_UNIT_EX) &&
			style == 0));
	switch (length->unit) {
		case CSS_UNIT_EM:
			return length->value *
				css_len2pt(&style->font_size.value.length, 0);
		case CSS_UNIT_EX:
			return length->value *
				css_len2pt(&style->font_size.value.length, 0) *
				0.6;
		/* We assume the screen and any other output has the same dpi */
		case CSS_UNIT_PX: return length->value * 72 / css_screen_dpi;
		/* 1pt = 1in/72 */
		case CSS_UNIT_IN: return length->value * 72;
		case CSS_UNIT_CM: return length->value * 28.452756;
		case CSS_UNIT_MM: return length->value * 2.8452756;
		case CSS_UNIT_PT: return length->value;
		/* 1pc = 1pt * 12 */
		case CSS_UNIT_PC: return length->value * 12.0;
		default: break;
	}
	return 0;
}

/**
 * Return the most 'eyecatching' border.
 *
 * \return the most eyecatching border, favoured towards test2
 */

struct css_border *css_eyecatching_border(struct css_border *test1,
		struct css_style *style1, struct css_border *test2,
		struct css_style *style2)
{
	float width1, width2;
	int impact = 0;

	assert(test1);
	assert(style1);
	assert(test2);
	assert(style2);

	/* hidden border styles always win, none always loses */
	if ((test1->style == CSS_BORDER_STYLE_HIDDEN) ||
			(test2->style == CSS_BORDER_STYLE_NONE))
		return test1;
	if ((test2->style == CSS_BORDER_STYLE_HIDDEN) ||
			(test1->style == CSS_BORDER_STYLE_NONE))
		return test2;

	/* the widest border wins */
	width1 = css_len2px(&test1->width.value, style1);
	width2 = css_len2px(&test2->width.value, style2);
	if (width1 > width2)
		return test1;
	if (width2 > width1)
		return test2;

	/* the closest to a solid line wins */
	switch (test1->style) {
		case CSS_BORDER_STYLE_DOUBLE:
			impact++;
		case CSS_BORDER_STYLE_SOLID:
			impact++;
		case CSS_BORDER_STYLE_DASHED:
			impact++;
		case CSS_BORDER_STYLE_DOTTED:
			impact++;
		case CSS_BORDER_STYLE_RIDGE:
			impact++;
		case CSS_BORDER_STYLE_OUTSET:
			impact++;
		case CSS_BORDER_STYLE_GROOVE:
			impact++;
		case CSS_BORDER_STYLE_INSET:
			impact++;
		default:
			break;
	}
	switch (test2->style) {
		case CSS_BORDER_STYLE_DOUBLE:
			impact--;
		case CSS_BORDER_STYLE_SOLID:
			impact--;
		case CSS_BORDER_STYLE_DASHED:
			impact--;
		case CSS_BORDER_STYLE_DOTTED:
			impact--;
		case CSS_BORDER_STYLE_RIDGE:
			impact--;
		case CSS_BORDER_STYLE_OUTSET:
			impact--;
		case CSS_BORDER_STYLE_GROOVE:
			impact--;
		case CSS_BORDER_STYLE_INSET:
			impact--;
		default:
			break;
	}
	if (impact > 0)
		return test1;
	return test2;
}