summaryrefslogtreecommitdiff
path: root/desktop/treeview.c
blob: 3bbc83928d86c161de019d67d36aec4ce903454c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
/*
 * Copyright 2012 - 2013 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
 *
 * Treeview handling implementation.
 */

#include <string.h>

#include "utils/utils.h"
#include "utils/log.h"
#include "utils/nsurl.h"
#include "utils/nsoption.h"
#include "utils/config.h"
#include "netsurf/bitmap.h"
#include "netsurf/content.h"
#include "netsurf/plotters.h"
#include "netsurf/clipboard.h"
#include "netsurf/layout.h"
#include "netsurf/keypress.h"
#include "netsurf/core_window.h"
#include "content/hlcache.h"
#include "css/utils.h"

#include "desktop/system_colour.h"
#include "desktop/knockout.h"
#include "desktop/textarea.h"
#include "desktop/treeview.h"
#include "desktop/gui_internal.h"

/**
 * The maximum horizontal size a treeview can possibly be.
 *
 * \todo get rid of REDRAW_MAX -- need to be able to know window size
 */
#define REDRAW_MAX 8000


/**
 * Treeview handling global context
 */
struct treeview_globals {
	unsigned initialised;
	int line_height;
	int furniture_width;
	int step_width;
	int window_padding;
	int icon_size;
	int icon_step;
	int move_offset;
} tree_g;


/**
 * Section type of a treeview at a point
 */
enum treeview_node_part {
	TV_NODE_PART_TOGGLE,	/**< Expansion toggle */
	TV_NODE_PART_ON_NODE,	/**< Node content (text, icon) */
	TV_NODE_PART_NONE	/**< Empty area */
};


/**
 * Text within a treeview field or node
 */
struct treeview_text {
	const char *data;	/**< Text string */
	uint32_t len;		/**< Length of string in bytes */
	int width;		/**< Width of text in px */
};


/**
 * a treeview field
 */
struct treeview_field {
	/** flags controlling how field is interpreted */
	enum treeview_field_flags flags;

	lwc_string *field; /**< field contents */
	struct treeview_text value; /**< field text */
};


/**
 * flags indicating render state of node.
 */
enum treeview_node_flags {
	TV_NFLAGS_NONE     = 0,		/**< No node flags set */
	TV_NFLAGS_EXPANDED = (1 << 0),	/**< Whether node is expanded */
	TV_NFLAGS_SELECTED = (1 << 1),	/**< Whether node is selected */
	TV_NFLAGS_SPECIAL  = (1 << 2),	/**< Render as special node */
	TV_NFLAGS_MATCHED  = (1 << 3),	/**< Whether node matches search */
};


/**
 * Treeview target position
 */
enum treeview_target_pos {
	TV_TARGET_ABOVE,
	TV_TARGET_INSIDE,
	TV_TARGET_BELOW,
	TV_TARGET_NONE
};


/**
 * Treeview node
 */
struct treeview_node {
	enum treeview_node_flags flags;	/**< Node flags */
	enum treeview_node_type type;	/**< Node type */

	int height;	/**< Includes height of any descendants (pixels) */
	int inset;	/**< Node's inset depending on tree depth (pixels) */

	treeview_node *parent; /**< parent node */
	treeview_node *prev_sib; /**< previous sibling node */
	treeview_node *next_sib; /**< next sibling node */
	treeview_node *children; /**< first child node */

	void *client_data;  /**< Passed to client on node event msg callback */

	struct treeview_text text; /** Text to show for node (default field) */
};


/**
 * Node entry
 *
 * node entry contains a base node at the beginning allowing for
 * trivial containerof by cast and some number of fields.
 */
struct treeview_node_entry {
	treeview_node base; /**< Entry class inherits node base class */
	struct treeview_field fields[FLEX_ARRAY_LEN_DECL];
};


/**
 * A mouse position wrt treeview
 */
struct treeview_pos {
	int x;		/**< Mouse X coordinate */
	int y;		/**< Mouse Y coordinate */
	int node_y;	/**< Top of node at y */
	int node_h;	/**< Height of node at y */
};


/**
 * Treeview drag state
 */
struct treeview_drag {
	enum {
		TV_DRAG_NONE,
		TV_DRAG_SELECTION,
		TV_DRAG_MOVE,
		TV_DRAG_TEXTAREA,
		TV_DRAG_SEARCH,
	} type;	/**< Drag type */
	treeview_node *start_node;	/**< Start node */
	bool selected;			/**< Start node is selected */
	enum treeview_node_part part;	/**< Node part at start */
	struct treeview_pos start;	/**< Start pos */
	struct treeview_pos prev;	/**< Previous pos */
};


/**
 * Treeview node move details
 */
struct treeview_move {
	treeview_node *root;		/**< Head of yanked node list */
	treeview_node *target;		/**< Move target */
	struct rect target_area;	/**< Pos/size of target indicator */
	enum treeview_target_pos target_pos;	/**< Pos wrt render node */
};


/**
 * Treeview node edit details
 */
struct treeview_edit {
	treeview_node *node;		/**< Node being edited, or NULL */
	struct textarea *textarea;	/**< Textarea for edit, or NULL */
	lwc_string *field;		/**< The field being edited, or NULL */
	int x;		/**< Textarea x position */
	int y;		/**< Textarea y position */
	int w;		/**< Textarea width */
	int h;		/**< Textarea height */
};


/**
 * Treeview search box details
 */
struct treeview_search {
	struct textarea *textarea;  /**< Search box. */
	bool active;                /**< Whether the search box has focus. */
	bool search;                /**< Whether we have a search term. */
};


/**
 * The treeview context
 */
struct treeview {
	uint32_t view_width; /**< Viewport horizontal size */

	treeview_flags flags; /**< Treeview behaviour settings */

	treeview_node *root; /**< Root node */

	struct treeview_field *fields;	/**< Array of fields */
	int n_fields; /**< fields[n_fields] is folder, lower are entry fields */
	int field_width; /**< Max width of shown field names */

	struct treeview_drag drag; /**< Drag state */
	struct treeview_move move; /**< Move drag details */
	struct treeview_edit edit; /**< Edit details */

	struct treeview_search search; /**< Treeview search box */

	const struct treeview_callback_table *callbacks; /**< For node events */

	const struct core_window_callback_table *cw_t; /**< Window cb table */
	struct core_window *cw_h; /**< Core window handle */
};


/**
 * Treeview furniture states.
 */
enum treeview_furniture_id {
	TREE_FURN_EXPAND = 0,
	TREE_FURN_CONTRACT,
	TREE_FURN_LAST
};


/**
 * style for a node
 */
struct treeview_node_style {
	plot_style_t bg;	  /**< Background */
	plot_font_style_t text;	  /**< Text */
	plot_font_style_t itext;  /**< Entry field text */

	plot_style_t sbg;	  /**< Selected background */
	plot_font_style_t stext;  /**< Selected text */
	plot_font_style_t sitext; /**< Selected entry field text */

	struct {
		int size;
		struct bitmap *bmp;
		struct bitmap *sel;
	} furn[TREE_FURN_LAST];
};


/**
 * Plot style for odd rows
 */
struct treeview_node_style plot_style_odd;


/**
 * Plot style for even rows
 */
struct treeview_node_style plot_style_even;


/**
 * Treeview content resource data
 */
struct treeview_resource {
	const char *url;
	struct hlcache_handle *c;
	int height;
	bool ready;
};


/**
 * treeview resource indexes
 */
enum treeview_resource_id {
	TREE_RES_ARROW = 0,
	TREE_RES_CONTENT,
	TREE_RES_FOLDER,
	TREE_RES_FOLDER_SPECIAL,
	TREE_RES_SEARCH,
	TREE_RES_LAST
};


/**
 * Treeview content resources
 */
static struct treeview_resource treeview_res[TREE_RES_LAST] = {
	{ "resource:icons/arrow-l.png", NULL, 0, false },
	{ "resource:icons/content.png", NULL, 0, false },
	{ "resource:icons/directory.png", NULL, 0, false },
	{ "resource:icons/directory2.png", NULL, 0, false },
	{ "resource:icons/search.png", NULL, 0, false }
};


/**
 * Corewindow callback wrapper: Request a redraw of the window
 *
 * \param[in] tree The treeview to request redraw on.
 * \param[in] r rectangle to redraw
 */
static inline
void cw_invalidate_area(const struct treeview *tree,
			const struct rect *r)
{
	if (tree->cw_t != NULL) {
		tree->cw_t->invalidate(tree->cw_h, r);
	}
}


/**
 * Corewindow callback wrapper: Update the limits of the window
 *
 * \param[in] tree The treeview to update size for.
 * \param[in] width the width in px, or negative if don't care
 * \param[in] height the height in px, or negative if don't care
 */
static inline void treeview__cw_update_size(
	const struct treeview *tree,
	int width, int height)
{
	int search_height = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	if (tree->cw_t != NULL) {
		tree->cw_t->update_size(tree->cw_h, width,
				height + search_height);
	}
}


/**
 * Corewindow callback_wrapper: Scroll to top of window.
 *
 * \param[in] tree  The treeview to scroll.
 */
static inline void treeview__cw_scroll_top(
		const struct treeview *tree)
{
	struct rect r = {
		.x0 = 0,
		.y0 = 0,
		.x1 = tree_g.window_padding,
		.y1 = tree_g.line_height,
	};

	if (tree->cw_t != NULL) {
		tree->cw_t->scroll_visible(tree->cw_h, &r);
	}
}


/**
 * Corewindow callback wrapper: Get window viewport dimensions
 *
 * \param[in] tree The treeview to get dimensions for.
 * \param[out] width to be set to viewport width in px
 * \param[out] height to be set to viewport height in px
 */
static inline void treeview__cw_get_window_dimensions(
	const struct treeview *tree,
	int *width, int *height)
{
	if (tree->cw_t != NULL) {
		tree->cw_t->get_window_dimensions(tree->cw_h, width, height);
	}
}


/**
 * Corewindow callback wrapper: Inform corewindow owner of drag status
 *
 * \param[in] tree The treeview to report status on.
 * \param[in] ds the current drag status
 */
static inline void treeview__cw_drag_status(
	const struct treeview *tree,
	core_window_drag_status ds)
{
	if (tree->cw_t != NULL) {
		tree->cw_t->drag_status(tree->cw_h, ds);
	}
}


/**
 * Helper function to access the given field of a node
 *
 * \param tree Treeview that node belongs to
 * \param n Node to get field from
 * \param i Index of field of interest
 * \return text entry for field or NULL.
 */
static inline struct treeview_text *
treeview_get_text_for_field(treeview *tree, treeview_node *n, int i)
{
	if (i == 0) {
		return &n->text;

	} else if (i < tree->n_fields && n->type == TREE_NODE_ENTRY) {
		struct treeview_node_entry *e = (struct treeview_node_entry *)n;
		return &e->fields[i - 1].value;
	}

	assert(0 && "Bad field index for node");
	return NULL;
}


/**
 * Find the next node in depth first tree order
 *
 * \param node Start node
 * \param full Iff true, visit children of collapsed nodes
 * \return next node, or NULL if \a node is last node
 */
static inline treeview_node * treeview_node_next(treeview_node *node, bool full)
{
	assert(node != NULL);

	if ((full || (node->flags & TV_NFLAGS_EXPANDED)) &&
	    node->children != NULL) {
		/* Next node is child */
		node = node->children;
	} else {
		/* No children.  As long as we're not at the root,
		 * go to next sibling if present, or nearest ancestor
		 * with a next sibling. */

		while (node->parent != NULL && node->next_sib == NULL) {
			node = node->parent;
		}

		if (node->type == TREE_NODE_ROOT) {
			node = NULL;

		} else {
			node = node->next_sib;
		}
	}

	return node;
}


/**
 * Find node at given y-position
 *
 * \param tree Treeview object to delete node from
 * \param target_y Target y-position
 * \return node at y_target
 */
static treeview_node * treeview_y_node(treeview *tree, int target_y)
{
	treeview_node *n;
	int y = 0;
	int h;

	assert(tree != NULL);
	assert(tree->root != NULL);

	n = treeview_node_next(tree->root, false);

	while (n != NULL) {
		h = (n->type == TREE_NODE_ENTRY) ?
			n->height : tree_g.line_height;
		if (target_y >= y && target_y < y + h)
			return n;
		y += h;

		n = treeview_node_next(n, false);
	}

	return NULL;
}


/**
 * Find y position of the top of a node
 *
 * \param tree Treeview object to delete node from
 * \param node Node to get position of
 * \return node's y position
 */
static int treeview_node_y(treeview *tree, treeview_node *node)
{
	treeview_node *n;
	int y = 0;

	assert(tree != NULL);
	assert(tree->root != NULL);

	n = treeview_node_next(tree->root, false);

	while (n != NULL && n != node) {
		y += (n->type == TREE_NODE_ENTRY) ?
			n->height : tree_g.line_height;

		n = treeview_node_next(n, false);
	}

	return y;
}


/**
 * Walk a treeview subtree, calling a callback at each node (depth first)
 *
 * \param root		Root to walk tree from (doesn't get a callback call)
 * \param full		Iff true, visit children of collapsed nodes
 * \param callback_bwd	Function to call on each node in backwards order
 * \param callback_fwd	Function to call on each node in forwards order
 * \param ctx		Context to pass to callback
 * \return NSERROR_OK on success, or appropriate error otherwise
 *
 * \note Any node deletion must happen in callback_bwd.
 */
static nserror
treeview_walk_internal(treeview_node *root,
		       bool full,
		       nserror (*callback_bwd)(treeview_node *n, void *ctx, bool *end),
		       nserror (*callback_fwd)(treeview_node *n, void *ctx, bool *skip_children, bool *end),
		       void *ctx)
{
	treeview_node *node, *child, *parent, *next_sibling;
	bool abort = false;
	bool skip_children = false;
	nserror err;

	assert(root != NULL);

	node = root;
	parent = node->parent;
	next_sibling = node->next_sib;
	child = (!skip_children &&
		 (full || (node->flags & TV_NFLAGS_EXPANDED))) ?
		node->children : NULL;

	while (node != NULL) {

		if (child != NULL) {
			/* Down to children */
			node = child;
		} else {
			/* No children.  As long as we're not at the root,
			 * go to next sibling if present, or nearest ancestor
			 * with a next sibling. */

			while (node != root &&
			       next_sibling == NULL) {
				if (callback_bwd != NULL) {
					/* Backwards callback */
					err = callback_bwd(node, ctx, &abort);

					if (err != NSERROR_OK) {
						return err;

					} else if (abort) {
						/* callback requested early
						 * termination */
						return NSERROR_OK;
					}
				}
				node = parent;
				parent = node->parent;
				next_sibling = node->next_sib;
			}

			if (node == root)
				break;

			if (callback_bwd != NULL) {
				/* Backwards callback */
				err = callback_bwd(node, ctx, &abort);

				if (err != NSERROR_OK) {
					return err;

				} else if (abort) {
					/* callback requested early
					 * termination */
					return NSERROR_OK;
				}
			}
			node = next_sibling;
		}

		assert(node != NULL);
		assert(node != root);

		parent = node->parent;
		next_sibling = node->next_sib;
		child = (full || (node->flags & TV_NFLAGS_EXPANDED)) ?
			node->children : NULL;

		if (callback_fwd != NULL) {
			/* Forwards callback */
			err = callback_fwd(node, ctx, &skip_children, &abort);

			if (err != NSERROR_OK) {
				return err;

			} else if (abort) {
				/* callback requested early termination */
				return NSERROR_OK;
			}
		}
		child = skip_children ? NULL : child;
	}
	return NSERROR_OK;
}


/**
 * Create treeview's root node
 *
 * \param[out] root Returns root node
 * \return NSERROR_OK on success, appropriate error otherwise
 */
static nserror treeview_create_node_root(treeview_node **root)
{
	treeview_node *n;

	n = malloc(sizeof(struct treeview_node));
	if (n == NULL) {
		return NSERROR_NOMEM;
	}

	n->flags = TV_NFLAGS_EXPANDED;
	n->type = TREE_NODE_ROOT;

	n->height = 0;
	n->inset = tree_g.window_padding - tree_g.step_width;

	n->text.data = NULL;
	n->text.len = 0;
	n->text.width = 0;

	n->parent = NULL;
	n->next_sib = NULL;
	n->prev_sib = NULL;
	n->children = NULL;

	n->client_data = NULL;

	*root = n;

	return NSERROR_OK;
}


/**
 * Set a node's inset from its parent
 *
 * This may be used as treeview walk callback
 *
 * \param[in] n node to set inset on
 * \param[in] ctx context unused
 * \param[out] skip_children set to false so child nodes are not skipped.
 * \param[out] end unused flag so treewalk in not terminated early.
 */
static nserror
treeview_set_inset_from_parent(treeview_node *n,
			       void *ctx,
			       bool *skip_children,
			       bool *end)
{
	if (n->parent != NULL)
		n->inset = n->parent->inset + tree_g.step_width;

	*skip_children = false;
	return NSERROR_OK;
}


/**
 * Insert a treeview node into a treeview
 *
 * \param a parentless node to insert
 * \param b tree node to insert a as a relation of
 * \param rel The relationship between \a a and \a b
 */
static inline void
treeview_insert_node(treeview_node *a,
		     treeview_node *b,
		     enum treeview_relationship rel)
{
	assert(a != NULL);
	assert(a->parent == NULL);
	assert(b != NULL);

	switch (rel) {
	case TREE_REL_FIRST_CHILD:
		assert(b->type != TREE_NODE_ENTRY);
		a->parent = b;
		a->next_sib = b->children;
		if (a->next_sib)
			a->next_sib->prev_sib = a;
		b->children = a;
		break;

	case TREE_REL_NEXT_SIBLING:
		assert(b->type != TREE_NODE_ROOT);
		a->prev_sib = b;
		a->next_sib = b->next_sib;
		a->parent = b->parent;
		b->next_sib = a;
		if (a->next_sib)
			a->next_sib->prev_sib = a;
		break;

	default:
		assert(0);
		break;
	}

	assert(a->parent != NULL);

	a->inset = a->parent->inset + tree_g.step_width;
	if (a->children != NULL) {
		treeview_walk_internal(a, true, NULL,
				       treeview_set_inset_from_parent, NULL);
	}

	if (a->parent->flags & TV_NFLAGS_EXPANDED) {
		int height = a->height;
		/* Parent is expanded, so inserted node will be visible and
		 * affect layout */
		if (a->text.width == 0) {
			guit->layout->width(&plot_style_odd.text,
					    a->text.data,
					    a->text.len,
					    &(a->text.width));
		}

		do {
			a->parent->height += height;
			a = a->parent;
		} while (a->parent != NULL);
	}
}


/* Exported interface, documented in treeview.h */
nserror
treeview_create_node_folder(treeview *tree,
			    treeview_node **folder,
			    treeview_node *relation,
			    enum treeview_relationship rel,
			    const struct treeview_field_data *field,
			    void *data,
			    treeview_node_options_flags flags)
{
	treeview_node *n;

	assert(data != NULL);
	assert(tree != NULL);
	assert(tree->root != NULL);

	if (relation == NULL) {
		relation = tree->root;
		rel = TREE_REL_FIRST_CHILD;
	}

	n = malloc(sizeof(struct treeview_node));
	if (n == NULL) {
		return NSERROR_NOMEM;
	}

	n->flags = (flags & TREE_OPTION_SPECIAL_DIR) ?
		TV_NFLAGS_SPECIAL : TV_NFLAGS_NONE;
	n->type = TREE_NODE_FOLDER;

	n->height = tree_g.line_height;

	n->text.data = field->value;
	n->text.len = field->value_len;
	n->text.width = 0;

	n->parent = NULL;
	n->next_sib = NULL;
	n->prev_sib = NULL;
	n->children = NULL;

	n->client_data = data;

	treeview_insert_node(n, relation, rel);

	if (n->parent->flags & TV_NFLAGS_EXPANDED) {
		/* Inform front end of change in dimensions */
		if (!(flags & TREE_OPTION_SUPPRESS_RESIZE))
			treeview__cw_update_size(tree, -1,
						 tree->root->height);

		/* Redraw */
		if (!(flags & TREE_OPTION_SUPPRESS_REDRAW)) {
			struct rect r;
			r.x0 = 0;
			r.y0 = treeview_node_y(tree, n);
			r.x1 = REDRAW_MAX;
			r.y1 = tree->root->height;
			cw_invalidate_area(tree, &r);
		}
	}

	*folder = n;

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_update_node_folder(treeview *tree,
			    treeview_node *folder,
			    const struct treeview_field_data *field,
			    void *data)
{
	bool match;

	assert(data != NULL);
	assert(tree != NULL);
	assert(folder != NULL);
	assert(data == folder->client_data);
	assert(folder->parent != NULL);

	assert(field != NULL);
	assert(lwc_string_isequal(tree->fields[tree->n_fields].field,
				  field->field, &match) == lwc_error_ok &&
	       match == true);
	folder->text.data = field->value;
	folder->text.len = field->value_len;
	folder->text.width = 0;

	if (folder->parent->flags & TV_NFLAGS_EXPANDED) {
		/* Text will be seen, get its width */
		guit->layout->width(&plot_style_odd.text,
				    folder->text.data,
				    folder->text.len,
				    &(folder->text.width));
	} else {
		/* Just invalidate the width, since it's not needed now */
		folder->text.width = 0;
	}

	/* Redraw */
	if (folder->parent->flags & TV_NFLAGS_EXPANDED) {
		struct rect r;
		r.x0 = 0;
		r.y0 = treeview_node_y(tree, folder);
		r.x1 = REDRAW_MAX;
		r.y1 = r.y0 + tree_g.line_height;
		cw_invalidate_area(tree, &r);
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_update_node_entry(treeview *tree,
			   treeview_node *entry,
			   const struct treeview_field_data fields[],
			   void *data)
{
	bool match;
	struct treeview_node_entry *e = (struct treeview_node_entry *)entry;
	int i;

	assert(data != NULL);
	assert(tree != NULL);
	assert(entry != NULL);
	assert(data == entry->client_data);
	assert(entry->parent != NULL);

	assert(fields != NULL);
	assert(fields[0].field != NULL);
	assert(lwc_string_isequal(tree->fields[0].field,
				  fields[0].field, &match) == lwc_error_ok &&
	       match == true);
	entry->text.data = fields[0].value;
	entry->text.len = fields[0].value_len;
	entry->text.width = 0;

	if (entry->parent->flags & TV_NFLAGS_EXPANDED) {
		/* Text will be seen, get its width */
		guit->layout->width(&plot_style_odd.text,
				    entry->text.data,
				    entry->text.len,
				    &(entry->text.width));
	} else {
		/* Just invalidate the width, since it's not needed now */
		entry->text.width = 0;
	}

	for (i = 1; i < tree->n_fields; i++) {
		assert(fields[i].field != NULL);
		assert(lwc_string_isequal(tree->fields[i].field,
					  fields[i].field, &match) == lwc_error_ok &&
		       match == true);

		e->fields[i - 1].value.data = fields[i].value;
		e->fields[i - 1].value.len = fields[i].value_len;

		if (entry->flags & TV_NFLAGS_EXPANDED) {
			/* Text will be seen, get its width */
			guit->layout->width(&plot_style_odd.text,
					    e->fields[i - 1].value.data,
					    e->fields[i - 1].value.len,
					    &(e->fields[i - 1].value.width));
		} else {
			/* Invalidate the width, since it's not needed yet */
			e->fields[i - 1].value.width = 0;
		}
	}

	/* Redraw */
	if (entry->parent->flags & TV_NFLAGS_EXPANDED) {
		struct rect r;
		r.x0 = 0;
		r.y0 = treeview_node_y(tree, entry);
		r.x1 = REDRAW_MAX;
		r.y1 = r.y0 + entry->height;
		cw_invalidate_area(tree, &r);
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_create_node_entry(treeview *tree,
			   treeview_node **entry,
			   treeview_node *relation,
			   enum treeview_relationship rel,
			   const struct treeview_field_data fields[],
			   void *data,
			   treeview_node_options_flags flags)
{
	bool match;
	struct treeview_node_entry *e;
	treeview_node *n;
	int i;

	assert(data != NULL);
	assert(tree != NULL);
	assert(tree->root != NULL);

	if (relation == NULL) {
		relation = tree->root;
		rel = TREE_REL_FIRST_CHILD;
	}

	e = malloc(sizeof(struct treeview_node_entry) +
			(tree->n_fields - 1) * sizeof(struct treeview_field));
	if (e == NULL) {
		return NSERROR_NOMEM;
	}


	n = (treeview_node *) e;

	n->flags = TV_NFLAGS_NONE;
	n->type = TREE_NODE_ENTRY;

	n->height = tree_g.line_height;

	assert(fields != NULL);
	assert(fields[0].field != NULL);
	assert(lwc_string_isequal(tree->fields[0].field,
			fields[0].field, &match) == lwc_error_ok &&
			match == true);
	n->text.data = fields[0].value;
	n->text.len = fields[0].value_len;
	n->text.width = 0;

	n->parent = NULL;
	n->next_sib = NULL;
	n->prev_sib = NULL;
	n->children = NULL;

	n->client_data = data;

	for (i = 1; i < tree->n_fields; i++) {
		assert(fields[i].field != NULL);
		assert(lwc_string_isequal(tree->fields[i].field,
				fields[i].field, &match) == lwc_error_ok &&
				match == true);

		e->fields[i - 1].value.data = fields[i].value;
		e->fields[i - 1].value.len = fields[i].value_len;
		e->fields[i - 1].value.width = 0;
	}

	treeview_insert_node(n, relation, rel);

	if (n->parent->flags & TV_NFLAGS_EXPANDED) {
		/* Inform front end of change in dimensions */
		if (!(flags & TREE_OPTION_SUPPRESS_RESIZE))
			treeview__cw_update_size(tree, -1,
						 tree->root->height);

		/* Redraw */
		if (!(flags & TREE_OPTION_SUPPRESS_REDRAW)) {
			struct rect r;
			r.x0 = 0;
			r.y0 = treeview_node_y(tree, n);
			r.x1 = REDRAW_MAX;
			r.y1 = tree->root->height;
			cw_invalidate_area(tree, &r);
		}
	}

	*entry = n;

	return NSERROR_OK;
}


/**
 * Treewalk iterator context
 */
struct treeview_walk_ctx {
	treeview_walk_cb enter_cb;
	treeview_walk_cb leave_cb;
	void *ctx;
	enum treeview_node_type type;
};


/**
 * Treewalk node enter callback.
 *
 * \param n current node
 * \param ctx treewalk context
 * \param skip_children set if child nodes should be skipped
 * \param end set if iteration should end early
 */
static nserror
treeview_walk_fwd_cb(treeview_node *n,
		     void *ctx,
		     bool *skip_children,
		     bool *end)
{
	struct treeview_walk_ctx *tw = ctx;

	if (n->type & tw->type) {
		return tw->enter_cb(tw->ctx, n->client_data, n->type, end);
	}

	return NSERROR_OK;
}


/**
 * Treewalk node leave callback.
 *
 * \param n current node
 * \param ctx treewalk context
 * \param end set if iteration should end early
 */
static nserror treeview_walk_bwd_cb(treeview_node *n, void *ctx, bool *end)
{
	struct treeview_walk_ctx *tw = ctx;

	if (n->type & tw->type) {
		return tw->leave_cb(tw->ctx, n->client_data, n->type, end);
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_walk(treeview *tree,
	      treeview_node *root,
	      treeview_walk_cb enter_cb,
	      treeview_walk_cb leave_cb,
	      void *ctx,
	      enum treeview_node_type type)
{
	struct treeview_walk_ctx tw = {
		.enter_cb = enter_cb,
		.leave_cb = leave_cb,
		.ctx = ctx,
		.type = type
	};

	assert(tree != NULL);
	assert(tree->root != NULL);

	if (root == NULL)
		root = tree->root;

	return treeview_walk_internal(root, true,
			(leave_cb != NULL) ? treeview_walk_bwd_cb : NULL,
			(enter_cb != NULL) ? treeview_walk_fwd_cb : NULL,
			&tw);
}


/**
 * Unlink a treeview node
 *
 * \param n Node to unlink
 * \return true iff ancestor heights need to be reduced
 */
static inline bool treeview_unlink_node(treeview_node *n)
{
	/* Unlink node from tree */
	if (n->parent != NULL && n->parent->children == n) {
		/* Node is a first child */
		n->parent->children = n->next_sib;

	} else if (n->prev_sib != NULL) {
		/* Node is not first child */
		n->prev_sib->next_sib = n->next_sib;
	}

	if (n->next_sib != NULL) {
		/* Always need to do this */
		n->next_sib->prev_sib = n->prev_sib;
	}

	/* Reduce ancestor heights */
	if ((n->parent != NULL) &&
	    (n->parent->flags & TV_NFLAGS_EXPANDED)) {
		return true;
	}

	return false;
}


/**
 * Cancel the editing of a treeview node
 *
 * \param tree Treeview object to cancel node editing in
 * \param redraw Set true iff redraw of removed textarea area required
 */
static void treeview_edit_cancel(treeview *tree, bool redraw)
{
	struct rect r;

	if (tree->edit.textarea == NULL)
		return;

	textarea_destroy(tree->edit.textarea);

	tree->edit.textarea = NULL;
	tree->edit.node = NULL;

	if (tree->drag.type == TV_DRAG_TEXTAREA)
		tree->drag.type = TV_DRAG_NONE;

	if (redraw) {
		r.x0 = tree->edit.x;
		r.y0 = tree->edit.y;
		r.x1 = tree->edit.x + tree->edit.w;
		r.y1 = tree->edit.y + tree->edit.h;
		cw_invalidate_area(tree, &r);
	}
}


/**
 * Complete a treeview edit
 *
 * Complete edit by informing the client with a change request msg
 *
 * \param tree Treeview object to complete edit in
 */
static void treeview_edit_done(treeview *tree)
{
	int len, error;
	char* new_text;
	treeview_node *n = tree->edit.node;
	struct treeview_node_msg msg;
	msg.msg = TREE_MSG_NODE_EDIT;

	if (tree->edit.textarea == NULL) {
		return;
	}

	assert(n != NULL);

	/* Get new text length */
	len = textarea_get_text(tree->edit.textarea, NULL, 0);

	new_text = malloc(len);
	if (new_text == NULL) {
		/* TODO: don't just silently ignore */
		return;
	}

	/* Get the new text from textarea */
	error = textarea_get_text(tree->edit.textarea, new_text, len);
	if (error == -1) {
		/* TODO: don't just silently ignore */
		free(new_text);
		return;
	}

	/* Inform the treeview client with change request message */
	msg.data.node_edit.field = tree->edit.field;
	msg.data.node_edit.text = new_text;

	switch (n->type) {
	case TREE_NODE_ENTRY:
		tree->callbacks->entry(msg, n->client_data);
		break;
	case TREE_NODE_FOLDER:
		tree->callbacks->folder(msg, n->client_data);
		break;
	case TREE_NODE_ROOT:
		break;
	default:
		break;
	}

	/* Finished with the new text */
	free(new_text);

	/* Finally, destroy the treeview, and redraw */
	treeview_edit_cancel(tree, true);
}


/**
 * context for treeview node deletion iterator
 */
struct treeview_node_delete {
	treeview *tree;
	int h_reduction;
	bool user_interaction;
};


/**
 * Treewalk node callback deleting nodes.
 */
static nserror
treeview_delete_node_walk_cb(treeview_node *n, void *ctx, bool *end)
{
	struct treeview_node_delete *nd = (struct treeview_node_delete *)ctx;
	struct treeview_node_msg msg;

	msg.msg = TREE_MSG_NODE_DELETE;
	msg.data.delete.user = nd->user_interaction;

	assert(n->children == NULL);

	if (treeview_unlink_node(n))
		nd->h_reduction += (n->type == TREE_NODE_ENTRY) ?
			n->height : tree_g.line_height;

	/* Handle any special treatment */
	switch (n->type) {
	case TREE_NODE_ENTRY:
		nd->tree->callbacks->entry(msg, n->client_data);
		break;

	case TREE_NODE_FOLDER:
		nd->tree->callbacks->folder(msg, n->client_data);
		break;

	case TREE_NODE_ROOT:
		break;

	default:
		return NSERROR_BAD_PARAMETER;
	}

	/* Cancel any edit of this node */
	if (nd->tree->edit.textarea != NULL &&
	    nd->tree->edit.node == n) {
		treeview_edit_cancel(nd->tree, false);
	}

	/* Free the node */
	free(n);

	return NSERROR_OK;
}


/**
 * Delete a treeview node
 *
 * Will emit folder or entry deletion msg callback.
 *
 * \note this can be called from inside a treeview_walk fwd callback.
 * For example walking the tree and calling this for any node that's selected.
 *
 * This function does not delete empty nodes, so if TREEVIEW_DEL_EMPTY_DIRS is
 * set, caller must also call treeview_delete_empty.
 *
 * \param tree		Treeview object to delete node from
 * \param n		Node to delete
 * \param interaction	Delete is result of user interaction with treeview
 * \param flags		Treeview node options flags
 * \return NSERROR_OK on success, appropriate error otherwise
 */
static nserror
treeview_delete_node_internal(treeview *tree,
			      treeview_node *n,
			      bool interaction,
			      treeview_node_options_flags flags)
{
	nserror err;
	treeview_node *p = n->parent;
	struct treeview_node_delete nd = {
		.tree = tree,
		.h_reduction = 0,
		.user_interaction = interaction
	};

	if (interaction && (tree->flags & TREEVIEW_NO_DELETES)) {
		return NSERROR_OK;
	}

	/* Delete any children first */
	err = treeview_walk_internal(n, true, treeview_delete_node_walk_cb,
				     NULL, &nd);
	if (err != NSERROR_OK) {
		return err;
	}

	/* Now delete node */
	if (n == tree->root)
		tree->root = NULL;
	err = treeview_delete_node_walk_cb(n, &nd, false);
	if (err != NSERROR_OK) {
		return err;
	}

	n = p;
	/* Reduce ancestor heights */
	while (n != NULL && n->flags & TV_NFLAGS_EXPANDED) {
		n->height -= nd.h_reduction;
		n = n->parent;
	}

	/* Inform front end of change in dimensions */
	if (tree->root != NULL && p != NULL && p->flags & TV_NFLAGS_EXPANDED &&
	    nd.h_reduction > 0 &&
	    !(flags & TREE_OPTION_SUPPRESS_RESIZE)) {
		treeview__cw_update_size(tree, -1,
					 tree->root->height);
	}

	return NSERROR_OK;
}


/**
 * Delete any empty treeview folder nodes
 *
 * \param tree Treeview object to delete empty nodes from
 * \param interaction Delete is result of user interaction with treeview
 * \return NSERROR_OK on success, appropriate error otherwise
 *
 * Note this must not be called within a treeview_walk.  It may delete the
 * walker's 'current' node, making it impossible to move on without invalid
 * reads.
 */
static nserror treeview_delete_empty_nodes(treeview *tree, bool interaction)
{
	treeview_node *node, *child, *parent, *next_sibling, *p;
	bool abort = false;
	nserror err;
	struct treeview_node_delete nd = {
		.tree = tree,
		.h_reduction = 0,
		.user_interaction = interaction
	};

	assert(tree != NULL);
	assert(tree->root != NULL);

	node = tree->root;
	parent = node->parent;
	next_sibling = node->next_sib;
	child = (node->flags & TV_NFLAGS_EXPANDED) ? node->children : NULL;

	while (node != NULL) {

		if (child != NULL) {
			/* Down to children */
			node = child;
		} else {
			/* No children.  As long as we're not at the root,
			 * go to next sibling if present, or nearest ancestor
			 * with a next sibling. */

			while (node->parent != NULL &&
			       next_sibling == NULL) {
				if (node->type == TREE_NODE_FOLDER &&
				    node->children == NULL) {
					/* Delete node */
					p = node->parent;
					err = treeview_delete_node_walk_cb(
						node, &nd, &abort);
					if (err != NSERROR_OK) {
						return err;
					}

					/* Reduce ancestor heights */
					while (p != NULL &&
					       p->flags &
					       TV_NFLAGS_EXPANDED) {
						p->height -= nd.h_reduction;
						p = p->parent;
					}
					nd.h_reduction = 0;
				}
				node = parent;
				parent = node->parent;
				next_sibling = node->next_sib;
			}

			if (node->parent == NULL)
				break;

			if (node->type == TREE_NODE_FOLDER &&
			    node->children == NULL) {
				/* Delete node */
				p = node->parent;
				err = treeview_delete_node_walk_cb(
					node, &nd, &abort);
				if (err != NSERROR_OK) {
					return err;
				}

				/* Reduce ancestor heights */
				while (p != NULL &&
				       p->flags & TV_NFLAGS_EXPANDED) {
					p->height -= nd.h_reduction;
					p = p->parent;
				}
				nd.h_reduction = 0;
			}
			node = next_sibling;
		}

		assert(node != NULL);
		assert(node->parent != NULL);

		parent = node->parent;
		next_sibling = node->next_sib;
		child = (node->flags & TV_NFLAGS_EXPANDED) ?
			node->children : NULL;
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_delete_node(treeview *tree,
		     treeview_node *n,
		     treeview_node_options_flags flags)
{
	nserror err;
	struct rect r;
	bool visible;

	assert(tree != NULL);
	assert(n != NULL);
	assert(n->parent != NULL);

	visible = n->parent->flags & TV_NFLAGS_EXPANDED;

	r.y0 = treeview_node_y(tree, n);
	r.y1 = tree->root->height;

	err = treeview_delete_node_internal(tree, n, false, flags);
	if (err != NSERROR_OK)
		return err;

	if (tree->flags & TREEVIEW_DEL_EMPTY_DIRS) {
		int h = tree->root->height;
		/* Delete any empty nodes */
		err = treeview_delete_empty_nodes(tree, false);
		if (err != NSERROR_OK)
			return err;

		/* Inform front end of change in dimensions */
		if (tree->root->height != h) {
			r.y0 = 0;
			if (!(flags & TREE_OPTION_SUPPRESS_RESIZE)) {
				treeview__cw_update_size(tree, -1,
							 tree->root->height);
			}
		}
	}

	/* Redraw */
	if (visible && !(flags & TREE_OPTION_SUPPRESS_REDRAW)) {
		r.x0 = 0;
		r.x1 = REDRAW_MAX;
		cw_invalidate_area(tree, &r);
	}

	return NSERROR_OK;
}


/**
 * Helper to create a textarea.
 *
 * \param[in] tree         The treeview we're creating the textarea for.
 * \param[in] width        The width of the textarea.
 * \param[in] height       The height of the textarea.
 * \param[in] border       The border colour to use.
 * \param[in] background   The background colour to use.
 * \param[in] foreground   The foreground colour to use.
 * \param[in] text         The text style to use for the text area.
 * \param[in] ta_callback  The textarea callback function to give the textarea.
 * \return the textarea pointer on success, or NULL on failure.
 */
static struct textarea *treeview__create_textarea(
		treeview *tree,
		int width,
		int height,
		colour border,
		colour background,
		colour foreground,
		plot_font_style_t text,
		textarea_client_callback ta_callback)
{
	/* Configure the textarea */
	textarea_flags ta_flags = TEXTAREA_INTERNAL_CARET;
	textarea_setup ta_setup = {
		.text = text,
		.width = width,
		.height = height,
		.pad_top = 0,
		.pad_left = 2,
		.pad_right = 2,
		.pad_bottom = 0,
		.border_width = 1,
		.border_col = border,
		.selected_bg = foreground,
		.selected_text = background,
	};

	ta_setup.text.foreground = foreground;
	ta_setup.text.background = background;

	/* Create text area */
	return textarea_create(ta_flags, &ta_setup, ta_callback, tree);
}


/**
 * Data used when doing a treeview walk for search.
 */
struct treeview_search_walk_data {
	treeview *tree;          /**< The treeview to search. */
	const char *text;        /**< The string being searched for. */
	const unsigned int len;  /**< Length of string being searched for. */
	int window_height;       /**< Accumulate height for matching entries. */
};


/**
 * Treewalk node callback for handling search.
 *
 * \param[in]     n              Current node.
 * \param[in]     ctx            Treeview search context.
 * \param[in,out] skip_children  Flag to allow children to be skipped.
 * \param[in,out] end            Flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror treeview__search_walk_cb(
		treeview_node *n,
		void *ctx,
		bool *skip_children,
		bool *end)
{
	struct treeview_search_walk_data *sw = ctx;

	if (n->type != TREE_NODE_ENTRY) {
		return NSERROR_OK;
	}

	if (sw->len == 0) {
		n->flags &= ~TV_NFLAGS_MATCHED;
	} else {
		struct treeview_node_entry *entry =
				(struct treeview_node_entry *)n;
		bool matched = false;

		for (int i = 0; i < sw->tree->n_fields; i++) {
			struct treeview_field *ef = &(sw->tree->fields[i + 1]);
			if (ef->flags & TREE_FLAG_SEARCHABLE) {
				if (strcasestr(entry->fields[i].value.data,
						sw->text) != NULL) {
					matched = true;
					break;
				}
			}
		}

		if (!matched && strcasestr(n->text.data, sw->text) != NULL) {
			matched = true;
		}

		if (matched) {
			n->flags |= TV_NFLAGS_MATCHED;
			sw->window_height += tree_g.line_height;
		} else {
			n->flags &= ~TV_NFLAGS_MATCHED;
		}
	}

	return NSERROR_OK;
}


/**
 * Search treeview for text.
 *
 * \param[in] tree  Treeview to search.
 * \param[in] text  UTF-8 string to search for.  (NULL-terminated.)
 * \param[in] len   Byte length of UTF-8 string.
 * \return NSERROR_OK on success, appropriate error otherwise.
 */
static nserror treeview__search(
		treeview *tree,
		const char *text,
		unsigned int len)
{
	nserror err;
	uint32_t height;
	struct treeview_search_walk_data sw = {
		.len = len,
		.text = text,
		.tree = tree,
		.window_height = 0,
	};

	assert(text[len] == '\0');

	err = treeview_walk_internal(tree->root, true, NULL,
			treeview__search_walk_cb, &sw);
	if (err != NSERROR_OK) {
		return err;
	}

	if (len > 0) {
		tree->search.search = true;
		height = sw.window_height;
	} else {
		tree->search.search = false;
		height = tree->root->height;
	}

	treeview__cw_update_size(tree, -1, height);
	treeview__cw_scroll_top(tree);

	return NSERROR_OK;
}


/**
 * Callback for textarea_create, in desktop/treeview.h
 *
 * \param data treeview context
 * \param msg textarea message
 */
static void treeview_textarea_search_callback(void *data,
		struct textarea_msg *msg)
{
	treeview *tree = data;
	struct rect *r;

	if (tree->search.active == false) {
		return;
	}

	switch (msg->type) {
	case TEXTAREA_MSG_DRAG_REPORT:
		if (msg->data.drag == TEXTAREA_DRAG_NONE) {
			/* Textarea drag finished */
			tree->drag.type = TV_DRAG_NONE;
		} else {
			/* Textarea drag started */
			tree->drag.type = TV_DRAG_SEARCH;
		}
		treeview__cw_drag_status(tree, tree->drag.type);
		break;

	case TEXTAREA_MSG_REDRAW_REQUEST:
		r = &msg->data.redraw;
		r->x0 += tree_g.window_padding + tree_g.icon_size;
		r->y0 += 0;
		r->x1 += 600;
		r->y1 += tree_g.line_height;

		/* Redraw the textarea */
		cw_invalidate_area(tree, r);
		break;

	case TEXTAREA_MSG_TEXT_MODIFIED:
		/* Textarea length includes trailing NULL, so subtract it. */
		treeview__search(tree,
				msg->data.modified.text,
				msg->data.modified.len - 1);
		break;

	default:
		break;
	}
}


/* Exported interface, documented in treeview.h */
nserror
treeview_create(treeview **tree,
		const struct treeview_callback_table *callbacks,
		int n_fields,
		struct treeview_field_desc fields[],
		const struct core_window_callback_table *cw_t,
		struct core_window *cw,
		treeview_flags flags)
{
	nserror error;
	int i;

	assert((cw_t == NULL && cw == NULL) || (cw_t != NULL && cw != NULL));
	assert(callbacks != NULL);

	assert(fields != NULL);
	assert(fields[0].flags & TREE_FLAG_DEFAULT);
	assert(fields[n_fields - 1].flags & TREE_FLAG_DEFAULT);
	assert(n_fields >= 2);

	*tree = malloc(sizeof(struct treeview));
	if (*tree == NULL) {
		return NSERROR_NOMEM;
	}

	(*tree)->fields = malloc(sizeof(struct treeview_field) * n_fields);
	if ((*tree)->fields == NULL) {
		free(tree);
		return NSERROR_NOMEM;
	}

	error = treeview_create_node_root(&((*tree)->root));
	if (error != NSERROR_OK) {
		free((*tree)->fields);
		free(*tree);
		return error;
	}

	(*tree)->field_width = 0;
	for (i = 0; i < n_fields; i++) {
		struct treeview_field *f = &((*tree)->fields[i]);

		f->flags = fields[i].flags;
		f->field = lwc_string_ref(fields[i].field);
		f->value.data = lwc_string_data(fields[i].field);
		f->value.len = lwc_string_length(fields[i].field);

		guit->layout->width(&plot_style_odd.text, f->value.data,
				    f->value.len, &(f->value.width));

		if (f->flags & TREE_FLAG_SHOW_NAME)
			if ((*tree)->field_width < f->value.width)
				(*tree)->field_width = f->value.width;
	}

	(*tree)->field_width += tree_g.step_width;

	(*tree)->callbacks = callbacks;
	(*tree)->n_fields = n_fields - 1;

	(*tree)->drag.type = TV_DRAG_NONE;
	(*tree)->drag.start_node = NULL;
	(*tree)->drag.start.x = 0;
	(*tree)->drag.start.y = 0;
	(*tree)->drag.start.node_y = 0;
	(*tree)->drag.start.node_h = 0;
	(*tree)->drag.prev.x = 0;
	(*tree)->drag.prev.y = 0;
	(*tree)->drag.prev.node_y = 0;
	(*tree)->drag.prev.node_h = 0;

	(*tree)->move.root = NULL;
	(*tree)->move.target = NULL;
	(*tree)->move.target_pos = TV_TARGET_NONE;

	(*tree)->edit.textarea = NULL;
	(*tree)->edit.node = NULL;

	if (flags & TREEVIEW_SEARCHABLE) {
		(*tree)->search.textarea = treeview__create_textarea(
				*tree, 600, tree_g.line_height,
				plot_style_even.text.background,
				plot_style_even.text.background,
				plot_style_even.text.foreground,
				plot_style_odd.text,
				treeview_textarea_search_callback);
		if ((*tree)->search.textarea == NULL) {
			treeview_destroy(*tree);
			return NSERROR_NOMEM;
		}
	} else {
		(*tree)->search.textarea = NULL;
	}
	(*tree)->search.active = false;
	(*tree)->search.search = false;

	(*tree)->flags = flags;

	(*tree)->cw_t = cw_t;
	(*tree)->cw_h = cw;

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror
treeview_cw_attach(treeview *tree,
		   const struct core_window_callback_table *cw_t,
		   struct core_window *cw)
{
	assert(cw_t != NULL);
	assert(cw != NULL);

	if (tree->cw_t != NULL || tree->cw_h != NULL) {
		NSLOG(netsurf, INFO, "Treeview already attached.");
		return NSERROR_UNKNOWN;
	}
	tree->cw_t = cw_t;
	tree->cw_h = cw;

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_cw_detach(treeview *tree)
{
	tree->cw_t = NULL;
	tree->cw_h = NULL;

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_destroy(treeview *tree)
{
	int f;

	assert(tree != NULL);

	/* Destroy nodes */
	treeview_delete_node_internal(tree, tree->root, false,
				      TREE_OPTION_SUPPRESS_RESIZE |
				      TREE_OPTION_SUPPRESS_REDRAW);

	/* Destroy feilds */
	for (f = 0; f <= tree->n_fields; f++) {
		lwc_string_unref(tree->fields[f].field);
	}
	free(tree->fields);

	if (tree->search.textarea != NULL) {
		textarea_destroy(tree->search.textarea);
	}

	/* Free treeview */
	free(tree);

	return NSERROR_OK;
}


/**
 * Expand a treeview's nodes
 *
 * \param tree Treeview object to expand nodes in
 * \param node The node to expand.
 * \return NSERROR_OK on success, appropriate error otherwise.
 */
static nserror
treeview_node_expand_internal(treeview *tree, treeview_node *node)
{
	treeview_node *child;
	struct treeview_node_entry *e;
	int additional_height = 0;
	int i;

	assert(tree != NULL);
	assert(node != NULL);

	if (node->flags & TV_NFLAGS_EXPANDED) {
		/* What madness is this? */
		NSLOG(netsurf, INFO, "Tried to expand an expanded node.");
		return NSERROR_OK;
	}

	switch (node->type) {
	case TREE_NODE_FOLDER:
		child = node->children;
		if (child == NULL) {
			/* Allow expansion of empty folders */
			break;
		}

		do {
			assert((child->flags & TV_NFLAGS_EXPANDED) == false);
			if (child->text.width == 0) {
				guit->layout->width(&plot_style_odd.text,
						    child->text.data,
						    child->text.len,
						    &(child->text.width));
			}

			additional_height += child->height;

			child = child->next_sib;
		} while (child != NULL);

		break;

	case TREE_NODE_ENTRY:
		assert(node->children == NULL);

		e = (struct treeview_node_entry *)node;

		for (i = 0; i < tree->n_fields - 1; i++) {

			if (e->fields[i].value.width == 0) {
				guit->layout->width(&plot_style_odd.text,
						    e->fields[i].value.data,
						    e->fields[i].value.len,
						    &(e->fields[i].value.width));
			}

			/* Add height for field */
			additional_height += tree_g.line_height;
		}

		break;

	case TREE_NODE_ROOT:
	case TREE_NODE_NONE:
		assert(node->type != TREE_NODE_ROOT);
		assert(node->type != TREE_NODE_NONE);
		break;
	}

	/* Update the node */
	node->flags |= TV_NFLAGS_EXPANDED;

	/* And parent's heights */
	do {
		node->height += additional_height;
		node = node->parent;
	} while (node->parent != NULL);

	node->height += additional_height;

	/* Inform front end of change in dimensions */
	if (additional_height != 0) {
		treeview__cw_update_size(tree, -1, tree->root->height);
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_node_expand(treeview *tree, treeview_node *node)
{
	nserror res;
	struct rect r;

	res = treeview_node_expand_internal(tree, node);
	if (res == NSERROR_OK) {
		/* expansion was successful, attempt redraw */
		r.x0 = 0;
		r.y0 = treeview_node_y(tree, node);
		r.x1 = REDRAW_MAX;
		r.y1 = tree->root->height;

		cw_invalidate_area(tree, &r);
	}

	return res;
}


/**
 * context for treeview contraction callback
 */
struct treeview_contract_data {
	bool only_entries;
};


/**
 * Treewalk node callback for handling node contraction.
 *
 * \param n node
 * \param ctx contract iterator context
 * \param end flag to end iteration now
 * \return NSERROR_OK on success else appropriate error code
 */
static nserror treeview_node_contract_cb(treeview_node *n, void *ctx, bool *end)
{
	struct treeview_contract_data *data = ctx;
	int h_reduction;

	assert(n != NULL);
	assert(n->type != TREE_NODE_ROOT);

	n->flags &= ~TV_NFLAGS_SELECTED;

	if ((n->flags & TV_NFLAGS_EXPANDED) == false ||
	    (n->type == TREE_NODE_FOLDER && data->only_entries)) {
		/* Nothing to do. */
		return NSERROR_OK;
	}

	n->flags ^= TV_NFLAGS_EXPANDED;
	h_reduction = n->height - tree_g.line_height;

	assert(h_reduction >= 0);

	do {
		n->height -= h_reduction;
		n = n->parent;
	} while (n != NULL);

	return NSERROR_OK;
}


/**
 * Contract a treeview node
 *
 * \param tree Treeview object to contract node in
 * \param node Node to contract
 * \return NSERROR_OK on success, appropriate error otherwise
 */
static nserror
treeview_node_contract_internal(treeview *tree, treeview_node *node)
{
	struct treeview_contract_data data;
	bool selected;
	assert(node != NULL);

	if ((node->flags & TV_NFLAGS_EXPANDED) == false) {
		/* What madness is this? */
		NSLOG(netsurf, INFO, "Tried to contract a contracted node.");
		return NSERROR_OK;
	}

	data.only_entries = false;
	selected = node->flags & TV_NFLAGS_SELECTED;

	/* Contract children. */
	treeview_walk_internal(node, false, treeview_node_contract_cb,
			       NULL, &data);

	/* Contract node */
	treeview_node_contract_cb(node, &data, false);

	if (selected)
		node->flags |= TV_NFLAGS_SELECTED;

	/* Inform front end of change in dimensions */
	treeview__cw_update_size(tree, -1, tree->root->height);

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_node_contract(treeview *tree, treeview_node *node)
{
	nserror res;
	struct rect r;

	assert(tree != NULL);

	res = treeview_node_contract_internal(tree, node);
	if (res == NSERROR_OK) {
		/* successful contraction, request redraw */
		r.x0 = 0;
		r.y0 = treeview_node_y(tree, node);
		r.x1 = REDRAW_MAX;
		r.y1 = tree->root->height;

		cw_invalidate_area(tree, &r);
	}

	return res;
}


/* Exported interface, documented in treeview.h */
nserror treeview_contract(treeview *tree, bool all)
{
	struct treeview_contract_data data;
	bool selected;
	treeview_node *n;
	struct rect r;

	assert(tree != NULL);
	assert(tree->root != NULL);

	r.x0 = 0;
	r.y0 = 0;
	r.x1 = REDRAW_MAX;
	r.y1 = tree->root->height;

	data.only_entries = !all;

	for (n = tree->root->children; n != NULL; n = n->next_sib) {
		if ((n->flags & TV_NFLAGS_EXPANDED) == false) {
			continue;
		}

		selected = n->flags & TV_NFLAGS_SELECTED;

		/* Contract children. */
		treeview_walk_internal(n, false,
				       treeview_node_contract_cb, NULL, &data);

		/* Contract node */
		treeview_node_contract_cb(n, &data, false);

		if (selected)
			n->flags |= TV_NFLAGS_SELECTED;
	}

	/* Inform front end of change in dimensions */
	treeview__cw_update_size(tree, -1, tree->root->height);

	/* Redraw */
	cw_invalidate_area(tree, &r);

	return NSERROR_OK;
}


/**
 * context data for treeview expansion
 */
struct treeview_expand_data {
	treeview *tree;
	bool only_folders;
};


/**
 * Treewalk node callback for handling recursive node expansion.
 *
 * \param n current node
 * \param ctx node expansion context
 * \param skip_children flag to allow children to be skipped
 * \param end flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror
treeview_expand_cb(treeview_node *n,
		   void *ctx,
		   bool *skip_children,
		   bool *end)
{
	struct treeview_expand_data *data = ctx;
	nserror err;

	assert(n != NULL);
	assert(n->type != TREE_NODE_ROOT);

	if (n->flags & TV_NFLAGS_EXPANDED ||
	    (data->only_folders && n->type != TREE_NODE_FOLDER)) {
		/* Nothing to do. */
		return NSERROR_OK;
	}

	err = treeview_node_expand_internal(data->tree, n);

	return err;
}


/* Exported interface, documented in treeview.h */
nserror treeview_expand(treeview *tree, bool only_folders)
{
	struct treeview_expand_data data;
	nserror res;
	struct rect r;

	assert(tree != NULL);
	assert(tree->root != NULL);

	data.tree = tree;
	data.only_folders = only_folders;

	res = treeview_walk_internal(tree->root,
				     true,
				     NULL,
				     treeview_expand_cb,
				     &data);
	if (res == NSERROR_OK) {
		/* expansion succeeded, schedule redraw */

		r.x0 = 0;
		r.y0 = 0;
		r.x1 = REDRAW_MAX;
		r.y1 = tree->root->height;

		cw_invalidate_area(tree, &r);
	}
	return res;
}


/**
 * Draw a treeview normally, in tree mode.
 *
 * \param[in]     tree      The treeview we're rendering.
 * \param[in]     x         X coordinate we're rendering the treeview at.
 * \param[in]     y         Y coordinate we're rendering the treeview at.
 * \param[in,out] render_y  Current vertical position in tree, updated on exit.
 * \param[in]     r         Clip rectangle.
 * \param[in]     data      Redraw data for rendering contents.
 * \param[in]     ctx       Current render context.
 */
static void treeview_redraw_tree(
		treeview *tree,
		const int x,
		const int y,
		int *render_y_in_out,
		struct rect *r,
		struct content_redraw_data *data,
		const struct redraw_context *ctx)
{
	struct treeview_node_style *style = &plot_style_odd;
	enum treeview_resource_id res = TREE_RES_CONTENT;
	int baseline = (tree_g.line_height * 3 + 2) / 4;
	plot_font_style_t *infotext_style;
	treeview_node *root = tree->root;
	treeview_node *node = tree->root;
	int render_y = *render_y_in_out;
	plot_font_style_t *text_style;
	plot_style_t *bg_style;
	int sel_min, sel_max;
	uint32_t count = 0;
	struct rect rect;
	int inset;
	int x0;

	if (tree->drag.start.y > tree->drag.prev.y) {
		sel_min = tree->drag.prev.y;
		sel_max = tree->drag.start.y;
	} else {
		sel_min = tree->drag.start.y;
		sel_max = tree->drag.prev.y;
	}

	while (node != NULL) {
		struct treeview_node_entry *entry;
		struct bitmap *furniture;
		bool invert_selection;
		treeview_node *next;
		int height;
		int i;

		next = (node->flags & TV_NFLAGS_EXPANDED) ?
			node->children : NULL;

		if (next != NULL) {
			/* down to children */
			node = next;
		} else {
			/* No children.  As long as we're not at the root,
			 * go to next sibling if present, or nearest ancestor
			 * with a next sibling. */

			while (node != root &&
			       node->next_sib == NULL) {
				node = node->parent;
			}

			if (node == root)
				break;

			node = node->next_sib;
		}

		assert(node != NULL);
		assert(node != root);
		assert(node->type == TREE_NODE_FOLDER ||
		       node->type == TREE_NODE_ENTRY);

		count++;
		inset = x + node->inset;
		height = (node->type == TREE_NODE_ENTRY) ? node->height :
			tree_g.line_height;

		if ((render_y + height) < r->y0) {
			/* This node's line is above clip region */
			render_y += height;
			continue;
		}

		style = (count & 0x1) ? &plot_style_odd : &plot_style_even;
		if (tree->drag.type == TV_DRAG_SELECTION &&
		    (render_y + height >= sel_min &&
		     render_y < sel_max)) {
			invert_selection = true;
		} else {
			invert_selection = false;
		}
		if ((node->flags & TV_NFLAGS_SELECTED && !invert_selection) ||
		    (!(node->flags & TV_NFLAGS_SELECTED) &&
		     invert_selection)) {
			bg_style = &style->sbg;
			text_style = &style->stext;
			infotext_style = &style->sitext;
			furniture = (node->flags & TV_NFLAGS_EXPANDED) ?
				style->furn[TREE_FURN_CONTRACT].sel :
				style->furn[TREE_FURN_EXPAND].sel;
		} else {
			bg_style = &style->bg;
			text_style = &style->text;
			infotext_style = &style->itext;
			furniture = (node->flags & TV_NFLAGS_EXPANDED) ?
				style->furn[TREE_FURN_CONTRACT].bmp :
				style->furn[TREE_FURN_EXPAND].bmp;
		}

		/* Render background */
		rect.x0 = r->x0;
		rect.y0 = render_y;
		rect.x1 = r->x1;
		rect.y1 = render_y + height;
		ctx->plot->rectangle(ctx, bg_style, &rect);

		/* Render toggle */
		ctx->plot->bitmap(ctx,
				furniture,
				inset,
				render_y + tree_g.line_height / 4,
				style->furn[TREE_FURN_EXPAND].size,
				style->furn[TREE_FURN_EXPAND].size,
				bg_style->fill_colour,
				BITMAPF_NONE);

		/* Render icon */
		if (node->type == TREE_NODE_ENTRY) {
			res = TREE_RES_CONTENT;
		} else if (node->flags & TV_NFLAGS_SPECIAL) {
			res = TREE_RES_FOLDER_SPECIAL;
		} else {
			res = TREE_RES_FOLDER;
		}

		if (treeview_res[res].ready) {
			/* Icon resource is available */
			data->x = inset + tree_g.step_width;
			data->y = render_y + ((tree_g.line_height -
					      treeview_res[res].height + 1) / 2);
			data->background_colour = bg_style->fill_colour;

			content_redraw(treeview_res[res].c, data, r, ctx);
		}

		/* Render text */
		x0 = inset + tree_g.step_width + tree_g.icon_step;
		ctx->plot->text(ctx,
				text_style,
				x0, render_y + baseline,
				node->text.data,
				node->text.len);

		/* Rendered the node */
		render_y += tree_g.line_height;
		if (render_y > r->y1) {
			/* Passed the bottom of what's in the clip region.
			 * Done. */
			break;
		}


		if (node->type != TREE_NODE_ENTRY ||
		    !(node->flags & TV_NFLAGS_EXPANDED))
			/* Done everything for this node */
			continue;

		/* Render expanded entry fields */
		entry = (struct treeview_node_entry *)node;
		for (i = 0; i < tree->n_fields - 1; i++) {
			struct treeview_field *ef = &(tree->fields[i + 1]);

			if (ef->flags & TREE_FLAG_SHOW_NAME) {
				int max_width = tree->field_width;

				ctx->plot->text(ctx,
						infotext_style,
						x0 + max_width - ef->value.width - tree_g.step_width,
						render_y + baseline,
						ef->value.data,
						ef->value.len);

				ctx->plot->text(ctx,
						infotext_style,
						x0 + max_width,
						render_y + baseline,
						entry->fields[i].value.data,
						entry->fields[i].value.len);
			} else {
				ctx->plot->text(ctx,
						infotext_style,
						x0, render_y + baseline,
						entry->fields[i].value.data,
						entry->fields[i].value.len);
			}

			/* Rendered the expanded entry field */
			render_y += tree_g.line_height;
		}

		/* Finished rendering expanded entry */

		if (render_y > r->y1) {
			/* Passed the bottom of what's in the clip region.
			 * Done. */
			break;
		}
	}

	*render_y_in_out = render_y;
}


/**
 * Draw a treeview normally, in tree mode.
 *
 * \param[in]     tree      The treeview we're rendering.
 * \param[in]     x         X coordinate we're rendering the treeview at.
 * \param[in]     y         Y coordinate we're rendering the treeview at.
 * \param[in,out] render_y  Current vertical position in tree, updated on exit.
 * \param[in]     r         Clip rectangle.
 * \param[in]     data      Redraw data for rendering contents.
 * \param[in]     ctx       Current render context.
 */
static void treeview_redraw_search(
		treeview *tree,
		const int x,
		const int y,
		int *render_y_in_out,
		struct rect *r,
		struct content_redraw_data *data,
		const struct redraw_context *ctx)
{
	struct treeview_node_style *style = &plot_style_odd;
	enum treeview_resource_id res = TREE_RES_CONTENT;
	int baseline = (tree_g.line_height * 3 + 2) / 4;
	plot_font_style_t *infotext_style;
	treeview_node *root = tree->root;
	treeview_node *node = tree->root;
	int render_y = *render_y_in_out;
	plot_font_style_t *text_style;
	plot_style_t *bg_style;
	int sel_min, sel_max;
	uint32_t count = 0;
	struct rect rect;
	int inset;
	int x0;

	if (tree->drag.start.y > tree->drag.prev.y) {
		sel_min = tree->drag.prev.y;
		sel_max = tree->drag.start.y;
	} else {
		sel_min = tree->drag.start.y;
		sel_max = tree->drag.prev.y;
	}

	while (node != NULL) {
		struct treeview_node_entry *entry;
		struct bitmap *furniture;
		bool invert_selection;
		treeview_node *next;
		int height;
		int i;

		next = node->children;

		if (next != NULL) {
			/* down to children */
			node = next;
		} else {
			/* No children.  As long as we're not at the root,
			 * go to next sibling if present, or nearest ancestor
			 * with a next sibling. */

			while (node != root &&
			       node->next_sib == NULL) {
				node = node->parent;
			}

			if (node == root)
				break;

			node = node->next_sib;
		}

		assert(node != NULL);
		assert(node != root);
		assert(node->type == TREE_NODE_FOLDER ||
		       node->type == TREE_NODE_ENTRY);

		if (node->type == TREE_NODE_FOLDER ||
				!(node->flags & TV_NFLAGS_MATCHED)) {
			continue;
		}

		count++;
		inset = x + tree_g.window_padding;
		height = tree_g.line_height;

		if ((render_y + height) < r->y0) {
			/* This node's line is above clip region */
			render_y += height;
			continue;
		}

		style = (count & 0x1) ? &plot_style_odd : &plot_style_even;
		if (tree->drag.type == TV_DRAG_SELECTION &&
		    (render_y + height >= sel_min &&
		     render_y < sel_max)) {
			invert_selection = true;
		} else {
			invert_selection = false;
		}
		if ((node->flags & TV_NFLAGS_SELECTED && !invert_selection) ||
		    (!(node->flags & TV_NFLAGS_SELECTED) &&
		     invert_selection)) {
			bg_style = &style->sbg;
			text_style = &style->stext;
			infotext_style = &style->sitext;
			furniture = (node->flags & TV_NFLAGS_EXPANDED) ?
				style->furn[TREE_FURN_CONTRACT].sel :
				style->furn[TREE_FURN_EXPAND].sel;
		} else {
			bg_style = &style->bg;
			text_style = &style->text;
			infotext_style = &style->itext;
			furniture = (node->flags & TV_NFLAGS_EXPANDED) ?
				style->furn[TREE_FURN_CONTRACT].bmp :
				style->furn[TREE_FURN_EXPAND].bmp;
		}

		/* Render background */
		rect.x0 = r->x0;
		rect.y0 = render_y;
		rect.x1 = r->x1;
		rect.y1 = render_y + height;
		ctx->plot->rectangle(ctx, bg_style, &rect);

		/* Render toggle */
		ctx->plot->bitmap(ctx,
				furniture,
				inset,
				render_y + tree_g.line_height / 4,
				style->furn[TREE_FURN_EXPAND].size,
				style->furn[TREE_FURN_EXPAND].size,
				bg_style->fill_colour,
				BITMAPF_NONE);

		/* Render icon */
		if (node->type == TREE_NODE_ENTRY) {
			res = TREE_RES_CONTENT;
		} else if (node->flags & TV_NFLAGS_SPECIAL) {
			res = TREE_RES_FOLDER_SPECIAL;
		} else {
			res = TREE_RES_FOLDER;
		}

		if (treeview_res[res].ready) {
			/* Icon resource is available */
			data->x = inset + tree_g.step_width;
			data->y = render_y + ((tree_g.line_height -
					      treeview_res[res].height + 1) / 2);
			data->background_colour = bg_style->fill_colour;

			content_redraw(treeview_res[res].c, data, r, ctx);
		}

		/* Render text */
		x0 = inset + tree_g.step_width + tree_g.icon_step;
		ctx->plot->text(ctx,
				text_style,
				x0, render_y + baseline,
				node->text.data,
				node->text.len);

		/* Rendered the node */
		render_y += tree_g.line_height;
		if (render_y > r->y1) {
			/* Passed the bottom of what's in the clip region.
			 * Done. */
			break;
		}


		if (node->type != TREE_NODE_ENTRY ||
		    !(node->flags & TV_NFLAGS_EXPANDED))
			/* Done everything for this node */
			continue;

		/* Render expanded entry fields */
		entry = (struct treeview_node_entry *)node;
		for (i = 0; i < tree->n_fields - 1; i++) {
			struct treeview_field *ef = &(tree->fields[i + 1]);

			if (ef->flags & TREE_FLAG_SHOW_NAME) {
				int max_width = tree->field_width;

				ctx->plot->text(ctx,
						infotext_style,
						x0 + max_width - ef->value.width - tree_g.step_width,
						render_y + baseline,
						ef->value.data,
						ef->value.len);

				ctx->plot->text(ctx,
						infotext_style,
						x0 + max_width,
						render_y + baseline,
						entry->fields[i].value.data,
						entry->fields[i].value.len);
			} else {
				ctx->plot->text(ctx,
						infotext_style,
						x0, render_y + baseline,
						entry->fields[i].value.data,
						entry->fields[i].value.len);
			}

			/* Rendered the expanded entry field */
			render_y += tree_g.line_height;
		}

		/* Finished rendering expanded entry */

		if (render_y > r->y1) {
			/* Passed the bottom of what's in the clip region.
			 * Done. */
			break;
		}
	}

	*render_y_in_out = render_y;
}


/* Exported interface, documented in treeview.h */
void
treeview_redraw(treeview *tree,
		const int x,
		const int y,
		struct rect *clip,
		const struct redraw_context *ctx)
{
	struct redraw_context new_ctx = *ctx;
	struct content_redraw_data data;
	struct rect r;
	struct rect rect;
	int render_y = y;

	assert(tree != NULL);
	assert(tree->root != NULL);
	assert(tree->root->flags & TV_NFLAGS_EXPANDED);

	/* Start knockout rendering if it's available for this plotter */
	if (ctx->plot->option_knockout) {
		knockout_plot_start(ctx, &new_ctx);
	}

	/* Set up clip rectangle */
	r.x0 = clip->x0 + x;
	r.y0 = clip->y0 + y;
	r.x1 = clip->x1 + x;
	r.y1 = clip->y1 + y;
	new_ctx.plot->clip(&new_ctx, &r);

	/* Setup common content redraw data */
	data.width = tree_g.icon_size;
	data.height = tree_g.icon_size;
	data.scale = 1;
	data.repeat_x = false;
	data.repeat_y = false;

	if (tree->flags & TREEVIEW_SEARCHABLE) {
		if (render_y < r.y1) {
			enum treeview_resource_id icon = TREE_RES_SEARCH;

			/* Fill the blank area at the bottom */
			rect.x0 = r.x0;
			rect.y0 = render_y;
			rect.x1 = r.x1;
			rect.y1 = render_y + tree_g.line_height;
			new_ctx.plot->rectangle(&new_ctx, &plot_style_even.bg,
					&rect);

			if (treeview_res[icon].ready) {
				/* Icon resource is available */
				data.x = tree_g.window_padding;
				data.y = render_y + ((tree_g.line_height -
						treeview_res[icon].height + 1) /
						2);
				data.background_colour = plot_style_even.bg.
						fill_colour;

				content_redraw(treeview_res[icon].c,
						&data, &r, &new_ctx);
			}

			textarea_redraw(tree->search.textarea,
					x + tree_g.window_padding +
							tree_g.icon_step, y,
					plot_style_even.bg.fill_colour, 1.0,
					&r, &new_ctx);
		}
		render_y += tree_g.line_height;
	}

	/* Render the treeview data */
	if (tree->search.search == true) {
		treeview_redraw_search(tree, x, y,
				&render_y, &r, &data, &new_ctx);
	} else {
		treeview_redraw_tree(tree, x, y,
				&render_y, &r, &data, &new_ctx);
	}

	if (render_y < r.y1) {
		/* Fill the blank area at the bottom */
		rect.x0 = r.x0;
		rect.y0 = render_y;
		rect.x1 = r.x1;
		rect.y1 = r.y1;
		new_ctx.plot->rectangle(&new_ctx, &plot_style_even.bg, &rect);
	}

	/* All normal treeview rendering is done; render any overlays */
	if ((tree->move.target_pos != TV_TARGET_NONE) &&
	    (treeview_res[TREE_RES_ARROW].ready)) {
		/* Got a MOVE drag; render move indicator arrow */
		data.x = tree->move.target_area.x0 + x;
		data.y = tree->move.target_area.y0 + y;
		data.background_colour = plot_style_even.bg.fill_colour;

		content_redraw(treeview_res[TREE_RES_ARROW].c, &data, &r, &new_ctx);

	} else if (tree->edit.textarea != NULL) {
		/* Edit in progress; render textarea */
		textarea_redraw(tree->edit.textarea,
				tree->edit.x + x, tree->edit.y + y,
				plot_style_even.bg.fill_colour, 1.0,
				&r, &new_ctx);
	}

	/* Rendering complete */
	if (ctx->plot->option_knockout) {
		knockout_plot_end(ctx);
	}
}


/**
 * context for treeview selection
 */
struct treeview_selection_walk_data {
	enum {
		TREEVIEW_WALK_HAS_SELECTION,
		TREEVIEW_WALK_GET_FIRST_SELECTED,
		TREEVIEW_WALK_CLEAR_SELECTION,
		TREEVIEW_WALK_SELECT_ALL,
		TREEVIEW_WALK_COMMIT_SELECT_DRAG,
		TREEVIEW_WALK_DELETE_SELECTION,
		TREEVIEW_WALK_PROPAGATE_SELECTION,
		TREEVIEW_WALK_YANK_SELECTION,
		TREEVIEW_WALK_COPY_SELECTION
	} purpose;
	union {
		bool has_selection;
		struct {
			bool required;
			struct rect *rect;
		} redraw;
		struct {
			int sel_min;
			int sel_max;
		} drag;
		struct {
			treeview_node *prev;
		} yank;
		struct {
			treeview_node *n;
		} first;
		struct {
			char *text;
			uint32_t len;
		} copy;
	} data;
	int current_y;
	treeview *tree;
};


/**
 * Treewalk node callback for handling selection related actions.
 *
 * \param n current node
 * \param ctx node selection context
 * \param skip_children flag to allow children to be skipped
 * \param end flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror
treeview_node_selection_walk_cb(treeview_node *n,
				void *ctx,
				bool *skip_children,
				bool *end)
{
	struct treeview_selection_walk_data *sw = ctx;
	int height;
	bool changed = false;
	nserror err;

	height = (n->type == TREE_NODE_ENTRY) ? n->height : tree_g.line_height;
	sw->current_y += height;

	switch (sw->purpose) {
	case TREEVIEW_WALK_HAS_SELECTION:
		if (n->flags & TV_NFLAGS_SELECTED) {
			sw->data.has_selection = true;
			*end = true; /* Can abort tree walk */
			return NSERROR_OK;
		}
		break;

	case TREEVIEW_WALK_GET_FIRST_SELECTED:
		if (n->flags & TV_NFLAGS_SELECTED) {
			sw->data.first.n = n;
			*end = true; /* Can abort tree walk */
			return NSERROR_OK;
		}
		break;

	case TREEVIEW_WALK_DELETE_SELECTION:
		if (n->flags & TV_NFLAGS_SELECTED) {
			err = treeview_delete_node_internal(sw->tree, n, true,
							    TREE_OPTION_NONE);
			if (err != NSERROR_OK) {
				return err;
			}
			*skip_children = true;
			changed = true;
		}
		break;

	case TREEVIEW_WALK_PROPAGATE_SELECTION:
		if (n->parent != NULL &&
		    n->parent->flags & TV_NFLAGS_SELECTED &&
		    !(n->flags & TV_NFLAGS_SELECTED)) {
			n->flags ^= TV_NFLAGS_SELECTED;
			changed = true;
		}
		break;

	case TREEVIEW_WALK_CLEAR_SELECTION:
		if (n->flags & TV_NFLAGS_SELECTED) {
			n->flags ^= TV_NFLAGS_SELECTED;
			changed = true;
		}
		break;

	case TREEVIEW_WALK_SELECT_ALL:
		if (!(n->flags & TV_NFLAGS_SELECTED)) {
			n->flags ^= TV_NFLAGS_SELECTED;
			changed = true;
		}
		break;

	case TREEVIEW_WALK_COMMIT_SELECT_DRAG:
		if (sw->current_y >= sw->data.drag.sel_min &&
		    sw->current_y - height <
		    sw->data.drag.sel_max) {
			n->flags ^= TV_NFLAGS_SELECTED;
		}
		return NSERROR_OK;

	case TREEVIEW_WALK_YANK_SELECTION:
		if (n->flags & TV_NFLAGS_SELECTED) {
			treeview_node *p = n->parent;
			int h = 0;

			if (treeview_unlink_node(n))
				h = n->height;

			/* Reduce ancestor heights */
			while (p != NULL && p->flags & TV_NFLAGS_EXPANDED) {
				p->height -= h;
				p = p->parent;
			}
			if (sw->data.yank.prev == NULL) {
				sw->tree->move.root = n;
				n->parent = NULL;
				n->prev_sib = NULL;
				n->next_sib = NULL;
			} else {
				n->parent = NULL;
				n->prev_sib = sw->data.yank.prev;
				n->next_sib = NULL;
				sw->data.yank.prev->next_sib = n;
			}
			sw->data.yank.prev = n;

			*skip_children = true;
		}
		break;

	case TREEVIEW_WALK_COPY_SELECTION:
		if (n->flags & TV_NFLAGS_SELECTED &&
		    n->type == TREE_NODE_ENTRY) {
			int i;
			char *temp;
			uint32_t len;
			const char *text;
			struct treeview_field *ef;
			struct treeview_text *val;

			for (i = 0; i < sw->tree->n_fields; i++) {
				ef = &(sw->tree->fields[i]);

				if (!(ef->flags & TREE_FLAG_COPY_TEXT)) {
					continue;
				}
				val = treeview_get_text_for_field(sw->tree,
								  n, i);
				text = val->data;
				len  = val->len;

				temp = realloc(sw->data.copy.text,
					       sw->data.copy.len + len + 1);
				if (temp == NULL) {
					free(sw->data.copy.text);
					sw->data.copy.text = NULL;
					sw->data.copy.len = 0;
					return NSERROR_NOMEM;
				}

				if (sw->data.copy.len != 0) {
					temp[sw->data.copy.len - 1] = '\n';
				}
				memcpy(temp + sw->data.copy.len, text, len);
				temp[sw->data.copy.len + len] = '\0';
				sw->data.copy.len += len + 1;
				sw->data.copy.text = temp;
			}
		}
		break;
	}

	if (changed) {
		if (sw->data.redraw.required == false) {
			sw->data.redraw.required = true;
			sw->data.redraw.rect->y0 = sw->current_y - height;
		}

		if (sw->current_y > sw->data.redraw.rect->y1) {
			sw->data.redraw.rect->y1 = sw->current_y;
		}
	}

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
bool treeview_has_selection(treeview *tree)
{
	struct treeview_selection_walk_data sw;

	sw.purpose = TREEVIEW_WALK_HAS_SELECTION;
	sw.data.has_selection = false;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.has_selection;
}


/**
 * Get first selected node (in any)
 *
 * \param tree Treeview object in which to create folder
 * \return the first selected treeview node, or NULL
 */
static treeview_node * treeview_get_first_selected(treeview *tree)
{
	struct treeview_selection_walk_data sw;

	sw.purpose = TREEVIEW_WALK_GET_FIRST_SELECTED;
	sw.data.first.n = NULL;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.first.n;
}


/* Exported interface, documented in treeview.h */
enum treeview_node_type treeview_get_selection(treeview *tree,
					       void **node_data)
{
	treeview_node *n;

	assert(tree != NULL);

	n = treeview_get_first_selected(tree);

	if (n != NULL && n->type & (TREE_NODE_ENTRY | TREE_NODE_FOLDER)) {
		*node_data = n->client_data;
		return n->type;
	}

	*node_data = NULL;
	return TREE_NODE_NONE;
}


/**
 * Clear any selection in a treeview
 *
 * \param tree Treeview object to clear selection in
 * \param rect Redraw rectangle (if redraw required)
 * \return true iff redraw required
 */
static bool treeview_clear_selection(treeview *tree, struct rect *rect)
{
	struct treeview_selection_walk_data sw;

	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	rect->y1 = 0;

	sw.purpose = TREEVIEW_WALK_CLEAR_SELECTION;
	sw.data.redraw.required = false;
	sw.data.redraw.rect = rect;
	sw.current_y = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.redraw.required;
}


/**
 * Select all in a treeview
 *
 * \param tree Treeview object to select all in
 * \param rect Redraw rectangle (if redraw required)
 * \return true iff redraw required
 */
static bool treeview_select_all(treeview *tree, struct rect *rect)
{
	struct treeview_selection_walk_data sw;

	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	rect->y1 = 0;

	sw.purpose = TREEVIEW_WALK_SELECT_ALL;
	sw.data.redraw.required = false;
	sw.data.redraw.rect = rect;
	sw.current_y = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.redraw.required;
}


/**
 * Commit a current selection drag, modifying the node's selection state.
 *
 * \param tree Treeview object to commit drag selection in
 */
static void treeview_commit_selection_drag(treeview *tree)
{
	struct treeview_selection_walk_data sw;

	sw.purpose = TREEVIEW_WALK_COMMIT_SELECT_DRAG;
	sw.current_y = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	if (tree->drag.start.y > tree->drag.prev.y) {
		sw.data.drag.sel_min = tree->drag.prev.y;
		sw.data.drag.sel_max = tree->drag.start.y;
	} else {
		sw.data.drag.sel_min = tree->drag.start.y;
		sw.data.drag.sel_max = tree->drag.prev.y;
	}

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);
}


/**
 * Yank a selection to the node move list.
 *
 * \param tree Treeview object to yank selection from
 */
static void treeview_move_yank_selection(treeview *tree)
{
	struct treeview_selection_walk_data sw;

	sw.purpose = TREEVIEW_WALK_YANK_SELECTION;
	sw.data.yank.prev = NULL;
	sw.tree = tree;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);
}


/**
 * Copy a selection to the clipboard.
 *
 * \param tree Treeview object to yank selection from
 */
static void treeview_copy_selection(treeview *tree)
{
	struct treeview_selection_walk_data sw;
	nserror err;

	sw.purpose = TREEVIEW_WALK_COPY_SELECTION;
	sw.data.copy.text = NULL;
	sw.data.copy.len = 0;
	sw.tree = tree;

	err = treeview_walk_internal(tree->root, false, NULL,
				     treeview_node_selection_walk_cb, &sw);
	if (err != NSERROR_OK) {
		return;
	}

	if (sw.data.copy.text != NULL) {
		guit->clipboard->set(sw.data.copy.text,
				     sw.data.copy.len - 1, NULL, 0);
		free(sw.data.copy.text);
	}
}


/**
 * Delete a selection.
 *
 * \param tree Treeview object to delete selected nodes from
 * \param rect Updated to redraw rectangle
 * \return true iff redraw required.
 */
static bool treeview_delete_selection(treeview *tree, struct rect *rect)
{
	struct treeview_selection_walk_data sw;

	assert(tree != NULL);
	assert(tree->root != NULL);

	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	rect->y1 = tree->root->height;

	sw.purpose = TREEVIEW_WALK_DELETE_SELECTION;
	sw.data.redraw.required = false;
	sw.data.redraw.rect = rect;
	sw.current_y = 0;
	sw.tree = tree;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.redraw.required;
}


/**
 * Propagate selection to visible descendants of selected nodes.
 *
 * \param tree Treeview object to propagate selection in
 * \param rect Redraw rectangle (if redraw required)
 * \return true iff redraw required
 */
static bool treeview_propagate_selection(treeview *tree, struct rect *rect)
{
	struct treeview_selection_walk_data sw;

	assert(tree != NULL);
	assert(tree->root != NULL);

	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	rect->y1 = 0;

	sw.purpose = TREEVIEW_WALK_PROPAGATE_SELECTION;
	sw.data.redraw.required = false;
	sw.data.redraw.rect = rect;
	sw.current_y = 0;
	sw.tree = tree;

	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_selection_walk_cb, &sw);

	return sw.data.redraw.required;
}


/**
 * Move a selection according to the current move drag.
 *
 * \param tree Treeview object to move selected nodes in
 * \param rect Redraw rectangle
 * \return NSERROR_OK on success else appropriate error code
 */
static nserror treeview_move_selection(treeview *tree, struct rect *rect)
{
	treeview_node *node, *next, *parent;
	treeview_node *relation;
	enum treeview_relationship relationship;
	int height;

	assert(tree != NULL);
	assert(tree->root != NULL);
	assert(tree->root->children != NULL);
	assert(tree->move.target_pos != TV_TARGET_NONE);

	height = tree->root->height;

	/* Identify target location */
	switch (tree->move.target_pos) {
	case TV_TARGET_ABOVE:
		if (tree->move.target == NULL) {
			/* Target: After last child of root */
			relation = tree->root->children;
			while (relation->next_sib != NULL) {
				relation = relation->next_sib;
			}
			relationship = TREE_REL_NEXT_SIBLING;

		} else if (tree->move.target->prev_sib != NULL) {
			/* Target: After previous sibling */
			relation = tree->move.target->prev_sib;
			relationship = TREE_REL_NEXT_SIBLING;

		} else {
			/* Target: Target: First child of parent */
			assert(tree->move.target->parent != NULL);
			relation = tree->move.target->parent;
			relationship = TREE_REL_FIRST_CHILD;
		}
		break;

	case TV_TARGET_INSIDE:
		assert(tree->move.target != NULL);
		relation = tree->move.target;
		relationship = TREE_REL_FIRST_CHILD;
		break;

	case TV_TARGET_BELOW:
		assert(tree->move.target != NULL);
		relation = tree->move.target;
		relationship = TREE_REL_NEXT_SIBLING;
		break;

	default:
		NSLOG(netsurf, INFO, "Bad drop target for move.");
		return NSERROR_BAD_PARAMETER;
	}

	if (relationship == TREE_REL_FIRST_CHILD) {
		parent = relation;
	} else {
		parent = relation->parent;
	}

	/* The node that we're moving selection to can't itself be selected */
	assert(!(relation->flags & TV_NFLAGS_SELECTED));

	/* Move all selected nodes from treeview to tree->move.root */
	treeview_move_yank_selection(tree);

	/* Move all nodes on tree->move.root to target location */
	for (node = tree->move.root; node != NULL; node = next) {
		next = node->next_sib;

		if (!(parent->flags & TV_NFLAGS_EXPANDED)) {
			if (node->flags & TV_NFLAGS_EXPANDED)
				treeview_node_contract_internal(tree, node);
			node->flags &= ~TV_NFLAGS_SELECTED;
		}

		treeview_insert_node(node, relation, relationship);

		relation = node;
		relationship = TREE_REL_NEXT_SIBLING;
	}
	tree->move.root = NULL;

	/* Tell window, if height has changed */
	if (height != tree->root->height)
		treeview__cw_update_size(tree, -1, tree->root->height);

	/* TODO: Deal with redraw area properly */
	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	rect->y1 = REDRAW_MAX;

	return NSERROR_OK;
}


/**
 * context for treeview launch action
 */
struct treeview_launch_walk_data {
	int selected_depth;
	treeview *tree;
};


/**
 * Treewalk node walk backward callback for tracking folder selection.
 */
static nserror
treeview_node_launch_walk_bwd_cb(treeview_node *n, void *ctx, bool *end)
{
	struct treeview_launch_walk_data *lw = ctx;

	if (n->type == TREE_NODE_FOLDER && n->flags == TV_NFLAGS_SELECTED) {
		lw->selected_depth--;
	}

	return NSERROR_OK;
}


/**
 * Treewalk node walk forward callback for launching nodes.
 *
 * \param n current node
 * \param ctx node launch context
 * \param skip_children flag to allow children to be skipped
 * \param end flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror
treeview_node_launch_walk_fwd_cb(treeview_node *n,
				 void *ctx,
				 bool *skip_children,
				 bool *end)
{
	struct treeview_launch_walk_data *lw = ctx;
	nserror ret = NSERROR_OK;

	if (n->type == TREE_NODE_FOLDER && n->flags & TV_NFLAGS_SELECTED) {
		lw->selected_depth++;

	} else if (n->type == TREE_NODE_ENTRY &&
		   (n->flags & TV_NFLAGS_SELECTED ||
		    lw->selected_depth > 0)) {
		struct treeview_node_msg msg;
		msg.msg = TREE_MSG_NODE_LAUNCH;
		msg.data.node_launch.mouse = BROWSER_MOUSE_HOVER;
		ret = lw->tree->callbacks->entry(msg, n->client_data);
	}

	return ret;
}


/**
 * Launch a selection.
 *
 * \note Selected entries are launched. Entries that are descendants
 *        of selected folders are also launched.
 *
 * \param tree Treeview object to launch selected nodes in
 * \return NSERROR_OK on success, appropriate error otherwise
 */
static nserror treeview_launch_selection(treeview *tree)
{
	struct treeview_launch_walk_data lw;

	assert(tree != NULL);
	assert(tree->root != NULL);

	lw.selected_depth = 0;
	lw.tree = tree;

	return treeview_walk_internal(tree->root, true,
				      treeview_node_launch_walk_bwd_cb,
				      treeview_node_launch_walk_fwd_cb, &lw);
}


/* Exported interface, documented in treeview.h */
nserror
treeview_get_relation(treeview *tree,
		      treeview_node **relation,
		      enum treeview_relationship *rel,
		      bool at_y,
		      int y)
{
	treeview_node *n;

	assert(tree != NULL);

	if (at_y) {
		n = treeview_y_node(tree, y);

	} else {
		n = treeview_get_first_selected(tree);
	}

	if (n != NULL && n->parent != NULL) {
		if (n == n->parent->children) {
			/* First child */
			*relation = n->parent;
			*rel = TREE_REL_FIRST_CHILD;
		} else {
			/* Not first child */
			*relation = n->prev_sib;
			*rel = TREE_REL_NEXT_SIBLING;
		}
	} else {
		if (tree->root->children == NULL) {
			/* First child of root */
			*relation = tree->root;
			*rel = TREE_REL_FIRST_CHILD;
		} else {
			/* Last child of root */
			n = tree->root->children;
			while (n->next_sib != NULL)
				n = n->next_sib;
			*relation = n;
			*rel = TREE_REL_NEXT_SIBLING;
		}
	}

	return NSERROR_OK;
}


/**
 * context for treeview keyboard action
 */
struct treeview_nav_state {
	treeview *tree;
	treeview_node *prev;
	treeview_node *curr;
	treeview_node *next;
	treeview_node *last;
	int n_selected;
	int prev_n_selected;
};


/**
 * Treewalk node callback for handling mouse action.
 *
 * \param node current node
 * \param ctx node context
 * \param skip_children flag to allow children to be skipped
 * \param end flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror
treeview_node_nav_cb(treeview_node *node,
		     void *ctx,
		     bool *skip_children,
		     bool *end)
{
	struct treeview_nav_state *ns = ctx;

	if (node == ns->tree->root)
		return NSERROR_OK;

	if (node->flags & TV_NFLAGS_SELECTED) {
		ns->n_selected++;
		if (ns->curr == NULL) {
			ns->curr = node;
		}

	} else {
		if (ns->n_selected == 0) {
			ns->prev = node;

		} else if (ns->prev_n_selected < ns->n_selected) {
			ns->next = node;
			ns->prev_n_selected = ns->n_selected;
		}
	}
	ns->last = node;

	return NSERROR_OK;
}


/**
 * Handle keyboard navigation.
 *
 * \note Selected entries are launched.
 *       Entries that are descendants of selected folders are also launched.
 *
 * \param tree Treeview object to launch selected nodes in
 * \param key The ucs4 character codepoint
 * \param rect Updated to redraw rectangle
 * \return true if treeview needs redraw, false otherwise
 */
static bool
treeview_keyboard_navigation(treeview *tree, uint32_t key, struct rect *rect)
{
	struct treeview_nav_state ns = {
		.tree = tree,
		.prev = NULL,
		.curr = NULL,
		.next = NULL,
		.last = NULL,
		.n_selected = 0,
		.prev_n_selected = 0
	};
	int h = tree->root->height;
	bool redraw = false;

	/* Fill out the nav. state struct, by examining the current selection
	 * state */
	treeview_walk_internal(tree->root, false, NULL,
			       treeview_node_nav_cb, &ns);
	if (ns.next == NULL)
		ns.next = tree->root->children;
	if (ns.prev == NULL)
		ns.prev = ns.last;

	/* Clear any existing selection */
	redraw = treeview_clear_selection(tree, rect);

	switch (key) {
	case NS_KEY_LEFT:
		if (ns.curr != NULL &&
		    ns.curr->parent != NULL &&
		    ns.curr->parent->type != TREE_NODE_ROOT) {
			/* Step to parent */
			ns.curr->parent->flags |= TV_NFLAGS_SELECTED;

		} else if (ns.curr != NULL && tree->root->children != NULL) {
			/* Select first node in tree */
			tree->root->children->flags |= TV_NFLAGS_SELECTED;
		}
		break;

	case NS_KEY_RIGHT:
		if (ns.curr != NULL) {
			if (!(ns.curr->flags & TV_NFLAGS_EXPANDED)) {
				/* Toggle node to expanded */
				treeview_node_expand_internal(tree, ns.curr);
				if (ns.curr->children != NULL) {
					/* Step to first child */
					ns.curr->children->flags |=
						TV_NFLAGS_SELECTED;
				} else {
					/* Retain current node selection */
					ns.curr->flags |= TV_NFLAGS_SELECTED;
				}
			} else {
				/* Toggle node to contracted */
				treeview_node_contract_internal(tree, ns.curr);
				/* Retain current node selection */
				ns.curr->flags |= TV_NFLAGS_SELECTED;
			}

		} else if (ns.curr != NULL) {
			/* Retain current node selection */
			ns.curr->flags |= TV_NFLAGS_SELECTED;
		}
		break;

	case NS_KEY_UP:
		if (ns.prev != NULL) {
			/* Step to previous node */
			ns.prev->flags |= TV_NFLAGS_SELECTED;
		}
		break;

	case NS_KEY_DOWN:
		if (ns.next != NULL) {
			/* Step to next node */
			ns.next->flags |= TV_NFLAGS_SELECTED;
		}
		break;

	default:
		break;
	}

	/* TODO: Deal with redraw area properly */
	rect->x0 = 0;
	rect->y0 = 0;
	rect->x1 = REDRAW_MAX;
	if (tree->root->height > h)
		rect->y1 = tree->root->height;
	else
		rect->y1 = h;
	redraw = true;

	return redraw;
}


/* Exported interface, documented in treeview.h */
bool treeview_keypress(treeview *tree, uint32_t key)
{
	struct rect r;	/**< Redraw rectangle */
	bool redraw = false;

	assert(tree != NULL);

	/* Pass to any textarea, if editing in progress */
	if (tree->edit.textarea != NULL) {
		switch (key) {
		case NS_KEY_ESCAPE:
			treeview_edit_cancel(tree, true);
			return true;
		case NS_KEY_NL:
		case NS_KEY_CR:
			treeview_edit_done(tree);
			return true;
		default:
			return textarea_keypress(tree->edit.textarea, key);
		}
	} else if (tree->search.active == true) {
		switch (key) {
		case NS_KEY_ESCAPE:
			textarea_set_text(tree->search.textarea, "");
			textarea_set_caret(tree->search.textarea, 0);
			r.x0 = tree_g.window_padding + tree_g.icon_size;
			r.x1 = 600;
			r.y0 = 0;
			r.y1 = tree_g.line_height;
			cw_invalidate_area(tree, &r);
			return true;
		case NS_KEY_NL:
		case NS_KEY_CR:
			return true;
		default:
			return textarea_keypress(tree->search.textarea, key);
		}
	}

	/* Keypress to be handled by treeview */
	switch (key) {
	case NS_KEY_SELECT_ALL:
		redraw = treeview_select_all(tree, &r);
		break;
	case NS_KEY_COPY_SELECTION:
		treeview_copy_selection(tree);
		break;
	case NS_KEY_DELETE_LEFT:
	case NS_KEY_DELETE_RIGHT:
		redraw = treeview_delete_selection(tree, &r);

		if (tree->flags & TREEVIEW_DEL_EMPTY_DIRS) {
			int h = tree->root->height;
			/* Delete any empty nodes */
			treeview_delete_empty_nodes(tree, false);

			/* Inform front end of change in dimensions */
			if (tree->root->height != h) {
				r.y0 = 0;
				treeview__cw_update_size(tree, -1,
							 tree->root->height);
			}
		}
		break;
	case NS_KEY_CR:
	case NS_KEY_NL:
		treeview_launch_selection(tree);
		break;
	case NS_KEY_ESCAPE:
	case NS_KEY_CLEAR_SELECTION:
		redraw = treeview_clear_selection(tree, &r);
		break;
	case NS_KEY_LEFT:
	case NS_KEY_RIGHT:
	case NS_KEY_UP:
	case NS_KEY_DOWN:
		redraw = treeview_keyboard_navigation(tree, key, &r);
		break;
	default:
		return false;
	}

	if (redraw) {
		cw_invalidate_area(tree, &r);
	}

	return true;
}


/**
 * Set the drag&drop drop indicator
 *
 * \param tree		Treeview object to set node indicator in
 * \param need_redraw	True iff we already have a redraw region
 * \param target	The treeview node with mouse pointer over it
 * \param node_height	The height of node
 * \param node_y	The Y coord of the top of target node
 * \param mouse_y	Y coord of mouse position
 * \param rect		Redraw rectangle (if redraw required)
 * \return true iff redraw required
 */
static bool
treeview_set_move_indicator(treeview *tree,
			    bool need_redraw,
			    treeview_node *target,
			    int node_height,
			    int node_y,
			    int mouse_y,
			    struct rect *rect)
{
	treeview_node *orig = target;
	enum treeview_target_pos target_pos;
	int mouse_pos = mouse_y - node_y;
	int x;

	assert(tree != NULL);
	assert(tree->root != NULL);
	assert(tree->root->children != NULL);
	assert(target != NULL);

	if (target->flags & TV_NFLAGS_SELECTED) {
		/* Find top selected ancestor */
		while (target->parent &&
		       target->parent->flags & TV_NFLAGS_SELECTED) {
			target = target->parent;
		}

		/* Find top adjacent selected sibling */
		while (target->prev_sib &&
		       target->prev_sib->flags & TV_NFLAGS_SELECTED) {
			target = target->prev_sib;
		}
		target_pos = TV_TARGET_ABOVE;

	} else switch (target->type) {
		case TREE_NODE_FOLDER:
			if (mouse_pos <= node_height / 4) {
				target_pos = TV_TARGET_ABOVE;
			} else if (mouse_pos <= (3 * node_height) / 4 ||
				   target->flags & TV_NFLAGS_EXPANDED) {
				target_pos = TV_TARGET_INSIDE;
			} else {
				target_pos = TV_TARGET_BELOW;
			}
			break;

		case TREE_NODE_ENTRY:
			if (mouse_pos <= node_height / 2) {
				target_pos = TV_TARGET_ABOVE;
			} else {
				target_pos = TV_TARGET_BELOW;
			}
			break;

		default:
			assert(target->type != TREE_NODE_ROOT);
			return false;
		}

	if (target_pos == tree->move.target_pos &&
	    target == tree->move.target) {
		/* No change */
		return need_redraw;
	}

	if (tree->move.target_pos != TV_TARGET_NONE) {
		/* Need to clear old indicator position */
		if (need_redraw) {
			if (rect->x0 > tree->move.target_area.x0)
				rect->x0 = tree->move.target_area.x0;
			if (tree->move.target_area.x1 > rect->x1)
				rect->x1 = tree->move.target_area.x1;
			if (rect->y0 > tree->move.target_area.y0)
				rect->y0 = tree->move.target_area.y0;
			if (tree->move.target_area.y1 > rect->y1)
				rect->y1 = tree->move.target_area.y1;
		} else {
			*rect = tree->move.target_area;
			need_redraw = true;
		}
	}

	/* Offset for ABOVE / BELOW */
	if (target_pos == TV_TARGET_ABOVE) {
		if (target != orig) {
			node_y = treeview_node_y(tree, target);
		}
		node_y -= (tree_g.line_height + 1) / 2;
	} else if (target_pos == TV_TARGET_BELOW) {
		node_y += node_height - (tree_g.line_height + 1) / 2;
	}

	/* Oftsets are all relative to centred (INSIDE) */
	node_y += (tree_g.line_height -
		   treeview_res[TREE_RES_ARROW].height + 1) / 2;

	x = target->inset + tree_g.move_offset;

	/* Update target details */
	tree->move.target = target;
	tree->move.target_pos = target_pos;
	tree->move.target_area.x0 = x;
	tree->move.target_area.y0 = node_y;
	tree->move.target_area.x1 = tree_g.icon_size + x;
	tree->move.target_area.y1 = tree_g.icon_size + node_y;

	if (target_pos != TV_TARGET_NONE) {
		/* Need to draw new indicator position */
		if (need_redraw) {
			if (rect->x0 > tree->move.target_area.x0)
				rect->x0 = tree->move.target_area.x0;
			if (tree->move.target_area.x1 > rect->x1)
				rect->x1 = tree->move.target_area.x1;
			if (rect->y0 > tree->move.target_area.y0)
				rect->y0 = tree->move.target_area.y0;
			if (tree->move.target_area.y1 > rect->y1)
				rect->y1 = tree->move.target_area.y1;
		} else {
			*rect = tree->move.target_area;
			need_redraw = true;
		}
	}

	return need_redraw;
}


/**
 * Callback for textarea_create, in desktop/treeview.h
 *
 * \param data treeview context
 * \param msg textarea message
 */
static void treeview_textarea_callback(void *data, struct textarea_msg *msg)
{
	treeview *tree = data;
	struct rect *r;

	switch (msg->type) {
	case TEXTAREA_MSG_DRAG_REPORT:
		if (msg->data.drag == TEXTAREA_DRAG_NONE) {
			/* Textarea drag finished */
			tree->drag.type = TV_DRAG_NONE;
		} else {
			/* Textarea drag started */
			tree->drag.type = TV_DRAG_TEXTAREA;
		}
		treeview__cw_drag_status(tree, tree->drag.type);
		break;

	case TEXTAREA_MSG_REDRAW_REQUEST:
		r = &msg->data.redraw;
		r->x0 += tree->edit.x;
		r->y0 += tree->edit.y;
		r->x1 += tree->edit.x;
		r->y1 += tree->edit.y;

		/* Redraw the textarea */
		cw_invalidate_area(tree, r);
		break;

	default:
		break;
	}
}


/**
 * Start edit of node field, at given y-coord, if editable
 *
 * \param tree Treeview object to consider editing in
 * \param n The treeview node to try editing
 * \param node_y The Y coord of the top of n
 * \param mouse_x X coord of mouse position
 * \param mouse_y Y coord of mouse position
 * \param rect Redraw rectangle (if redraw required)
 * \return true iff redraw required
 */
static bool
treeview_edit_node_at_point(treeview *tree,
			    treeview_node *n,
			    int node_y,
			    int mouse_x,
			    int mouse_y,
			    struct rect *rect)
{
	struct treeview_text *field_data = NULL;
	struct treeview_field *ef, *field_desc = NULL;
	int pos = node_y + tree_g.line_height;
	int field_y = node_y;
	int field_x;
	int width, height;
	bool success;

	/* If the main field is editable, make field_data point to it */
	if (n->type == TREE_NODE_ENTRY)
		ef = &(tree->fields[0]);
	else
		ef = &(tree->fields[tree->n_fields]);
	if (ef->flags & TREE_FLAG_ALLOW_EDIT) {
		field_data = &n->text;
		field_desc = ef;
		field_y = node_y;
	}

	/* Check for editable entry fields */
	if (n->type == TREE_NODE_ENTRY && n->height != tree_g.line_height) {
		struct treeview_node_entry *e = (struct treeview_node_entry *)n;
		int i;

		for (i = 0; i < tree->n_fields - 1; i++) {
			if (mouse_y <= pos)
				continue;

			ef = &(tree->fields[i + 1]);
			pos += tree_g.line_height;
			if (mouse_y <= pos && (ef->flags &
					       TREE_FLAG_ALLOW_EDIT)) {
				field_data = &e->fields[i].value;
				field_desc = ef;
				field_y = pos - tree_g.line_height;
			}
		}
	}

	if (field_data == NULL || field_desc == NULL) {
		/* No editable field */
		return false;
	}

	/* Get window width/height */
	treeview__cw_get_window_dimensions(tree, &width, &height);

	/* Calculate textarea width/height */
	field_x = n->inset + tree_g.step_width + tree_g.icon_step - 3;
	width -= field_x;
	height = tree_g.line_height;

	/* Create text area */
	tree->edit.textarea = treeview__create_textarea(tree, width, height,
			0x000000, 0xffffff, 0x000000, plot_style_odd.text,
			treeview_textarea_callback);
	if (tree->edit.textarea == NULL) {
		return false;
	}

	success = textarea_set_text(tree->edit.textarea, field_data->data);
	if (!success) {
		textarea_destroy(tree->edit.textarea);
		return false;
	}

	tree->edit.node = n;
	tree->edit.field = field_desc->field;

	/* Position the caret */
	mouse_x -= field_x;
	if (mouse_x < 0)
		mouse_x = 0;
	else if (mouse_x >= width)
		mouse_x = width - 1;

	textarea_mouse_action(tree->edit.textarea,
			      BROWSER_MOUSE_PRESS_1 | BROWSER_MOUSE_CLICK_1,
			      mouse_x, tree_g.line_height / 2);

	/* Position the textarea */
	tree->edit.x = field_x;
	tree->edit.y = field_y;
	tree->edit.w = width;
	tree->edit.h = height;

	/* Setup redraw rectangle */
	if (rect->x0 > field_x)
		rect->x0 = field_x;
	if (rect->y0 > field_y)
		rect->y0 = field_y;
	if (rect->x1 < field_x + width)
		rect->x1 = field_x + width;
	if (rect->y1 < field_y + height)
		rect->y1 = field_y + height;

	return true;
}


/* Exported interface, documented in treeview.h */
void treeview_edit_selection(treeview *tree)
{
	struct rect rect;
	treeview_node *n;
	bool redraw;
	int y;

	assert(tree != NULL);
	assert(tree->root != NULL);

	/* Get first selected node */
	n = treeview_get_first_selected(tree);

	if (n == NULL)
		return;

	/* Get node's y-position */
	y = treeview_node_y(tree, n);

	/* Edit node at y */
	redraw = treeview_edit_node_at_point(tree, n, y,
					     0, y + tree_g.line_height / 2, &rect);

	if (redraw == false)
		return;

	/* Redraw */
	rect.x0 = 0;
	rect.y0 = y;
	rect.x1 = REDRAW_MAX;
	rect.y1 = y + tree_g.line_height;
	cw_invalidate_area(tree, &rect);
}


/**
 * context for treeview mouse handling
 */
struct treeview_mouse_action {
	treeview *tree;
	browser_mouse_state mouse;
	int x;
	int y;
	int current_y;	/* Y coordinate value of top of current node */
};


/**
 * Treewalk node callback for handling mouse action.
 *
 * \param node current node
 * \param ctx node context
 * \param skip_children flag to allow children to be skipped
 * \param end flag to allow iteration to be finished early.
 * \return NSERROR_OK on success else error code.
 */
static nserror
treeview_node_mouse_action_cb(treeview_node *node,
			      void *ctx,
			      bool *skip_children,
			      bool *end)
{
	struct treeview_mouse_action *ma = ctx;
	struct rect r;
	bool redraw = false;
	bool click;
	int height;
	enum {
		TV_NODE_ACTION_NONE		= 0,
		TV_NODE_ACTION_SELECTION	= (1 << 0)
	} action = TV_NODE_ACTION_NONE;
	enum treeview_node_part part = TV_NODE_PART_NONE;
	nserror err;

	r.x0 = 0;
	r.x1 = REDRAW_MAX;

	height = (node->type == TREE_NODE_ENTRY) ? node->height :
		tree_g.line_height;

	/* Skip line if we've not reached mouse y */
	if (ma->y > ma->current_y + height) {
		ma->current_y += height;
		return NSERROR_OK; /* Don't want to abort tree walk */
	}

	/* Find where the mouse is */
	if (ma->y <= ma->current_y + tree_g.line_height) {
		if (ma->x >= node->inset - 1 &&
		    ma->x < node->inset + tree_g.step_width) {
			/* Over expansion toggle */
			part = TV_NODE_PART_TOGGLE;

		} else if (ma->x >= node->inset + tree_g.step_width &&
			   ma->x < node->inset + tree_g.step_width +
			   tree_g.icon_step + node->text.width) {
			/* On node */
			part = TV_NODE_PART_ON_NODE;
		}
	} else if (node->type == TREE_NODE_ENTRY &&
		   height > tree_g.line_height) {
		/* Expanded entries */
		int x = node->inset + tree_g.step_width + tree_g.icon_step;
		int y = ma->current_y + tree_g.line_height;
		int i;
		struct treeview_node_entry *entry =
			(struct treeview_node_entry *)node;
		for (i = 0; i < ma->tree->n_fields - 1; i++) {
			struct treeview_field *ef = &(ma->tree->fields[i + 1]);

			if (ma->y > y + tree_g.line_height) {
				y += tree_g.line_height;
				continue;
			}

			if (ef->flags & TREE_FLAG_SHOW_NAME) {
				int max_width = ma->tree->field_width;

				if (ma->x >= x + max_width - ef->value.width -
				    tree_g.step_width &&
				    ma->x < x + max_width -
				    tree_g.step_width) {
					/* On a field name */
					part = TV_NODE_PART_ON_NODE;

				} else if (ma->x >= x + max_width &&
					   ma->x < x + max_width +
					   entry->fields[i].value.width) {
					/* On a field value */
					part = TV_NODE_PART_ON_NODE;
				}
			} else {
				if (ma->x >= x && ma->x < x +
				    entry->fields[i].value.width) {
					/* On a field value */
					part = TV_NODE_PART_ON_NODE;
				}
			}

			break;
		}
	}

	/* Record what position / part a drag started on */
	if (ma->mouse & (BROWSER_MOUSE_PRESS_1 | BROWSER_MOUSE_PRESS_2) &&
	    ma->tree->drag.type == TV_DRAG_NONE) {
		ma->tree->drag.selected = node->flags & TV_NFLAGS_SELECTED;
		ma->tree->drag.start_node = node;
		ma->tree->drag.part = part;
		ma->tree->drag.start.x = ma->x;
		ma->tree->drag.start.y = ma->y;
		ma->tree->drag.start.node_y = ma->current_y;
		ma->tree->drag.start.node_h = height;

		ma->tree->drag.prev.x = ma->x;
		ma->tree->drag.prev.y = ma->y;
		ma->tree->drag.prev.node_y = ma->current_y;
		ma->tree->drag.prev.node_h = height;
	}

	/* Handle drag start */
	if (ma->tree->drag.type == TV_DRAG_NONE) {
		if (ma->mouse & BROWSER_MOUSE_DRAG_1 &&
		    ma->tree->drag.selected == false &&
		    ma->tree->drag.part == TV_NODE_PART_NONE) {
			ma->tree->drag.type = TV_DRAG_SELECTION;
			treeview__cw_drag_status(ma->tree,
						 CORE_WINDOW_DRAG_SELECTION);

		} else if (!(ma->tree->flags & TREEVIEW_NO_MOVES) &&
			   ma->mouse & BROWSER_MOUSE_DRAG_1 &&
			   (ma->tree->drag.selected == true ||
			    ma->tree->drag.part == TV_NODE_PART_ON_NODE)) {
			ma->tree->drag.type = TV_DRAG_MOVE;
			treeview__cw_drag_status(ma->tree,
						 CORE_WINDOW_DRAG_MOVE);
			redraw |= treeview_propagate_selection(ma->tree, &r);

		} else if (ma->mouse & BROWSER_MOUSE_DRAG_2) {
			ma->tree->drag.type = TV_DRAG_SELECTION;
			treeview__cw_drag_status(ma->tree,
						 CORE_WINDOW_DRAG_SELECTION);
		}

		if (ma->tree->drag.start_node != NULL &&
		    ma->tree->drag.type == TV_DRAG_SELECTION) {
			ma->tree->drag.start_node->flags ^= TV_NFLAGS_SELECTED;
		}
	}

	/* Handle active drags */
	switch (ma->tree->drag.type) {
	case TV_DRAG_SELECTION:
	{
		int curr_y1 = ma->current_y + height;
		int prev_y1 = ma->tree->drag.prev.node_y +
			ma->tree->drag.prev.node_h;

		r.y0 = (ma->current_y < ma->tree->drag.prev.node_y) ?
			ma->current_y : ma->tree->drag.prev.node_y;
		r.y1 = (curr_y1 > prev_y1) ? curr_y1 : prev_y1;

		redraw = true;

		ma->tree->drag.prev.x = ma->x;
		ma->tree->drag.prev.y = ma->y;
		ma->tree->drag.prev.node_y = ma->current_y;
		ma->tree->drag.prev.node_h = height;
	}
	break;

	case TV_DRAG_MOVE:
		redraw |= treeview_set_move_indicator(ma->tree, redraw,
						      node, height,
						      ma->current_y, ma->y, &r);
		break;

	default:
		break;
	}

	click = ma->mouse & (BROWSER_MOUSE_CLICK_1 | BROWSER_MOUSE_CLICK_2);

	if (((node->type == TREE_NODE_FOLDER) &&
	     (ma->mouse & BROWSER_MOUSE_DOUBLE_CLICK) && click) ||
	    (part == TV_NODE_PART_TOGGLE && click)) {
		int h = ma->tree->root->height;

		/* Clear any existing selection */
		redraw |= treeview_clear_selection(ma->tree, &r);

		/* Toggle node expansion */
		if (node->flags & TV_NFLAGS_EXPANDED) {
			err = treeview_node_contract_internal(ma->tree, node);
		} else {
			err = treeview_node_expand_internal(ma->tree, node);
		}
		if (err != NSERROR_OK) {
			return err;
		}

		/* Set up redraw */
		if (!redraw || r.y0 > ma->current_y)
			r.y0 = ma->current_y;
		r.y1 = h > ma->tree->root->height ? h : ma->tree->root->height;
		redraw = true;

	} else if ((node->type == TREE_NODE_ENTRY) &&
		   (ma->mouse & BROWSER_MOUSE_DOUBLE_CLICK) && click) {
		struct treeview_node_msg msg;
		msg.msg = TREE_MSG_NODE_LAUNCH;
		msg.data.node_launch.mouse = ma->mouse;

		/* Clear any existing selection */
		redraw |= treeview_clear_selection(ma->tree, &r);

		/* Tell client an entry was launched */
		ma->tree->callbacks->entry(msg, node->client_data);

	} else if (ma->mouse & BROWSER_MOUSE_PRESS_2 ||
		   (ma->mouse & BROWSER_MOUSE_PRESS_1 &&
		    ma->mouse & BROWSER_MOUSE_MOD_2)) {
		/* Toggle selection of node */
		action |= TV_NODE_ACTION_SELECTION;

	} else if (ma->mouse & BROWSER_MOUSE_CLICK_1 &&
		   ma->mouse &
		   (BROWSER_MOUSE_MOD_1 | BROWSER_MOUSE_MOD_3) &&
		   part != TV_NODE_PART_TOGGLE) {

		/* Clear any existing selection */
		redraw |= treeview_clear_selection(ma->tree, &r);

		/* Edit node */
		redraw |= treeview_edit_node_at_point(ma->tree, node,
						      ma->current_y, ma->x,
						      ma->y, &r);

	} else if (ma->mouse & BROWSER_MOUSE_PRESS_1 &&
		   !(ma->mouse &
		     (BROWSER_MOUSE_MOD_1 | BROWSER_MOUSE_MOD_3)) &&
		   !(node->flags & TV_NFLAGS_SELECTED) &&
		   part != TV_NODE_PART_TOGGLE) {
		/* Clear any existing selection */
		redraw |= treeview_clear_selection(ma->tree, &r);

		/* Select node */
		action |= TV_NODE_ACTION_SELECTION;

	}

	if (action & TV_NODE_ACTION_SELECTION) {
		/* Handle change in selection */
		node->flags ^= TV_NFLAGS_SELECTED;

		/* Redraw */
		if (!redraw) {
			r.y0 = ma->current_y;
			r.y1 = ma->current_y + height;
			redraw = true;
		} else {
			if (r.y0 > ma->current_y) {
				r.y0 = ma->current_y;
			}
			if (r.y1 < ma->current_y + height) {
				r.y1 = ma->current_y + height;
			}
		}
	}

	if (redraw) {
		cw_invalidate_area(ma->tree, &r);
	}

	*end = true; /* Reached line with click; stop walking tree */
	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
void
treeview_mouse_action(treeview *tree, browser_mouse_state mouse, int x, int y)
{
	struct rect r;
	bool redraw = false;
	int search_height = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	assert(tree != NULL);
	assert(tree->root != NULL);

	/* Handle mouse drag captured by textarea */
	if (tree->drag.type == TV_DRAG_TEXTAREA) {
		textarea_mouse_action(tree->edit.textarea, mouse,
				      x - tree->edit.x, y - tree->edit.y);
		return;
	} else if (tree->drag.type == TV_DRAG_SEARCH || y < search_height) {
		if (tree->search.active == false) {
			tree->search.active = true;
			if (treeview_clear_selection(tree, &r)) {
				cw_invalidate_area(tree, &r);
			}
		}
		textarea_mouse_action(tree->search.textarea, mouse,
				x - tree_g.window_padding - tree_g.icon_size,
				y);
		return;
	} else if (mouse & (BROWSER_MOUSE_PRESS_1 | BROWSER_MOUSE_PRESS_2) &&
			tree->search.active == true) {

		tree->search.active = false;
		textarea_set_caret(tree->search.textarea, -1);
		return;
	}

	/* Handle textarea related mouse action */
	if (tree->edit.textarea != NULL) {
		int ta_x = x - tree->edit.x;
		int ta_y = y - tree->edit.y;

		if (ta_x > 0 && ta_x < tree->edit.w &&
		    ta_y > 0 && ta_y < tree->edit.h) {
			/* Inside textarea */
			textarea_mouse_action(tree->edit.textarea, mouse,
					      ta_x, ta_y);
			return;

		} else if (mouse != BROWSER_MOUSE_HOVER) {
			/* Action outside textarea */
			treeview_edit_cancel(tree, true);
		}
	}

	/* Handle drag ends */
	if (mouse == BROWSER_MOUSE_HOVER) {
		switch (tree->drag.type) {
		case TV_DRAG_SELECTION:
			treeview_commit_selection_drag(tree);
			tree->drag.type = TV_DRAG_NONE;
			tree->drag.start_node = NULL;

			treeview__cw_drag_status(tree, CORE_WINDOW_DRAG_NONE);
			return;
		case TV_DRAG_MOVE:
			treeview_move_selection(tree, &r);
			tree->drag.type = TV_DRAG_NONE;
			tree->drag.start_node = NULL;

			tree->move.target = NULL;
			tree->move.target_pos = TV_TARGET_NONE;

			treeview__cw_drag_status(tree, CORE_WINDOW_DRAG_NONE);
			cw_invalidate_area(tree, &r);
			return;
		default:
			/* No drag to end */
			break;
		}
	}

	if (y > tree->root->height + search_height) {
		/* Below tree */

		r.x0 = 0;
		r.x1 = REDRAW_MAX;

		/* Record what position / part a drag started on */
		if (mouse & (BROWSER_MOUSE_PRESS_1 | BROWSER_MOUSE_PRESS_2) &&
		    tree->drag.type == TV_DRAG_NONE) {
			tree->drag.selected = false;
			tree->drag.start_node = NULL;
			tree->drag.part = TV_NODE_PART_NONE;
			tree->drag.start.x = x;
			tree->drag.start.y = y;
			tree->drag.start.node_y = tree->root->height;
			tree->drag.start.node_h = 0;

			tree->drag.prev.x = x;
			tree->drag.prev.y = y;
			tree->drag.prev.node_y = tree->root->height;
			tree->drag.prev.node_h = 0;
		}

		/* Handle drag start */
		if (tree->drag.type == TV_DRAG_NONE) {
			if (mouse & BROWSER_MOUSE_DRAG_1 &&
			    tree->drag.selected == false &&
			    tree->drag.part == TV_NODE_PART_NONE) {
				tree->drag.type = TV_DRAG_SELECTION;
				treeview__cw_drag_status(tree,
						CORE_WINDOW_DRAG_SELECTION);
			} else if (mouse & BROWSER_MOUSE_DRAG_2) {
				tree->drag.type = TV_DRAG_SELECTION;
				treeview__cw_drag_status(tree,
						CORE_WINDOW_DRAG_SELECTION);
			}

			if (tree->drag.start_node != NULL &&
			    tree->drag.type == TV_DRAG_SELECTION) {
				tree->drag.start_node->flags ^=
					TV_NFLAGS_SELECTED;
			}
		}

		/* Handle selection drags */
		if (tree->drag.type == TV_DRAG_SELECTION) {
			int curr_y1 = tree->root->height;
			int prev_y1 = tree->drag.prev.node_y +
				tree->drag.prev.node_h;

			r.y0 = tree->drag.prev.node_y;
			r.y1 = (curr_y1 > prev_y1) ? curr_y1 : prev_y1;

			redraw = true;

			tree->drag.prev.x = x;
			tree->drag.prev.y = y;
			tree->drag.prev.node_y = curr_y1;
			tree->drag.prev.node_h = 0;
		}

		if (mouse & BROWSER_MOUSE_PRESS_1) {
			/* Clear any existing selection */
			redraw |= treeview_clear_selection(tree, &r);
		}

		if (redraw) {
			cw_invalidate_area(tree, &r);
		}

	} else {
		/* On tree */
		struct treeview_mouse_action ma;

		ma.tree = tree;
		ma.mouse = mouse;
		ma.x = x;
		ma.y = y;
		ma.current_y = search_height;

		treeview_walk_internal(tree->root, false, NULL,
				       treeview_node_mouse_action_cb, &ma);
	}
}


/* Exported interface, documented in treeview.h */
int treeview_get_height(treeview *tree)
{
	int search_height = (tree->flags & TREEVIEW_SEARCHABLE) ?
			tree_g.line_height : 0;

	assert(tree != NULL);
	assert(tree->root != NULL);

	treeview__cw_update_size(tree, -1, tree->root->height);

	return tree->root->height + search_height;
}


/**
 * Initialise the plot styles from CSS system colour values.
 *
 * \param font_pt_size font size to use
 * \return NSERROR_OK on success else appropriate error code
 */
static nserror treeview_init_plot_styles(int font_pt_size)
{
	nserror res;

	/* Background colour */
	plot_style_even.bg.stroke_type = PLOT_OP_TYPE_NONE;
	plot_style_even.bg.stroke_width = 0;
	plot_style_even.bg.stroke_colour = 0;
	plot_style_even.bg.fill_type = PLOT_OP_TYPE_SOLID;
	res = ns_system_colour_char("Window", &plot_style_even.bg.fill_colour);
	if (res != NSERROR_OK) {
		return res;
	}

	/* Text colour */
	plot_style_even.text.family = PLOT_FONT_FAMILY_SANS_SERIF;
	plot_style_even.text.size = font_pt_size;
	plot_style_even.text.weight = 400;
	plot_style_even.text.flags = FONTF_NONE;
	res = ns_system_colour_char("WindowText", &plot_style_even.text.foreground);
	if (res != NSERROR_OK) {
		return res;
	}
	res = ns_system_colour_char("Window", &plot_style_even.text.background);
	if (res != NSERROR_OK) {
		return res;
	}

	/* Entry field text colour */
	plot_style_even.itext = plot_style_even.text;
	plot_style_even.itext.foreground = mix_colour(
		plot_style_even.text.foreground,
		plot_style_even.text.background,
		255 * 10 / 16);

	/* Selected background colour */
	plot_style_even.sbg = plot_style_even.bg;
	res = ns_system_colour_char("Highlight", &plot_style_even.sbg.fill_colour);
	if (res != NSERROR_OK) {
		return res;
	}

	/* Selected text colour */
	plot_style_even.stext = plot_style_even.text;
	res = ns_system_colour_char("HighlightText", &plot_style_even.stext.foreground);
	if (res != NSERROR_OK) {
		return res;
	}
	res = ns_system_colour_char("Highlight", &plot_style_even.stext.background);
	if (res != NSERROR_OK) {
		return res;
	}

	/* Selected entry field text colour */
	plot_style_even.sitext = plot_style_even.stext;
	plot_style_even.sitext.foreground = mix_colour(
		plot_style_even.stext.foreground,
		plot_style_even.stext.background,
		255 * 25 / 32);

	/* Odd numbered node styles */
	plot_style_odd.bg = plot_style_even.bg;
	plot_style_odd.bg.fill_colour = mix_colour(
		plot_style_even.bg.fill_colour,
		plot_style_even.text.foreground, 255 * 15 / 16);
	plot_style_odd.text = plot_style_even.text;
	plot_style_odd.text.background = plot_style_odd.bg.fill_colour;
	plot_style_odd.itext = plot_style_odd.text;
	plot_style_odd.itext.foreground = mix_colour(
		plot_style_odd.text.foreground,
		plot_style_odd.text.background, 255 * 10 / 16);

	plot_style_odd.sbg = plot_style_even.sbg;
	plot_style_odd.stext = plot_style_even.stext;
	plot_style_odd.sitext = plot_style_even.sitext;

	return NSERROR_OK;
}


/**
 * Callback for hlcache retrieving resources.
 *
 * \param handle content hlcache handle
 * \param event The event that occurred on the content
 * \param pw treeview resource context
 */
static nserror
treeview_res_cb(struct hlcache_handle *handle,
		const hlcache_event *event,
		void *pw)
{
	struct treeview_resource *r = pw;

	switch (event->type) {
	case CONTENT_MSG_READY:
	case CONTENT_MSG_DONE:
		r->ready = true;
		r->height = content_get_height(handle);
		break;

	default:
		break;
	}

	return NSERROR_OK;
}


/**
 * Fetch content resources used by treeview.
 */
static void treeview_init_resources(void)
{
	int i;

	for (i = 0; i < TREE_RES_LAST; i++) {
		nsurl *url;
		treeview_res[i].ready = false;
		treeview_res[i].height = 0;
		if (nsurl_create(treeview_res[i].url, &url) == NSERROR_OK) {
			hlcache_handle_retrieve(url, 0, NULL, NULL,
						treeview_res_cb,
						&(treeview_res[i]), NULL,
						CONTENT_IMAGE,
						&(treeview_res[i].c));
			nsurl_unref(url);
		}
	}
}


/**
 * Create a right-pointing anti-aliased triangle bitmap
 *
 * \param bg background colour
 * \param fg foreground colour
 * \param size required bitmap size
 */
static struct bitmap *
treeview_generate_triangle_bitmap(colour bg, colour fg, int size)
{
	struct bitmap *b = NULL;
	int x, y;
	unsigned char *rpos;
	unsigned char *pos;
	size_t stride;

	/* Set up required colour graduations.  Ignores screen gamma. */
	colour colour0 = bg;
	colour colour1 = mix_colour(bg, fg, 255 * 3 / 4);
	colour colour2 = blend_colour(bg, fg);
	colour colour3 = mix_colour(bg, fg, 255 * 1 / 4);
	colour colour4 = fg;

	/* Create the bitmap */
	b = guit->bitmap->create(size, size, BITMAP_NEW | BITMAP_OPAQUE);
	if (b == NULL)
		return NULL;

	rpos = guit->bitmap->get_buffer(b);
	stride = guit->bitmap->get_rowstride(b);

	/* Draw the triangle */
	for (y = 0; y < size; y++) {
		pos = rpos;

		if (y < size / 2) {
			/* Top half */
			for (x = 0; x < y * 2; x++) {
				*(pos++) = red_from_colour(colour4);
				*(pos++) = green_from_colour(colour4);
				*(pos++) = blue_from_colour(colour4);
				*(pos++) = 0xff;
			}
			*(pos++) = red_from_colour(colour3);
			*(pos++) = green_from_colour(colour3);
			*(pos++) = blue_from_colour(colour3);
			*(pos++) = 0xff;
			*(pos++) = red_from_colour(colour1);
			*(pos++) = green_from_colour(colour1);
			*(pos++) = blue_from_colour(colour1);
			*(pos++) = 0xff;
			for (x = y * 2 + 2; x < size ; x++) {
				*(pos++) = red_from_colour(colour0);
				*(pos++) = green_from_colour(colour0);
				*(pos++) = blue_from_colour(colour0);
				*(pos++) = 0xff;
			}
		} else if ((y == size / 2) && (size & 0x1)) {
			/* Middle row */
			for (x = 0; x < size - 1; x++) {
				*(pos++) = red_from_colour(colour4);
				*(pos++) = green_from_colour(colour4);
				*(pos++) = blue_from_colour(colour4);
				*(pos++) = 0xff;
			}
			*(pos++) = red_from_colour(colour2);
			*(pos++) = green_from_colour(colour2);
			*(pos++) = blue_from_colour(colour2);
			*(pos++) = 0xff;
		} else {
			/* Bottom half */
			for (x = 0; x < (size - y - 1) * 2; x++) {
				*(pos++) = red_from_colour(colour4);
				*(pos++) = green_from_colour(colour4);
				*(pos++) = blue_from_colour(colour4);
				*(pos++) = 0xff;
			}
			*(pos++) = red_from_colour(colour3);
			*(pos++) = green_from_colour(colour3);
			*(pos++) = blue_from_colour(colour3);
			*(pos++) = 0xff;
			*(pos++) = red_from_colour(colour1);
			*(pos++) = green_from_colour(colour1);
			*(pos++) = blue_from_colour(colour1);
			*(pos++) = 0xff;
			for (x = (size - y) * 2; x < size ; x++) {
				*(pos++) = red_from_colour(colour0);
				*(pos++) = green_from_colour(colour0);
				*(pos++) = blue_from_colour(colour0);
				*(pos++) = 0xff;
			}
		}

		rpos += stride;
	}

	guit->bitmap->modified(b);

	return b;
}


/**
 * Create bitmap copy of another bitmap
 *
 * \param orig bitmap to copy
 * \param size required bitmap size
 */
static struct bitmap *
treeview_generate_copy_bitmap(struct bitmap *orig, int size)
{
	struct bitmap *b = NULL;
	unsigned char *data;
	unsigned char *orig_data;
	size_t stride;

	if (orig == NULL)
		return NULL;

	assert(size == guit->bitmap->get_width(orig));
	assert(size == guit->bitmap->get_height(orig));

	/* Create the bitmap */
	b = guit->bitmap->create(size, size, BITMAP_NEW | BITMAP_OPAQUE);
	if (b == NULL)
		return NULL;

	stride = guit->bitmap->get_rowstride(b);
	assert(stride == guit->bitmap->get_rowstride(orig));

	data = guit->bitmap->get_buffer(b);
	orig_data = guit->bitmap->get_buffer(orig);

	/* Copy the bitmap */
	memcpy(data, orig_data, stride * size);

	guit->bitmap->modified(b);

	/* We've not modified the original image, but we called
	 * bitmap_get_buffer(), so we need to pair that with a
	 * bitmap_modified() call to appease certain front ends. */
	guit->bitmap->modified(orig);

	return b;
}


/**
 * Create bitmap from rotation of another bitmap
 *
 * \param orig bitmap to create rotation of
 * \param size required bitmap size
 */
static struct bitmap *
treeview_generate_rotate_bitmap(struct bitmap *orig, int size)
{
	struct bitmap *b = NULL;
	int x, y;
	unsigned char *rpos;
	unsigned char *pos;
	unsigned char *orig_data;
	unsigned char *orig_pos;
	size_t stride;

	if (orig == NULL)
		return NULL;

	assert(size == guit->bitmap->get_width(orig));
	assert(size == guit->bitmap->get_height(orig));

	/* Create the bitmap */
	b = guit->bitmap->create(size, size, BITMAP_NEW | BITMAP_OPAQUE);
	if (b == NULL)
		return NULL;

	stride = guit->bitmap->get_rowstride(b);
	assert(stride == guit->bitmap->get_rowstride(orig));

	rpos = guit->bitmap->get_buffer(b);
	orig_data = guit->bitmap->get_buffer(orig);

	/* Copy the rotated bitmap */
	for (y = 0; y < size; y++) {
		pos = rpos;

		for (x = 0; x < size; x++) {
			orig_pos = orig_data + x * stride + y * 4;
			*(pos++) = *(orig_pos++);
			*(pos++) = *(orig_pos++);
			*(pos++) = *(orig_pos);
			*(pos++) = 0xff;

		}

		rpos += stride;
	}

	guit->bitmap->modified(b);

	/* We've not modified the original image, but we called
	 * bitmap_get_buffer(), so we need to pair that with a
	 * bitmap_modified() call to appease certain front ends.
	 */
	guit->bitmap->modified(orig);

	return b;
}


/**
 * Measures width of characters used to represent treeview furniture.
 *
 * \return NSERROR_OK on success else error code
 */
static nserror treeview_init_furniture(void)
{
	int size = tree_g.line_height / 2;

	plot_style_odd.furn[TREE_FURN_EXPAND].size = size;
	plot_style_odd.furn[TREE_FURN_EXPAND].bmp =
		treeview_generate_triangle_bitmap(
			plot_style_odd.bg.fill_colour,
			plot_style_odd.itext.foreground, size);
	plot_style_odd.furn[TREE_FURN_EXPAND].sel =
		treeview_generate_triangle_bitmap(
			plot_style_odd.sbg.fill_colour,
			plot_style_odd.sitext.foreground, size);

	plot_style_even.furn[TREE_FURN_EXPAND].size = size;
	plot_style_even.furn[TREE_FURN_EXPAND].bmp =
		treeview_generate_triangle_bitmap(
			plot_style_even.bg.fill_colour,
			plot_style_even.itext.foreground, size);
	plot_style_even.furn[TREE_FURN_EXPAND].sel =
		treeview_generate_copy_bitmap(
			plot_style_odd.furn[TREE_FURN_EXPAND].sel, size);

	plot_style_odd.furn[TREE_FURN_CONTRACT].size = size;
	plot_style_odd.furn[TREE_FURN_CONTRACT].bmp =
		treeview_generate_rotate_bitmap(
			plot_style_odd.furn[TREE_FURN_EXPAND].bmp, size);
	plot_style_odd.furn[TREE_FURN_CONTRACT].sel =
		treeview_generate_rotate_bitmap(
			plot_style_odd.furn[TREE_FURN_EXPAND].sel, size);

	plot_style_even.furn[TREE_FURN_CONTRACT].size = size;
	plot_style_even.furn[TREE_FURN_CONTRACT].bmp =
		treeview_generate_rotate_bitmap(
			plot_style_even.furn[TREE_FURN_EXPAND].bmp, size);
	plot_style_even.furn[TREE_FURN_CONTRACT].sel =
		treeview_generate_rotate_bitmap(
			plot_style_even.furn[TREE_FURN_EXPAND].sel, size);

	if (plot_style_odd.furn[TREE_FURN_EXPAND].bmp == NULL ||
	    plot_style_odd.furn[TREE_FURN_EXPAND].sel == NULL ||
	    plot_style_even.furn[TREE_FURN_EXPAND].bmp == NULL ||
	    plot_style_even.furn[TREE_FURN_EXPAND].sel == NULL ||
	    plot_style_odd.furn[TREE_FURN_CONTRACT].bmp == NULL ||
	    plot_style_odd.furn[TREE_FURN_CONTRACT].sel == NULL ||
	    plot_style_even.furn[TREE_FURN_CONTRACT].bmp == NULL ||
	    plot_style_even.furn[TREE_FURN_CONTRACT].sel == NULL)
		return NSERROR_NOMEM;

	tree_g.furniture_width = size + tree_g.line_height / 4;

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_init(void)
{
	long long font_px_size;
	long long font_pt_size;
	nserror res;

	if (tree_g.initialised > 0) {
		tree_g.initialised++;
		return NSERROR_OK;
	}

	NSLOG(netsurf, INFO, "Initialising treeview module");

	font_pt_size = nsoption_int(treeview_font_size);
	if (font_pt_size <= 0) {
		font_pt_size = 11 * 10;
	}

	font_px_size = (font_pt_size * FIXTOINT(nscss_screen_dpi) /
			10 + 36) / 72;
	tree_g.line_height = (font_px_size * 8 + 3) / 6;

	res = treeview_init_plot_styles(font_pt_size * FONT_SIZE_SCALE / 10);
	if (res != NSERROR_OK) {
		return res;
	}

	treeview_init_resources();

	res = treeview_init_furniture();
	if (res != NSERROR_OK) {
		return res;
	}

	tree_g.step_width = tree_g.furniture_width;
	tree_g.window_padding = 6;
	tree_g.icon_size = 17;
	tree_g.icon_step = 23;
	tree_g.move_offset = 18;

	tree_g.initialised++;

	NSLOG(netsurf, INFO, "Initialised treeview module");

	return NSERROR_OK;
}


/* Exported interface, documented in treeview.h */
nserror treeview_fini(void)
{
	int i;

	if (tree_g.initialised > 1) {
		tree_g.initialised--;
		return NSERROR_OK;

	} else if (tree_g.initialised == 0) {
		NSLOG(netsurf, INFO,
		      "Warning: tried to finalise uninitialised treeview module");
		return NSERROR_OK;
	}

	NSLOG(netsurf, INFO, "Finalising treeview module");

	for (i = 0; i < TREE_RES_LAST; i++) {
		hlcache_handle_release(treeview_res[i].c);
	}

	guit->bitmap->destroy(plot_style_odd.furn[TREE_FURN_EXPAND].bmp);
	guit->bitmap->destroy(plot_style_odd.furn[TREE_FURN_EXPAND].sel);
	guit->bitmap->destroy(plot_style_even.furn[TREE_FURN_EXPAND].bmp);
	guit->bitmap->destroy(plot_style_even.furn[TREE_FURN_EXPAND].sel);
	guit->bitmap->destroy(plot_style_odd.furn[TREE_FURN_CONTRACT].bmp);
	guit->bitmap->destroy(plot_style_odd.furn[TREE_FURN_CONTRACT].sel);
	guit->bitmap->destroy(plot_style_even.furn[TREE_FURN_CONTRACT].bmp);
	guit->bitmap->destroy(plot_style_even.furn[TREE_FURN_CONTRACT].sel);

	tree_g.initialised--;

	NSLOG(netsurf, INFO, "Finalised treeview module");

	return NSERROR_OK;
}