summaryrefslogtreecommitdiff
path: root/desktop/browser_window.c
blob: fcee085996e909f62eed77d2898f5773f71e99e3 (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
/*
 * Copyright 2008 Michael Drake <tlsa@netsurf-browser.org>
 * Copyright 2010 Daniel Silverstone <dsilvers@digital-scurf.org>
 * Copyright 2010 Vincent Sanders <vince@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
 *
 * Browser window creation and manipulation implementation.
 */

#include "utils/config.h"

#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <nsutils/time.h>

#include "utils/corestrings.h"
#include "utils/log.h"
#include "utils/messages.h"
#include "utils/nsurl.h"
#include "utils/utils.h"
#include "utils/utf8.h"
#include "utils/nsoption.h"
#include "netsurf/misc.h"
#include "netsurf/window.h"
#include "netsurf/content.h"
#include "netsurf/plotters.h"
#include "content/content_debug.h"
#include "content/fetch.h"
#include "content/hlcache.h"
#include "content/urldb.h"
#include "css/utils.h"
#include "html/form_internal.h"
#include "html/html.h"
#include "html/box.h"
#include "javascript/js.h"

#include "desktop/browser_history.h"
#include "desktop/browser_private.h"
#include "desktop/download.h"
#include "desktop/frames.h"
#include "desktop/global_history.h"
#include "desktop/hotlist.h"
#include "desktop/knockout.h"
#include "desktop/scrollbar.h"
#include "desktop/selection.h"
#include "desktop/theme.h"
#include "desktop/gui_internal.h"
#include "desktop/textinput.h"

/**
 * smallest scale that can be applied to a browser window
 */
#define SCALE_MINIMUM 0.2

/**
 * largests scale that can be applied to a browser window
 */
#define SCALE_MAXIMUM 10.0

/**
 * maximum frame depth
 */
#define FRAME_DEPTH 8

/* Have to forward declare browser_window_destroy_internal */
static void browser_window_destroy_internal(struct browser_window *bw);

/* Forward declare internal navigation function */
static nserror browser_window__navigate_internal(
	struct browser_window *bw, struct browser_fetch_parameters *params);


/**
 * Close and destroy all child browser window.
 *
 * \param bw browser window
 */
static void browser_window_destroy_children(struct browser_window *bw)
{
	int i;

	if (bw->children) {
		for (i = 0; i < (bw->rows * bw->cols); i++) {
			browser_window_destroy_internal(&bw->children[i]);
		}
		free(bw->children);
		bw->children = NULL;
		bw->rows = 0;
		bw->cols = 0;
	}
	if (bw->iframes) {
		for (i = 0; i < bw->iframe_count; i++) {
			browser_window_destroy_internal(&bw->iframes[i]);
		}
		free(bw->iframes);
		bw->iframes = NULL;
		bw->iframe_count = 0;
	}
}


/**
 * Free the stored fetch parameters
 *
 * \param bw The browser window
 */
static void
browser_window__free_fetch_parameters(struct browser_fetch_parameters *params)
{
	if (params->url != NULL) {
		nsurl_unref(params->url);
		params->url = NULL;
	}
	if (params->referrer != NULL) {
		nsurl_unref(params->referrer);
		params->referrer = NULL;
	}
	if (params->post_urlenc != NULL) {
		free(params->post_urlenc);
		params->post_urlenc = NULL;
	}
	if (params->post_multipart != NULL) {
		fetch_multipart_data_destroy(params->post_multipart);
		params->post_multipart = NULL;
	}
	if (params->parent_charset != NULL) {
		free(params->parent_charset);
		params->parent_charset = NULL;
	}
}


/**
 * Get position of scrollbar widget within browser window.
 *
 * \param bw The browser window
 * \param horizontal Whether to get position of horizontal scrollbar
 * \param x Updated to x-coord of top left of scrollbar widget
 * \param y Updated to y-coord of top left of scrollbar widget
 */
static inline void
browser_window_get_scrollbar_pos(struct browser_window *bw,
				 bool horizontal,
				 int *x, int *y)
{
	if (horizontal) {
		*x = 0;
		*y = bw->height - SCROLLBAR_WIDTH;
	} else {
		*x = bw->width - SCROLLBAR_WIDTH;
		*y = 0;
	}
}


/**
 * Get browser window horizontal scrollbar widget length
 *
 * \param bw The browser window
 * \return the scrollbar's length
 */
static inline int get_horz_scrollbar_len(struct browser_window *bw)
{
	if (bw->scroll_y == NULL) {
		return bw->width;
	}
	return bw->width - SCROLLBAR_WIDTH;
}


/**
 * Get browser window vertical scrollbar widget length
 *
 * \param bw The browser window
 * \return the scrollbar's length
 */
static inline int get_vert_scrollbar_len(struct browser_window *bw)
{
	return bw->height;
}


/**
 * Set or remove a selection.
 *
 * \param bw browser window with selection
 * \param selection true if bw has a selection, false if removing selection
 * \param read_only true iff selection is read only (e.g. can't cut it)
 */
static void
browser_window_set_selection(struct browser_window *bw,
			     bool selection,
			     bool read_only)
{
	struct browser_window *top;

	assert(bw != NULL);

	top = browser_window_get_root(bw);

	assert(top != NULL);

	if (bw != top->selection.bw &&
	    top->selection.bw != NULL &&
	    top->selection.bw->current_content != NULL) {
		/* clear old selection */
		content_clear_selection(top->selection.bw->current_content);
	}

	if (selection) {
		top->selection.bw = bw;
	} else {
		top->selection.bw = NULL;
	}

	top->selection.read_only = read_only;
}


/**
 * Set the scroll position of a browser window.
 *
 * scrolls the viewport to ensure the specified rectangle of the
 *   content is shown.
 *
 * \param bw window to scroll
 * \param rect The rectangle to ensure is shown.
 * \return NSERROR_OK on success or apropriate error code.
 */
static nserror
browser_window_set_scroll(struct browser_window *bw, const struct rect *rect)
{
	if (bw->window != NULL) {
		return guit->window->set_scroll(bw->window, rect);
	}

	if (bw->scroll_x != NULL) {
		scrollbar_set(bw->scroll_x, rect->x0, false);
	}
	if (bw->scroll_y != NULL) {
		scrollbar_set(bw->scroll_y, rect->y0, false);
	}

	return NSERROR_OK;
}


/**
 * Internal helper for getting the positional features
 *
 * \param[in] bw browser window to examine.
 * \param[in] x x-coordinate of point of interest
 * \param[in] y y-coordinate of point of interest
 * \param[out] data Feature structure to update.
 * \return NSERROR_OK or appropriate error code on faliure.
 */
static nserror
browser_window__get_contextual_content(struct browser_window *bw,
				       int x, int y,
				       struct browser_window_features *data)
{
	nserror ret = NSERROR_OK;

	/* Handle (i)frame scroll offset (core-managed browser windows only) */
	x += scrollbar_get_offset(bw->scroll_x);
	y += scrollbar_get_offset(bw->scroll_y);

	if (bw->children) {
		/* Browser window has children, so pass request on to
		 * appropriate child.
		 */
		struct browser_window *bwc;
		int cur_child;
		int children = bw->rows * bw->cols;

		/* Loop through all children of bw */
		for (cur_child = 0; cur_child < children; cur_child++) {
			/* Set current child */
			bwc = &bw->children[cur_child];

			/* Skip this frame if (x, y) coord lies outside */
			if ((x < bwc->x) ||
			    (bwc->x + bwc->width < x) ||
			    (y < bwc->y) ||
			    (bwc->y + bwc->height < y)) {
				continue;
			}

			/* Pass request into this child */
			return browser_window__get_contextual_content(bwc,
					      (x - bwc->x), (y - bwc->y), data);
		}

		/* Coordinate not contained by any frame */

	} else if (bw->current_content != NULL) {
		/* Pass request to content */
		ret = content_get_contextual_content(bw->current_content,
						     x, y, data);
		data->main = bw->current_content;
	}

	return ret;
}


/**
 * slow script handler
 */
static bool slow_script(void *ctx)
{
	static int count = 0;
	NSLOG(netsurf, INFO, "Continuing execution %d", count);
	count++;
	if (count > 1) {
		count = 0;
		return false;
	}
	return true;
}


/**
 * implements the download operation of a window navigate
 */
static nserror
browser_window_download(struct browser_window *bw,
			nsurl *url,
			nsurl *nsref,
			uint32_t fetch_flags,
			bool fetch_is_post,
			llcache_post_data *post)
{
	llcache_handle *l;
	struct browser_window *root;
	nserror error;

	root = browser_window_get_root(bw);
	assert(root != NULL);

	fetch_flags |= LLCACHE_RETRIEVE_FORCE_FETCH;
	fetch_flags |= LLCACHE_RETRIEVE_STREAM_DATA;

	error = llcache_handle_retrieve(url, fetch_flags, nsref,
					fetch_is_post ? post : NULL,
					NULL, NULL, &l);
	if (error == NSERROR_NO_FETCH_HANDLER) {
		/* no internal handler for this type, call out to frontend */
		error = guit->misc->launch_url(url);
	} else if (error != NSERROR_OK) {
		NSLOG(netsurf, INFO, "Failed to fetch download: %d", error);
	} else {
		error = download_context_create(l, root->window);
		if (error != NSERROR_OK) {
			NSLOG(netsurf, INFO,
			      "Failed creating download context: %d", error);
			llcache_handle_abort(l);
			llcache_handle_release(l);
		}
	}

	return error;
}


/**
 * recursively check browser windows for activity
 *
 * \param bw browser window to start checking from.
 */
static bool browser_window_check_throbber(struct browser_window *bw)
{
	int children, index;

	if (bw->throbbing)
		return true;

	if (bw->children) {
		children = bw->rows * bw->cols;
		for (index = 0; index < children; index++) {
			if (browser_window_check_throbber(&bw->children[index]))
				return true;
		}
	}

	if (bw->iframes) {
		for (index = 0; index < bw->iframe_count; index++) {
			if (browser_window_check_throbber(&bw->iframes[index]))
				return true;
		}
	}

	return false;
}


/**
 * Start the busy indicator.
 *
 * \param bw browser window
 */
static nserror browser_window_start_throbber(struct browser_window *bw)
{
	bw->throbbing = true;

	while (bw->parent)
		bw = bw->parent;

	return guit->window->event(bw->window, GW_EVENT_START_THROBBER);
}


/**
 * Stop the busy indicator.
 *
 * \param bw browser window
 */
static nserror browser_window_stop_throbber(struct browser_window *bw)
{
	nserror res = NSERROR_OK;

	bw->throbbing = false;

	while (bw->parent) {
		bw = bw->parent;
	}

	if (!browser_window_check_throbber(bw)) {
		res = guit->window->event(bw->window, GW_EVENT_STOP_THROBBER);
	}
	return res;
}


/**
 * Callback for fetchcache() for browser window favicon fetches.
 *
 * \param c content handle of favicon
 * \param event The event to process
 * \param pw a context containing the browser window
 * \return NSERROR_OK on success else appropriate error code.
 */
static nserror
browser_window_favicon_callback(hlcache_handle *c,
				const hlcache_event *event,
				void *pw)
{
	struct browser_window *bw = pw;

	switch (event->type) {
	case CONTENT_MSG_DONE:
		if (bw->favicon.current != NULL) {
			content_close(bw->favicon.current);
			hlcache_handle_release(bw->favicon.current);
		}

		bw->favicon.current = c;
		bw->favicon.loading = NULL;

		/* content_get_bitmap on the hlcache_handle should give
		 *   the favicon bitmap at this point
		 */
		guit->window->set_icon(bw->window, c);
		break;

	case CONTENT_MSG_ERROR:

		/* clean up after ourselves */
		if (c == bw->favicon.loading) {
			bw->favicon.loading = NULL;
		} else if (c == bw->favicon.current) {
			bw->favicon.current = NULL;
		}

		hlcache_handle_release(c);

		if (bw->favicon.failed == false) {
			nsurl *nsref = NULL;
			nsurl *nsurl;
			nserror error;

			bw->favicon.failed = true;

			error = nsurl_create("resource:favicon.ico", &nsurl);
			if (error != NSERROR_OK) {
				NSLOG(netsurf, INFO,
				      "Unable to create default location url");
			} else {
				hlcache_handle_retrieve(nsurl,
							HLCACHE_RETRIEVE_SNIFF_TYPE,
							nsref, NULL,
							browser_window_favicon_callback,
							bw, NULL, CONTENT_IMAGE,
							&bw->favicon.loading);

				nsurl_unref(nsurl);
			}

		}
		break;

	default:
		break;

	}
	return NSERROR_OK;
}


/**
 * update the favicon associated with the browser window
 *
 * \param c the page content handle.
 * \param bw A top level browser window.
 * \param link A link context or NULL to attempt fallback scanning.
 */
static nserror
browser_window_update_favicon(hlcache_handle *c,
			      struct browser_window *bw,
			      struct content_rfc5988_link *link)
{
	nsurl *nsref = NULL;
	nsurl *nsurl;
	nserror res;

	assert(c != NULL);
	assert(bw !=NULL);

	if (bw->window == NULL) {
		/* Not top-level browser window; not interested */
		return NSERROR_OK;
	}

	/* already fetching the favicon - use that */
	if (bw->favicon.loading != NULL) {
		return NSERROR_OK;
	}

	bw->favicon.failed = false;

	if (link == NULL) {
		/* Look for "icon" */
		link = content_find_rfc5988_link(c, corestring_lwc_icon);
	}

	if (link == NULL) {
		/* Look for "shortcut icon" */
		link = content_find_rfc5988_link(c, corestring_lwc_shortcut_icon);
	}

	if (link == NULL) {
		lwc_string *scheme;
		bool speculative_default = false;
		bool match;

		nsurl = hlcache_handle_get_url(c);

		scheme = nsurl_get_component(nsurl, NSURL_SCHEME);

		/* If the document was fetched over http(s), then speculate
		 * that there's a favicon living at /favicon.ico */
		if ((lwc_string_caseless_isequal(scheme,
						 corestring_lwc_http,
						 &match) == lwc_error_ok &&
		     match) ||
		    (lwc_string_caseless_isequal(scheme,
						 corestring_lwc_https,
						 &match) == lwc_error_ok &&
		     match)) {
			speculative_default = true;
		}

		lwc_string_unref(scheme);

		if (speculative_default) {
			/* no favicon via link, try for the default location */
			res = nsurl_join(nsurl, "/favicon.ico", &nsurl);
		} else {
			bw->favicon.failed = true;
			res = nsurl_create("resource:favicon.ico", &nsurl);
		}
		if (res != NSERROR_OK) {
			NSLOG(netsurf, INFO,
			      "Unable to create default location url");
			return res;
		}
	} else {
		nsurl = nsurl_ref(link->href);
	}

	if (link == NULL) {
		NSLOG(netsurf, INFO,
		      "fetching general favicon from '%s'",
		      nsurl_access(nsurl));
	} else {
		NSLOG(netsurf, INFO,
		      "fetching favicon rel:%s '%s'",
		      lwc_string_data(link->rel),
		      nsurl_access(nsurl));
	}

	res = hlcache_handle_retrieve(nsurl,
				      HLCACHE_RETRIEVE_SNIFF_TYPE,
				      nsref,
				      NULL,
				      browser_window_favicon_callback,
				      bw,
				      NULL,
				      CONTENT_IMAGE,
				      &bw->favicon.loading);

	nsurl_unref(nsurl);

	return res;
}


/**
 * Handle meta http-equiv refresh time elapsing by loading a new page.
 *
 * \param p browser window to refresh with new page
 */
static void browser_window_refresh(void *p)
{
	struct browser_window *bw = p;
	nsurl *url;
	nsurl *refresh;
	hlcache_handle *parent = NULL;
	enum browser_window_nav_flags flags = BW_NAVIGATE_UNVERIFIABLE;

	assert(bw->current_content != NULL &&
	       (content_get_status(bw->current_content) ==
		CONTENT_STATUS_READY ||
		content_get_status(bw->current_content) ==
		CONTENT_STATUS_DONE));

	/* Ignore if the refresh URL has gone
	 * (may happen if a fetch error occurred) */
	refresh = content_get_refresh_url(bw->current_content);
	if (refresh == NULL)
		return;

	/* mark this content as invalid so it gets flushed from the cache */
	content_invalidate_reuse_data(bw->current_content);

	url = hlcache_handle_get_url(bw->current_content);
	if ((url == NULL) || (nsurl_compare(url, refresh, NSURL_COMPLETE))) {
		flags |= BW_NAVIGATE_HISTORY;
	}

	/* Treat an (almost) immediate refresh in a top-level browser window as
	 * if it were an HTTP redirect, and thus make the resulting fetch
	 * verifiable.
	 *
	 * See fetchcache.c for why redirected fetches should be verifiable at
	 * all.
	 */
	if (bw->refresh_interval <= 100 && bw->parent == NULL) {
		flags &= ~BW_NAVIGATE_UNVERIFIABLE;
	} else {
		parent = bw->current_content;
	}

	browser_window_navigate(bw,
				refresh,
				url,
				flags,
				NULL,
				NULL,
				parent);

}


/**
 * Transfer the loading_content to a new download window.
 */
static void
browser_window_convert_to_download(struct browser_window *bw,
				   llcache_handle *stream)
{
	struct browser_window *root = browser_window_get_root(bw);
	nserror error;

	assert(root != NULL);

	error = download_context_create(stream, root->window);
	if (error != NSERROR_OK) {
		llcache_handle_abort(stream);
		llcache_handle_release(stream);
	}

	/* remove content from browser window */
	hlcache_handle_release(bw->loading_content);
	bw->loading_content = NULL;

	browser_window_stop_throbber(bw);
}


/**
 * handle message for content ready on browser window
 */
static nserror browser_window_content_ready(struct browser_window *bw)
{
	int width, height;
	nserror res = NSERROR_OK;

	/* close and release the current window content */
	if (bw->current_content != NULL) {
		content_close(bw->current_content);
		hlcache_handle_release(bw->current_content);
	}

	bw->current_content = bw->loading_content;
	bw->loading_content = NULL;

	if (!bw->internal_nav) {
		/* Transfer the fetch parameters */
		browser_window__free_fetch_parameters(&bw->current_parameters);
		bw->current_parameters = bw->loading_parameters;
		memset(&bw->loading_parameters, 0, sizeof(bw->loading_parameters));
		/* Transfer the SSL info */
		bw->current_ssl_info = bw->loading_ssl_info;
		bw->loading_ssl_info.num = 0;
	}

	/* Format the new content to the correct dimensions */
	browser_window_get_dimensions(bw, &width, &height);
	width /= bw->scale;
	height /= bw->scale;
	content_reformat(bw->current_content, false, width, height);

	/* history */
	if (bw->history_add && bw->history && !bw->internal_nav) {
		nsurl *url = hlcache_handle_get_url(bw->current_content);

		if (urldb_add_url(url)) {
			urldb_set_url_title(url, content_get_title(bw->current_content));
			urldb_update_url_visit_data(url);
			urldb_set_url_content_type(url,
						   content_get_type(bw->current_content));

			/* This is safe as we've just added the URL */
			global_history_add(urldb_get_url(url));
		}
		/**
		 * \todo Urldb / Thumbnails / Local history brokenness
		 *
		 * We add to local history after calling urldb_add_url rather
		 *  than in the block above.  If urldb_add_url fails (as it
		 *  will for urls like "about:about", "about:config" etc),
		 *  there would be no local history node, and later calls to
		 *  history_update will either explode or overwrite the node
		 *  for the previous URL.
		 *
		 * We call it after, rather than before urldb_add_url because
		 *  history_add calls bitmap render, which tries to register
		 *  the thumbnail with urldb.  That thumbnail registration
		 *  fails if the url doesn't exist in urldb already, and only
		 *  urldb-registered thumbnails get freed.  So if we called
		 *  history_add before urldb_add_url we would leak thumbnails
		 *  for all newly visited URLs.  With the history_add call
		 *  after, we only leak the thumbnails when urldb does not add
		 *  the URL.
		 *
		 * Also, since browser_window_history_add can create a
		 *  thumbnail (content_redraw), we need to do it after
		 *  content_reformat.
		 */
		browser_window_history_add(bw, bw->current_content, bw->frag_id);
	}

	browser_window_remove_caret(bw, false);

	if (bw->window != NULL) {
		guit->window->event(bw->window, GW_EVENT_NEW_CONTENT);

		browser_window_refresh_url_bar(bw);
	}

	/* new content; set scroll_to_top */
	browser_window_update(bw, true);
	content_open(bw->current_content, bw, 0, 0);
	browser_window_set_status(bw, content_get_status_message(bw->current_content));

	/* frames */
	if ((content_get_type(bw->current_content) == CONTENT_HTML) &&
	    (html_get_frameset(bw->current_content) != NULL)) {
		res = browser_window_create_frameset(bw, html_get_frameset(bw->current_content));
	}

	if (content_get_type(bw->current_content) == CONTENT_HTML &&
	    html_get_iframe(bw->current_content) != NULL) {
		browser_window_create_iframes(bw, html_get_iframe(bw->current_content));
	}

	/* Indicate page status may have changed */
	if (res == NSERROR_OK) {
		struct browser_window *root = browser_window_get_root(bw);
		res = guit->window->event(root->window, GW_EVENT_PAGE_INFO_CHANGE);
	}

	return res;
}


/**
 * handle message for content done on browser window
 */
static nserror
browser_window_content_done(struct browser_window *bw)
{
	float sx, sy;
	struct rect rect;
	int scrollx;
	int scrolly;

	if (bw->window == NULL) {
		/* Updated browser window's scrollbars. */
		/**
		 * \todo update browser window scrollbars before CONTENT_MSG_DONE
		 */
		browser_window_reformat(bw, true, bw->width, bw->height);
		browser_window_handle_scrollbars(bw);
	}

	browser_window_update(bw, false);
	browser_window_set_status(bw, content_get_status_message(bw->current_content));
	browser_window_stop_throbber(bw);
	browser_window_update_favicon(bw->current_content, bw, NULL);

	if (browser_window_history_get_scroll(bw, &sx, &sy) == NSERROR_OK) {
		scrollx = (int)((float)content_get_width(bw->current_content) * sx);
		scrolly = (int)((float)content_get_height(bw->current_content) * sy);
		rect.x0 = rect.x1 = scrollx;
		rect.y0 = rect.y1 = scrolly;
		if (browser_window_set_scroll(bw, &rect) != NSERROR_OK) {
			NSLOG(netsurf, WARNING,
			      "Unable to set browser scroll offsets to %d by %d",
			      scrollx, scrolly);
		}
	}

	if (!bw->internal_nav) {
		browser_window_history_update(bw, bw->current_content);
		hotlist_update_url(hlcache_handle_get_url(bw->current_content));
	}

	if (bw->refresh_interval != -1) {
		guit->misc->schedule(bw->refresh_interval * 10,
				     browser_window_refresh, bw);
	}

	return NSERROR_OK;
}


/**
 * Handle query responses from SSL requests
 */
static nserror
browser_window__handle_ssl_query_response(bool proceed, void *pw)
{
	struct browser_window *bw = (struct browser_window *)pw;

	/* If we're in the process of loading, stop the load */
	if (bw->loading_content != NULL) {
		/* We had a loading content (maybe auth page?) */
		browser_window_stop(bw);
		browser_window_remove_caret(bw, false);
		browser_window_destroy_children(bw);
	}

	if (!proceed) {
		/* We're processing a "back to safety", do a rough-and-ready
		 * nav to the old 'current' parameters, with any post data
		 * stripped away
		 */
		return browser_window__reload_current_parameters(bw);
	}

	/* We're processing a "proceed" attempt from the form */
	/* First, we permit the SSL */
	urldb_set_cert_permissions(bw->loading_parameters.url, true);

	/* And then we navigate to the original loading parameters */
	bw->internal_nav = false;

	return browser_window__navigate_internal(bw, &bw->loading_parameters);
}


/**
 * Unpack a "username:password" to components.
 *
 * \param[in]  userpass      The input string to split.
 * \param[in]  username_out  Returns username on success.  Owned by caller.
 * \param[out] password_out  Returns password on success.  Owned by caller.
 * \return NSERROR_OK, or appropriate error code.
 */
static nserror
browser_window__unpack_userpass(const char *userpass,
				char **username_out,
				char **password_out)
{
	const char *tmp;
	char *username;
	char *password;
	size_t len;

	if (userpass == NULL) {
		username = malloc(1);
		password = malloc(1);
		if (username == NULL || password == NULL) {
			free(username);
			free(password);
			return NSERROR_NOMEM;
		}
		username[0] = '\0';
		password[0] = '\0';

		*username_out = username;
		*password_out = password;
		return NSERROR_OK;
	}

	tmp = strchr(userpass, ':');
	if (tmp == NULL) {
		return NSERROR_BAD_PARAMETER;
	} else {
		size_t len2;
		len = tmp - userpass;
		len2 = strlen(++tmp);

		username = malloc(len + 1);
		password = malloc(len2 + 1);
		if (username == NULL || password == NULL) {
			free(username);
			free(password);
			return NSERROR_NOMEM;
		}
		memcpy(username, userpass, len);
		username[len] = '\0';
		memcpy(password, tmp, len2 + 1);
	}

	*username_out = username;
	*password_out = password;
	return NSERROR_OK;
}


/**
 * Build a "username:password" from components.
 *
 * \param[in]  username      The username component.
 * \param[in]  password      The password component.
 * \param[out] userpass_out  Returns combined string on success.
 *                           Owned by caller.
 * \return NSERROR_OK, or appropriate error code.
 */
static nserror
browser_window__build_userpass(const char *username,
			       const char *password,
			       char **userpass_out)
{
	char *userpass;
	size_t len;

	len = strlen(username) + 1 + strlen(password) + 1;

	userpass = malloc(len);
	if (userpass == NULL) {
		return NSERROR_NOMEM;
	}

	snprintf(userpass, len, "%s:%s", username, password);

	*userpass_out = userpass;
	return NSERROR_OK;
}


/**
 * Handle a response from the UI when prompted for credentials
 */
static nserror
browser_window__handle_userpass_response(nsurl *url,
					 const char *realm,
					 const char *username,
					 const char *password,
					 void *pw)
{
	struct browser_window *bw = (struct browser_window *)pw;
	char *userpass;
	nserror err;

	err = browser_window__build_userpass(username, password, &userpass);
	if (err != NSERROR_OK) {
		return err;
	}

	urldb_set_auth_details(url, realm, userpass);

	free(userpass);

	/**
	 * \todo QUERY - Eventually this should fill out the form *NOT* nav
	 *               to the original location
	 */
	/* Finally navigate to the original loading parameters */
	if (bw->loading_content != NULL) {
		/* We had a loading content (maybe auth page?) */
		browser_window_stop(bw);
		browser_window_remove_caret(bw, false);
		browser_window_destroy_children(bw);
	}
	bw->internal_nav = false;
	return browser_window__navigate_internal(bw, &bw->loading_parameters);
}


/**
 * Handle login request (BAD_AUTH) during fetch
 *
 */
static nserror
browser_window__handle_login(struct browser_window *bw,
			     const char *realm,
			     nsurl *url) {
	char *username = NULL, *password = NULL;
	nserror err = NSERROR_OK;
	struct browser_fetch_parameters params;

	memset(&params, 0, sizeof(params));

	/* Step one, retrieve what we have */
	err = browser_window__unpack_userpass(
				      urldb_get_auth_details(url, realm),
				      &username, &password);
	if (err != NSERROR_OK) {
		goto out;
	}

	/* Step two, construct our fetch parameters */
	params.url = nsurl_ref(corestring_nsurl_about_query_auth);
	params.referrer = nsurl_ref(url);
	params.flags = BW_NAVIGATE_HISTORY | BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE | BW_NAVIGATE_INTERNAL;

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "siteurl",
					  nsurl_access(url));
	if (err != NSERROR_OK) {
		goto out;
	}

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "realm",
					  realm);
	if (err != NSERROR_OK) {
		goto out;
	}

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "username",
					  username);
	if (err != NSERROR_OK) {
		goto out;
	}

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "password",
					  password);
	if (err != NSERROR_OK) {
		goto out;
	}

	/* Now we issue the fetch */
	bw->internal_nav = true;
	err = browser_window__navigate_internal(bw, &params);

	if (err != NSERROR_OK) {
		goto out;
	}

	err = guit->misc->login(url, realm, username, password,
				browser_window__handle_userpass_response, bw);

	if (err == NSERROR_NOT_IMPLEMENTED) {
		err = NSERROR_OK;
	}
 out:
	if (username != NULL) {
		free(username);
	}
	if (password != NULL) {
		free(password);
	}
	browser_window__free_fetch_parameters(&params);
	return err;
}


/**
 * Handle a certificate verification request (BAD_CERTS) during a fetch
 */
static nserror
browser_window__handle_bad_certs(struct browser_window *bw,
				 nsurl *url)
{
	struct browser_fetch_parameters params;
	nserror err;
	/* Initially we don't know WHY the SSL cert was bad */
	const char *reason = messages_get_sslcode(SSL_CERT_ERR_UNKNOWN);
	size_t n;

	memset(&params, 0, sizeof(params));

	params.url = nsurl_ref(corestring_nsurl_about_query_ssl);
	params.referrer = nsurl_ref(url);
	params.flags = BW_NAVIGATE_HISTORY | BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE | BW_NAVIGATE_INTERNAL;

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "siteurl",
					  nsurl_access(url));
	if (err != NSERROR_OK) {
		goto out;
	}

	for (n = 0; n < bw->loading_ssl_info.num; ++n) {
		size_t idx = bw->loading_ssl_info.num - (n + 1);
		ssl_cert_err err = bw->loading_ssl_info.certs[idx].err;
		if (err != SSL_CERT_ERR_OK) {
			reason = messages_get_sslcode(err);
			break;
		}
	}

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "reason",
					  reason);
	if (err != NSERROR_OK) {
		goto out;
	}

	/* Now we issue the fetch */
	bw->internal_nav = true;
	err = browser_window__navigate_internal(bw, &params);
	if (err != NSERROR_OK) {
		goto out;
	}

	err = guit->misc->cert_verify(url,
				      bw->loading_ssl_info.certs,
				      bw->loading_ssl_info.num,
				      browser_window__handle_ssl_query_response,
				      bw);

	if (err == NSERROR_NOT_IMPLEMENTED) {
		err = NSERROR_OK;
	}
 out:
	browser_window__free_fetch_parameters(&params);
	return err;
}


/**
 * Handle a timeout during a fetch
 */
static nserror
browser_window__handle_timeout(struct browser_window *bw, nsurl *url)
{
	struct browser_fetch_parameters params;
	nserror err;

	memset(&params, 0, sizeof(params));

	params.url = nsurl_ref(corestring_nsurl_about_query_timeout);
	params.referrer = nsurl_ref(url);
	params.flags = BW_NAVIGATE_HISTORY | BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE | BW_NAVIGATE_INTERNAL;

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "siteurl",
					  nsurl_access(url));
	if (err != NSERROR_OK) {
		goto out;
	}

	/* Now we issue the fetch */
	bw->internal_nav = true;
	err = browser_window__navigate_internal(bw, &params);
	if (err != NSERROR_OK) {
		goto out;
	}

 out:
	browser_window__free_fetch_parameters(&params);
	return err;
}


/**
 * Handle non specific errors during a fetch
 */
static nserror
browser_window__handle_fetcherror(struct browser_window *bw,
				  const char *reason,
				  nsurl *url)
{
	struct browser_fetch_parameters params;
	nserror err;

	memset(&params, 0, sizeof(params));

	params.url = nsurl_ref(corestring_nsurl_about_query_fetcherror);
	params.referrer = nsurl_ref(url);
	params.flags = BW_NAVIGATE_HISTORY | BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE | BW_NAVIGATE_INTERNAL;

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "siteurl",
					  nsurl_access(url));
	if (err != NSERROR_OK) {
		goto out;
	}

	err = fetch_multipart_data_new_kv(&params.post_multipart,
					  "reason",
					  reason);
	if (err != NSERROR_OK) {
		goto out;
	}

	/* Now we issue the fetch */
	bw->internal_nav = true;
	err = browser_window__navigate_internal(bw, &params);
	if (err != NSERROR_OK) {
		goto out;
	}

 out:
	browser_window__free_fetch_parameters(&params);
	return err;
}


/**
 * Handle errors during content fetch
 */
static nserror
browser_window__handle_error(struct browser_window *bw,
			     hlcache_handle *c,
			     const hlcache_event *event)
{
	const char *message = event->data.errordata.errormsg;
	nserror code = event->data.errordata.errorcode;
	nserror res;
	nsurl *url = hlcache_handle_get_url(c);

	/* Unexpected OK? */
	assert(code != NSERROR_OK);

	if (message == NULL) {
		message = messages_get_errorcode(code);
	}

	if (c == bw->loading_content) {
		bw->loading_content = NULL;
	} else if (c == bw->current_content) {
		bw->current_content = NULL;
		browser_window_remove_caret(bw, false);
	}

	hlcache_handle_release(c);

	switch (code) {
	case NSERROR_BAD_AUTH:
		res = browser_window__handle_login(bw, message, url);
		break;

	case NSERROR_BAD_CERTS:
		res = browser_window__handle_bad_certs(bw, url);
		break;

	case NSERROR_TIMEOUT:
		res = browser_window__handle_timeout(bw, url);
		break;

	default:
		res = browser_window__handle_fetcherror(bw, message, url);
		break;
	}

	return NSERROR_OK;
}


/**
 * Browser window content event callback handler.
 */
static nserror
browser_window_callback(hlcache_handle *c, const hlcache_event *event, void *pw)
{
	struct browser_window *bw = pw;
	nserror res = NSERROR_OK;

	switch (event->type) {
	case CONTENT_MSG_SSL_CERTS:
		/* SSL certificate information has arrived, store it */
		assert(event->data.certs.num < MAX_SSL_CERTS);
		memcpy(&bw->loading_ssl_info.certs[0],
		       event->data.certs.certs,
		       sizeof(struct ssl_cert_info) * event->data.certs.num);
		bw->loading_ssl_info.num = event->data.certs.num;
		break;

	case CONTENT_MSG_LOG:
		browser_window_console_log(bw,
					   event->data.log.src,
					   event->data.log.msg,
					   event->data.log.msglen,
					   event->data.log.flags);
		break;

	case CONTENT_MSG_DOWNLOAD:
		assert(bw->loading_content == c);

		browser_window_convert_to_download(bw, event->data.download);

		if (bw->current_content != NULL) {
			browser_window_refresh_url_bar(bw);
		}
		break;

	case CONTENT_MSG_LOADING:
		assert(bw->loading_content == c);

#ifdef WITH_THEME_INSTALL
		if (content_get_type(c) == CONTENT_THEME) {
			theme_install_start(c);
			bw->loading_content = NULL;
			browser_window_stop_throbber(bw);
		} else
#endif
		{
			bw->refresh_interval = -1;
			browser_window_set_status(bw,
						  content_get_status_message(c));
		}
		break;

	case CONTENT_MSG_READY:
		assert(bw->loading_content == c);

		res = browser_window_content_ready(bw);
		break;

	case CONTENT_MSG_DONE:
		assert(bw->current_content == c);

		res = browser_window_content_done(bw);
		break;

	case CONTENT_MSG_ERROR:
		res = browser_window__handle_error(bw, c, event);
		break;

	case CONTENT_MSG_REDIRECT:
		if (urldb_add_url(event->data.redirect.from)) {
			urldb_update_url_visit_data(event->data.redirect.from);
		}
		break;

	case CONTENT_MSG_STATUS:
		if (event->data.explicit_status_text == NULL) {
			/* Object content's status text updated */
			const char *status = NULL;
			if (bw->loading_content != NULL) {
				/* Give preference to any loading content */
				status = content_get_status_message(
							bw->loading_content);
			}

			if (status == NULL) {
				status = content_get_status_message(c);
			}

			if (status != NULL) {
				browser_window_set_status(bw, status);
			}
		} else {
			/* Object content wants to set explicit message */
			browser_window_set_status(bw,
					event->data.explicit_status_text);
		}
		break;

	case CONTENT_MSG_REFORMAT:
		if (c == bw->current_content &&
		    content_get_type(c) == CONTENT_HTML) {
			/* reposition frames */
			if (html_get_frameset(c) != NULL)
				browser_window_recalculate_frameset(bw);
			/* reflow iframe positions */
			if (html_get_iframe(c) != NULL)
				browser_window_recalculate_iframes(bw);
		}

		/* Hide any caret, but don't remove it */
		browser_window_remove_caret(bw, true);

		if (!(event->data.background)) {
			/* Reformatted content should be redrawn */
			browser_window_update(bw, false);
		}
		break;

	case CONTENT_MSG_REDRAW:
		{
			struct rect rect = {
					    .x0 = event->data.redraw.x,
					    .y0 = event->data.redraw.y,
					    .x1 = event->data.redraw.x + event->data.redraw.width,
					    .y1 = event->data.redraw.y + event->data.redraw.height
			};

			browser_window_update_box(bw, &rect);
		}
		break;

	case CONTENT_MSG_REFRESH:
		bw->refresh_interval = event->data.delay * 100;
		break;

	case CONTENT_MSG_LINK: /* content has an rfc5988 link element */
		{
			bool match;

			/* Handle "icon" and "shortcut icon" */
			if ((lwc_string_caseless_isequal(
							 event->data.rfc5988_link->rel,
							 corestring_lwc_icon,
							 &match) == lwc_error_ok && match) ||
			    (lwc_string_caseless_isequal(
							 event->data.rfc5988_link->rel,
							 corestring_lwc_shortcut_icon,
							 &match) == lwc_error_ok && match)) {
				/* it's a favicon perhaps start a fetch for it */
				browser_window_update_favicon(c, bw,
						      event->data.rfc5988_link);
			}
		}
		break;

	case CONTENT_MSG_GETCTX:
		/* only the content object created by the browser
		 * window requires a new global compartment object
		 */
		assert(bw->loading_content == c);
		if (js_newcompartment(bw->jsctx,
				      bw,
				      hlcache_handle_get_content(c)) != NULL) {
			*(event->data.jscontext) = bw->jsctx;
		}
		break;

	case CONTENT_MSG_GETDIMS:
		{
			int width;
			int height;

			browser_window_get_dimensions(bw, &width, &height);

			*(event->data.getdims.viewport_width) = width / bw->scale;
			*(event->data.getdims.viewport_height) = height / bw->scale;
			break;
		}

	case CONTENT_MSG_SCROLL:
		{
			struct rect rect = {
					    .x0 = event->data.scroll.x0,
					    .y0 = event->data.scroll.y0,
			};

			/* Content wants to be scrolled */
			if (bw->current_content != c) {
				break;
			}

			if (event->data.scroll.area) {
				rect.x1 = event->data.scroll.x1;
				rect.y1 = event->data.scroll.y1;
			} else {
				rect.x1 = event->data.scroll.x0;
				rect.y1 = event->data.scroll.y0;
			}
			browser_window_set_scroll(bw, &rect);

			break;
		}

	case CONTENT_MSG_DRAGSAVE:
		{
			/* Content wants drag save of a content */
			struct browser_window *root = browser_window_get_root(bw);
			hlcache_handle *save = event->data.dragsave.content;

			if (save == NULL) {
				save = c;
			}

			switch(event->data.dragsave.type) {
			case CONTENT_SAVE_ORIG:
				guit->window->drag_save_object(root->window,
							       save,
							       GUI_SAVE_OBJECT_ORIG);
				break;

			case CONTENT_SAVE_NATIVE:
				guit->window->drag_save_object(root->window,
							       save,
							       GUI_SAVE_OBJECT_NATIVE);
				break;

			case CONTENT_SAVE_COMPLETE:
				guit->window->drag_save_object(root->window,
							       save,
							       GUI_SAVE_COMPLETE);
				break;

			case CONTENT_SAVE_SOURCE:
				guit->window->drag_save_object(root->window,
							       save,
							       GUI_SAVE_SOURCE);
				break;
			}
		}
		break;

	case CONTENT_MSG_SAVELINK:
		{
			/* Content wants a link to be saved */
			struct browser_window *root = browser_window_get_root(bw);
			guit->window->save_link(root->window,
						event->data.savelink.url,
						event->data.savelink.title);
		}
		break;

	case CONTENT_MSG_POINTER:
		/* Content wants to have specific mouse pointer */
		browser_window_set_pointer(bw, event->data.pointer);
		break;

	case CONTENT_MSG_DRAG:
		{
			browser_drag_type bdt = DRAGGING_NONE;

			switch (event->data.drag.type) {
			case CONTENT_DRAG_NONE:
				bdt = DRAGGING_NONE;
				break;
			case CONTENT_DRAG_SCROLL:
				bdt = DRAGGING_CONTENT_SCROLLBAR;
				break;
			case CONTENT_DRAG_SELECTION:
				bdt = DRAGGING_SELECTION;
				break;
			}
			browser_window_set_drag_type(bw, bdt, event->data.drag.rect);
		}
		break;

	case CONTENT_MSG_CARET:
		switch (event->data.caret.type) {
		case CONTENT_CARET_REMOVE:
			browser_window_remove_caret(bw, false);
			break;
		case CONTENT_CARET_HIDE:
			browser_window_remove_caret(bw, true);
			break;
		case CONTENT_CARET_SET_POS:
			browser_window_place_caret(bw,
						   event->data.caret.pos.x,
						   event->data.caret.pos.y,
						   event->data.caret.pos.height,
						   event->data.caret.pos.clip);
			break;
		}
		break;

	case CONTENT_MSG_SELECTION:
		browser_window_set_selection(bw,
					     event->data.selection.selection,
					     event->data.selection.read_only);
		break;

	case CONTENT_MSG_SELECTMENU:
		if (event->data.select_menu.gadget->type == GADGET_SELECT) {
			struct browser_window *root =
				browser_window_get_root(bw);
			guit->window->create_form_select_menu(root->window,
							      event->data.select_menu.gadget);
		}

		break;

	case CONTENT_MSG_GADGETCLICK:
		if (event->data.gadget_click.gadget->type == GADGET_FILE) {
			struct browser_window *root =
				browser_window_get_root(bw);
			guit->window->file_gadget_open(root->window, c,
						       event->data.gadget_click.gadget);
		}

		break;

	default:
		break;
	}

	return res;
}


/**
 * internal scheduled reformat callback.
 *
 * scheduled reformat callback to allow reformats from unthreaded context.
 *
 * \param vbw The browser window to be reformatted
 */
static void scheduled_reformat(void *vbw)
{
	struct browser_window *bw = vbw;
	int width;
	int height;
	nserror res;

	res = guit->window->get_dimensions(bw->window, &width, &height);
	if (res == NSERROR_OK) {
		browser_window_reformat(bw, false, width, height);
	}
}


/**
 * Release all memory associated with a browser window.
 *
 * \param bw browser window
 */
static void browser_window_destroy_internal(struct browser_window *bw)
{
	assert(bw);

	NSLOG(netsurf, INFO, "Destroying window");

	if (bw->children != NULL || bw->iframes != NULL) {
		browser_window_destroy_children(bw);
	}

	/* Destroy scrollbars */
	if (bw->scroll_x != NULL) {
		scrollbar_destroy(bw->scroll_x);
	}

	if (bw->scroll_y != NULL) {
		scrollbar_destroy(bw->scroll_y);
	}

	/* clear any pending callbacks */
	guit->misc->schedule(-1, browser_window_refresh, bw);
	NSLOG(netsurf, INFO,
	      "Clearing reformat schedule for browser window %p", bw);
	guit->misc->schedule(-1, scheduled_reformat, bw);

	/* If this brower window is not the root window, and has focus, unset
	 * the root browser window's focus pointer. */
	if (!bw->window) {
		struct browser_window *top = browser_window_get_root(bw);

		if (top->focus == bw)
			top->focus = top;

		if (top->selection.bw == bw) {
			browser_window_set_selection(top, false, false);
		}
	}

	/* Destruction order is important: we must ensure that the frontend
	 * destroys any window(s) associated with this browser window before
	 * we attempt any destructive cleanup.
	 */

	if (bw->window) {
		/* Only the root window has a GUI window */
		guit->window->destroy(bw->window);
	}

	if (bw->loading_content != NULL) {
		hlcache_handle_abort(bw->loading_content);
		hlcache_handle_release(bw->loading_content);
		bw->loading_content = NULL;
	}

	if (bw->current_content != NULL) {
		content_close(bw->current_content);
		hlcache_handle_release(bw->current_content);
		bw->current_content = NULL;
	}

	if (bw->favicon.loading != NULL) {
		hlcache_handle_abort(bw->favicon.loading);
		hlcache_handle_release(bw->favicon.loading);
		bw->favicon.loading = NULL;
	}

	if (bw->favicon.current != NULL) {
		content_close(bw->favicon.current);
		hlcache_handle_release(bw->favicon.current);
		bw->favicon.current = NULL;
	}

	if (bw->box != NULL) {
		bw->box->iframe = NULL;
		bw->box = NULL;
	}

	if (bw->jsctx != NULL) {
		js_destroycontext(bw->jsctx);
	}

	/* These simply free memory, so are safe here */

	if (bw->frag_id != NULL) {
		lwc_string_unref(bw->frag_id);
	}

	browser_window_history_destroy(bw);

	free(bw->name);
	free(bw->status.text);
	bw->status.text = NULL;
	browser_window__free_fetch_parameters(&bw->current_parameters);
	browser_window__free_fetch_parameters(&bw->loading_parameters);
	NSLOG(netsurf, INFO, "Status text cache match:miss %d:%d",
	      bw->status.match, bw->status.miss);
}


/**
 * Update URL bar for a given browser window to given URL
 *
 * \param bw	Browser window to update URL bar for.
 * \param url	URL for content displayed by bw including any fragment.
 */
static inline nserror
browser_window_refresh_url_bar_internal(struct browser_window *bw, nsurl *url)
{
	assert(bw);
	assert(url);

	if ((bw->parent != NULL) || (bw->window == NULL)) {
		/* Not root window or no gui window so do not set a URL */
		return NSERROR_OK;
	}

	return guit->window->set_url(bw->window, url);
}


/**
 * scroll to a fragment if present
 *
 * \param bw browser window
 * \return true if the scroll was sucessful
 */
static bool frag_scroll(struct browser_window *bw)
{
	struct rect rect;

	if (bw->frag_id == NULL) {
		return false;
	}

	if (!html_get_id_offset(bw->current_content,
				bw->frag_id,
				&rect.x0,
				&rect.y0)) {
		return false;
	}

	rect.x1 = rect.x0;
	rect.y1 = rect.y0;
	if (browser_window_set_scroll(bw, &rect) == NSERROR_OK) {
		if (bw->current_content != NULL &&
		    bw->history != NULL &&
		    bw->history->current != NULL) {
			browser_window_history_update(bw, bw->current_content);
		}
		return true;
	}
	return false;
}


/**
 * Set browser window scale.
 *
 * \param bw Browser window.
 * \param absolute scale value.
 * \return NSERROR_OK on success else error code
 */
static nserror
browser_window_set_scale_internal(struct browser_window *bw, float scale)
{
	int i;
	nserror res = NSERROR_OK;

	/* do not apply tiny changes in scale */
	if (fabs(bw->scale - scale) < 0.0001)
		return res;

	bw->scale = scale;

	if (bw->current_content != NULL) {
		if (content_can_reformat(bw->current_content) == false) {
			browser_window_update(bw, false);
		} else {
			res = browser_window_schedule_reformat(bw);
		}
	}

	/* scale frames */
	for (i = 0; i < (bw->cols * bw->rows); i++) {
		res = browser_window_set_scale_internal(&bw->children[i], scale);
	}

	/* sale iframes */
	for (i = 0; i < bw->iframe_count; i++) {
		res = browser_window_set_scale_internal(&bw->iframes[i], scale);
	}

	return res;
}


/**
 * Find browser window.
 *
 * \param bw Browser window.
 * \param target Name of target.
 * \param depth Depth to scan.
 * \param page The browser window page.
 * \param rdepth The rdepth.
 * \param bw_target the output browser window.
 */
static void
browser_window_find_target_internal(struct browser_window *bw,
				    const char *target,
				    int depth,
				    struct browser_window *page,
				    int *rdepth,
				    struct browser_window **bw_target)
{
	int i;

	if ((bw->name) && (!strcasecmp(bw->name, target))) {
		if ((bw == page) || (depth > *rdepth)) {
			*rdepth = depth;
			*bw_target = bw;
		}
	}

	if ((!bw->children) && (!bw->iframes))
		return;

	depth++;

	if (bw->children != NULL) {
		for (i = 0; i < (bw->cols * bw->rows); i++) {
			if ((bw->children[i].name) &&
			    (!strcasecmp(bw->children[i].name,
					 target))) {
				if ((page == &bw->children[i]) ||
				    (depth > *rdepth)) {
					*rdepth = depth;
					*bw_target = &bw->children[i];
				}
			}
			if (bw->children[i].children)
				browser_window_find_target_internal(
							    &bw->children[i],
							    target, depth, page,
							    rdepth, bw_target);
		}
	}

	if (bw->iframes != NULL) {
		for (i = 0; i < bw->iframe_count; i++) {
			browser_window_find_target_internal(&bw->iframes[i],
							    target,
							    depth,
							    page,
							    rdepth,
							    bw_target);
		}
	}
}


/**
 * Handles the end of a drag operation in a browser window.
 *
 * \param  bw	  browser window
 * \param  mouse  state of mouse buttons and modifier keys
 * \param  x	  coordinate of mouse
 * \param  y	  coordinate of mouse
 *
 * \todo Remove this function, once these things are associated with content,
 *       rather than bw.
 */
static void
browser_window_mouse_drag_end(struct browser_window *bw,
			      browser_mouse_state mouse,
			      int x, int y)
{
	int scr_x, scr_y;

	switch (bw->drag.type) {
	case DRAGGING_SELECTION:
	case DRAGGING_OTHER:
	case DRAGGING_CONTENT_SCROLLBAR:
		/* Drag handled by content handler */
		break;

	case DRAGGING_SCR_X:

		browser_window_get_scrollbar_pos(bw, true, &scr_x, &scr_y);

		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		scrollbar_mouse_drag_end(bw->scroll_x, mouse, scr_x, scr_y);

		bw->drag.type = DRAGGING_NONE;
		break;

	case DRAGGING_SCR_Y:

		browser_window_get_scrollbar_pos(bw, false, &scr_x, &scr_y);

		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		scrollbar_mouse_drag_end(bw->scroll_y, mouse, scr_x, scr_y);

		bw->drag.type = DRAGGING_NONE;
		break;

	default:
		browser_window_set_drag_type(bw, DRAGGING_NONE, NULL);
		break;
	}
}

/**
 * Process mouse click event
 *
 * \param bw The browsing context receiving the event
 * \param mouse The mouse event state
 * \param x The scaled x co-ordinate of the event
 * \param y The scaled y co-ordinate of the event
 */
static void
browser_window_mouse_click_internal(struct browser_window *bw,
				    browser_mouse_state mouse,
				    int x, int y)
{
	hlcache_handle *c = bw->current_content;
	const char *status = NULL;
	browser_pointer_shape pointer = BROWSER_POINTER_DEFAULT;

	if (bw->children) {
		/* Browser window has children (frames) */
		struct browser_window *child;
		int cur_child;
		int children = bw->rows * bw->cols;

		for (cur_child = 0; cur_child < children; cur_child++) {

			child = &bw->children[cur_child];

			if ((x < child->x) ||
			    (y < child->y) ||
			    (child->x + child->width < x) ||
			    (child->y + child->height < y)) {
				/* Click not in this child */
				continue;
			}

			/* It's this child that contains the click; pass it
			 * on to child. */
			browser_window_mouse_click_internal(
				child,
				mouse,
				x - child->x + scrollbar_get_offset(child->scroll_x),
				y - child->y + scrollbar_get_offset(child->scroll_y));

			/* Mouse action was for this child, we're done */
			return;
		}

		return;
	}

	if (!c)
		return;

	if (bw->scroll_x != NULL) {
		int scr_x, scr_y;
		browser_window_get_scrollbar_pos(bw, true, &scr_x, &scr_y);
		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		if (scr_x > 0 && scr_x < get_horz_scrollbar_len(bw) &&
		    scr_y > 0 && scr_y < SCROLLBAR_WIDTH) {
			status = scrollbar_mouse_status_to_message(
					   scrollbar_mouse_action(
						  bw->scroll_x, mouse,
						  scr_x, scr_y));
			pointer = BROWSER_POINTER_DEFAULT;

			if (status != NULL)
				browser_window_set_status(bw, status);

			browser_window_set_pointer(bw, pointer);
			return;
		}
	}

	if (bw->scroll_y != NULL) {
		int scr_x, scr_y;
		browser_window_get_scrollbar_pos(bw, false, &scr_x, &scr_y);
		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		if (scr_y > 0 && scr_y < get_vert_scrollbar_len(bw) &&
		    scr_x > 0 && scr_x < SCROLLBAR_WIDTH) {
			status = scrollbar_mouse_status_to_message(
						scrollbar_mouse_action(
							bw->scroll_y,
							mouse,
							scr_x,
							scr_y));
			pointer = BROWSER_POINTER_DEFAULT;

			if (status != NULL) {
				browser_window_set_status(bw, status);
			}

			browser_window_set_pointer(bw, pointer);
			return;
		}
	}

	switch (content_get_type(c)) {
	case CONTENT_HTML:
	case CONTENT_TEXTPLAIN:
		{
			/* Give bw focus */
			struct browser_window *root_bw = browser_window_get_root(bw);
			if (bw != root_bw->focus) {
				browser_window_remove_caret(bw, false);
				browser_window_set_selection(bw, false, true);
				root_bw->focus = bw;
			}

			/* Pass mouse action to content */
			content_mouse_action(c, bw, mouse, x, y);
		}
		break;
	default:
		if (mouse & BROWSER_MOUSE_MOD_2) {
			if (mouse & BROWSER_MOUSE_DRAG_2) {
				guit->window->drag_save_object(bw->window, c,
							       GUI_SAVE_OBJECT_NATIVE);
			} else if (mouse & BROWSER_MOUSE_DRAG_1) {
				guit->window->drag_save_object(bw->window, c,
							       GUI_SAVE_OBJECT_ORIG);
			}
		} else if (mouse & (BROWSER_MOUSE_DRAG_1 |
				    BROWSER_MOUSE_DRAG_2)) {
			browser_window_page_drag_start(bw, x, y);
			browser_window_set_pointer(bw, BROWSER_POINTER_MOVE);
		}
		break;
	}
}


/**
 * Process mouse movement event
 *
 * \param bw The browsing context receiving the event
 * \param mouse The mouse event state
 * \param x The scaled x co-ordinate of the event
 * \param y The scaled y co-ordinate of the event
 */
static void
browser_window_mouse_track_internal(struct browser_window *bw,
				    browser_mouse_state mouse,
				    int x, int y)
{
	hlcache_handle *c = bw->current_content;
	const char *status = NULL;
	browser_pointer_shape pointer = BROWSER_POINTER_DEFAULT;

	if (bw->window != NULL && bw->drag.window && bw != bw->drag.window) {
		/* This is the root browser window and there's an active drag
		 * in a sub window.
		 * Pass the mouse action straight on to that bw. */
		struct browser_window *drag_bw = bw->drag.window;
		int off_x = 0;
		int off_y = 0;

		browser_window_get_position(drag_bw, true, &off_x, &off_y);

		if (drag_bw->browser_window_type == BROWSER_WINDOW_FRAME) {
			browser_window_mouse_track_internal(drag_bw,
							    mouse,
							    x - off_x,
							    y - off_y);

		} else if (drag_bw->browser_window_type == BROWSER_WINDOW_IFRAME) {
			browser_window_mouse_track_internal(drag_bw, mouse,
							    x - off_x / bw->scale,
							    y - off_y / bw->scale);
		}
		return;
	}

	if (bw->children) {
		/* Browser window has children (frames) */
		struct browser_window *child;
		int cur_child;
		int children = bw->rows * bw->cols;

		for (cur_child = 0; cur_child < children; cur_child++) {

			child = &bw->children[cur_child];

			if ((x < child->x) ||
			    (y < child->y) ||
			    (child->x + child->width < x) ||
			    (child->y + child->height < y)) {
				/* Click not in this child */
				continue;
			}

			/* It's this child that contains the mouse; pass
			 * mouse action on to child */
			browser_window_mouse_track_internal(
				child,
				mouse,
				x - child->x + scrollbar_get_offset(child->scroll_x),
				y - child->y + scrollbar_get_offset(child->scroll_y));

			/* Mouse action was for this child, we're done */
			return;
		}

		/* Odd if we reached here, but nothing else can use the click
		 * when there are children. */
		return;
	}

	if (c == NULL && bw->drag.type != DRAGGING_FRAME) {
		return;
	}

	if (bw->drag.type != DRAGGING_NONE && !mouse) {
		browser_window_mouse_drag_end(bw, mouse, x, y);
	}

	/* Browser window's horizontal scrollbar */
	if (bw->scroll_x != NULL && bw->drag.type != DRAGGING_SCR_Y) {
		int scr_x, scr_y;
		browser_window_get_scrollbar_pos(bw, true, &scr_x, &scr_y);
		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		if ((bw->drag.type == DRAGGING_SCR_X) ||
		    (scr_x > 0 &&
		     scr_x < get_horz_scrollbar_len(bw) &&
		     scr_y > 0 &&
		     scr_y < SCROLLBAR_WIDTH &&
		     bw->drag.type == DRAGGING_NONE)) {
			/* Start a scrollbar drag, or continue existing drag */
			status = scrollbar_mouse_status_to_message(
					scrollbar_mouse_action(bw->scroll_x,
							       mouse,
							       scr_x,
							       scr_y));
			pointer = BROWSER_POINTER_DEFAULT;

			if (status != NULL) {
				browser_window_set_status(bw, status);
			}

			browser_window_set_pointer(bw, pointer);
			return;
		}
	}

	/* Browser window's vertical scrollbar */
	if (bw->scroll_y != NULL) {
		int scr_x, scr_y;
		browser_window_get_scrollbar_pos(bw, false, &scr_x, &scr_y);
		scr_x = x - scr_x - scrollbar_get_offset(bw->scroll_x);
		scr_y = y - scr_y - scrollbar_get_offset(bw->scroll_y);

		if ((bw->drag.type == DRAGGING_SCR_Y) ||
		    (scr_y > 0 &&
		     scr_y < get_vert_scrollbar_len(bw) &&
		     scr_x > 0 &&
		     scr_x < SCROLLBAR_WIDTH &&
		     bw->drag.type == DRAGGING_NONE)) {
			/* Start a scrollbar drag, or continue existing drag */
			status = scrollbar_mouse_status_to_message(
					scrollbar_mouse_action(bw->scroll_y,
							       mouse,
							       scr_x,
							       scr_y));
			pointer = BROWSER_POINTER_DEFAULT;

			if (status != NULL) {
				browser_window_set_status(bw, status);
			}

			browser_window_set_pointer(bw, pointer);
			return;
		}
	}

	if (bw->drag.type == DRAGGING_FRAME) {
		browser_window_resize_frame(bw, bw->x + x, bw->y + y);
	} else if (bw->drag.type == DRAGGING_PAGE_SCROLL) {
		/* mouse movement since drag started */
		struct rect rect;

		rect.x0 = bw->drag.start_x - x;
		rect.y0 = bw->drag.start_y - y;

		/* new scroll offsets */
		rect.x0 += bw->drag.start_scroll_x;
		rect.y0 += bw->drag.start_scroll_y;

		bw->drag.start_scroll_x = rect.x1 = rect.x0;
		bw->drag.start_scroll_y = rect.y1 = rect.y0;

		browser_window_set_scroll(bw, &rect);
	} else {
		assert(c != NULL);
		content_mouse_track(c, bw, mouse, x, y);
	}
}


/**
 * perform a scroll operation at a given coordinate
 *
 * \param bw The browsing context receiving the event
 * \param x The scaled x co-ordinate of the event
 * \param y The scaled y co-ordinate of the event
 */
static bool
browser_window_scroll_at_point_internal(struct browser_window *bw,
					int x, int y,
					int scrx, int scry)
{
	bool handled_scroll = false;
	assert(bw != NULL);

	/* Handle (i)frame scroll offset (core-managed browser windows only) */
	x += scrollbar_get_offset(bw->scroll_x);
	y += scrollbar_get_offset(bw->scroll_y);

	if (bw->children) {
		/* Browser window has children, so pass request on to
		 * appropriate child */
		struct browser_window *bwc;
		int cur_child;
		int children = bw->rows * bw->cols;

		/* Loop through all children of bw */
		for (cur_child = 0; cur_child < children; cur_child++) {
			/* Set current child */
			bwc = &bw->children[cur_child];

			/* Skip this frame if (x, y) coord lies outside */
			if (x < bwc->x || bwc->x + bwc->width < x ||
			    y < bwc->y || bwc->y + bwc->height < y)
				continue;

			/* Pass request into this child */
			return browser_window_scroll_at_point_internal(
								bwc,
								(x - bwc->x),
								(y - bwc->y),
								scrx, scry);
		}
	}

	/* Try to scroll any current content */
	if (bw->current_content != NULL &&
	    content_scroll_at_point(bw->current_content, x, y, scrx, scry) == true) {
		/* Scroll handled by current content */
		return true;
	}

	/* Try to scroll this window, if scroll not already handled */
	if (handled_scroll == false) {
		if (bw->scroll_y && scrollbar_scroll(bw->scroll_y, scry)) {
			handled_scroll = true;
		}

		if (bw->scroll_x && scrollbar_scroll(bw->scroll_x, scrx)) {
			handled_scroll = true;
		}
	}

	return handled_scroll;
}


/**
 * allows a dragged file to be dropped into a browser window at a position
 *
 * \param bw The browsing context receiving the event
 * \param x The scaled x co-ordinate of the event
 * \param y The scaled y co-ordinate of the event
 * \param file filename to be put in the widget
 */
static bool
browser_window_drop_file_at_point_internal(struct browser_window *bw,
					   int x, int y,
					   char *file)
{
	assert(bw != NULL);

	/* Handle (i)frame scroll offset (core-managed browser windows only) */
	x += scrollbar_get_offset(bw->scroll_x);
	y += scrollbar_get_offset(bw->scroll_y);

	if (bw->children) {
		/* Browser window has children, so pass request on to
		 * appropriate child */
		struct browser_window *bwc;
		int cur_child;
		int children = bw->rows * bw->cols;

		/* Loop through all children of bw */
		for (cur_child = 0; cur_child < children; cur_child++) {
			/* Set current child */
			bwc = &bw->children[cur_child];

			/* Skip this frame if (x, y) coord lies outside */
			if (x < bwc->x || bwc->x + bwc->width < x ||
			    y < bwc->y || bwc->y + bwc->height < y)
				continue;

			/* Pass request into this child */
			return browser_window_drop_file_at_point_internal(
								bwc,
								(x - bwc->x),
								(y - bwc->y),
								file);
		}
	}

	/* Pass file drop on to any content */
	if (bw->current_content != NULL) {
		return content_drop_file_at_point(bw->current_content,
						  x, y, file);
	}

	return false;
}


/**
 * Check if this is an internal navigation URL.
 *
 * This safely checks if the given url is an internal navigation even
 *  for urls with no scheme or path.
 *
 * \param url The URL to check
 * \return true if an internal navigation url else false
 */
static bool
is_internal_navigate_url(nsurl *url)
{
	bool is_internal = false;
	lwc_string *scheme, *path;

	scheme = nsurl_get_component(url, NSURL_SCHEME);
	if (scheme != NULL) {
		path = nsurl_get_component(url, NSURL_PATH);
		if (path != NULL) {
			if (scheme == corestring_lwc_about) {
				if (path == corestring_lwc_query_auth) {
					is_internal = true;
				} else if (path == corestring_lwc_query_ssl) {
					is_internal = true;
				} else if (path == corestring_lwc_query_timeout) {
					is_internal = true;
				} else if (path == corestring_lwc_query_fetcherror) {
					is_internal = true;
				}
			}
			lwc_string_unref(path);
		}
		lwc_string_unref(scheme);
	}
	return is_internal;
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_get_name(struct browser_window *bw, const char **out_name)
{
	assert(bw != NULL);

	*out_name = bw->name;

	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_set_name(struct browser_window *bw, const char *name)
{
	char *nname = NULL;

	assert(bw != NULL);

	if (name != NULL) {
		nname = strdup(name);
		if (nname == NULL) {
			return NSERROR_NOMEM;
		}
	}

	if (bw->name != NULL) {
		free(bw->name);
	}

	bw->name = nname;

	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
bool
browser_window_redraw(struct browser_window *bw,
		      int x, int y,
		      const struct rect *clip,
		      const struct redraw_context *ctx)
{
	struct redraw_context new_ctx = *ctx;
	int width = 0;
	int height = 0;
	bool plot_ok = true;
	content_type content_type;
	struct content_redraw_data data;
	struct rect content_clip;
	nserror res;

	x /= bw->scale;
	y /= bw->scale;

	if (bw == NULL) {
		NSLOG(netsurf, INFO, "NULL browser window");
		return false;
	}

	if ((bw->current_content == NULL) &&
	    (bw->children == NULL)) {
		/* Browser window has no content, render blank fill */
		ctx->plot->clip(ctx, clip);
		return (ctx->plot->rectangle(ctx, plot_style_fill_white, clip) == NSERROR_OK);
	}

	/* Browser window has content OR children (frames) */
	if ((bw->window != NULL) &&
	    (ctx->plot->option_knockout)) {
		/* Root browser window: start knockout */
		knockout_plot_start(ctx, &new_ctx);
	}

	new_ctx.plot->clip(ctx, clip);

	/* Handle redraw of any browser window children */
	if (bw->children) {
		struct browser_window *child;
		int cur_child;
		int children = bw->rows * bw->cols;

		if (bw->window != NULL) {
			/* Root browser window; start with blank fill */
			plot_ok &= (new_ctx.plot->rectangle(ctx,
							    plot_style_fill_white,
							    clip) == NSERROR_OK);
		}

		/* Loop through all children of bw */
		for (cur_child = 0; cur_child < children; cur_child++) {
			/* Set current child */
			child = &bw->children[cur_child];

			/* Get frame edge box in global coordinates */
			content_clip.x0 = (x + child->x) * child->scale;
			content_clip.y0 = (y + child->y) * child->scale;
			content_clip.x1 = content_clip.x0 +
				child->width * child->scale;
			content_clip.y1 = content_clip.y0 +
				child->height * child->scale;

			/* Intersect it with clip rectangle */
			if (content_clip.x0 < clip->x0)
				content_clip.x0 = clip->x0;
			if (content_clip.y0 < clip->y0)
				content_clip.y0 = clip->y0;
			if (clip->x1 < content_clip.x1)
				content_clip.x1 = clip->x1;
			if (clip->y1 < content_clip.y1)
				content_clip.y1 = clip->y1;

			/* Skip this frame if it lies outside clip rectangle */
			if (content_clip.x0 >= content_clip.x1 ||
			    content_clip.y0 >= content_clip.y1)
				continue;

			/* Redraw frame */
			plot_ok &= browser_window_redraw(child,
							 x + child->x,
							 y + child->y,
							 &content_clip,
							 &new_ctx);
		}

		/* Nothing else to redraw for browser windows with children;
		 * cleanup and return
		 */
		if (bw->window != NULL && ctx->plot->option_knockout) {
			/* Root browser window: knockout end */
			knockout_plot_end(ctx);
		}

		return plot_ok;
	}

	/* Handle browser windows with content to redraw */

	content_type = content_get_type(bw->current_content);
	if (content_type != CONTENT_HTML && content_type != CONTENT_TEXTPLAIN) {
		/* Set render area according to scale */
		width = content_get_width(bw->current_content) * bw->scale;
		height = content_get_height(bw->current_content) * bw->scale;

		/* Non-HTML may not fill viewport to extents, so plot white
		 * background fill */
		plot_ok &= (new_ctx.plot->rectangle(&new_ctx,
						    plot_style_fill_white,
						    clip) == NSERROR_OK);
	}

	/* Set up content redraw data */
	data.x = x - scrollbar_get_offset(bw->scroll_x);
	data.y = y - scrollbar_get_offset(bw->scroll_y);
	data.width = width;
	data.height = height;

	data.background_colour = 0xFFFFFF;
	data.scale = bw->scale;
	data.repeat_x = false;
	data.repeat_y = false;

	content_clip = *clip;

	if (!bw->window) {
		int x0 = x * bw->scale;
		int y0 = y * bw->scale;
		int x1 = (x + bw->width - ((bw->scroll_y != NULL) ?
					   SCROLLBAR_WIDTH : 0)) * bw->scale;
		int y1 = (y + bw->height - ((bw->scroll_x != NULL) ?
					    SCROLLBAR_WIDTH : 0)) * bw->scale;

		if (content_clip.x0 < x0) content_clip.x0 = x0;
		if (content_clip.y0 < y0) content_clip.y0 = y0;
		if (x1 < content_clip.x1) content_clip.x1 = x1;
		if (y1 < content_clip.y1) content_clip.y1 = y1;
	}

	/* Render the content */
	plot_ok &= content_redraw(bw->current_content, &data,
				  &content_clip, &new_ctx);

	/* Back to full clip rect */
	new_ctx.plot->clip(&new_ctx, clip);

	if (!bw->window) {
		/* Render scrollbars */
		int off_x, off_y;
		if (bw->scroll_x != NULL) {
			browser_window_get_scrollbar_pos(bw, true,
							 &off_x, &off_y);
			res = scrollbar_redraw(bw->scroll_x,
					       x + off_x, y + off_y, clip,
					       bw->scale, &new_ctx);
			if (res != NSERROR_OK) {
				plot_ok = false;
			}
		}
		if (bw->scroll_y != NULL) {
			browser_window_get_scrollbar_pos(bw, false,
							 &off_x, &off_y);
			res = scrollbar_redraw(bw->scroll_y,
					       x + off_x, y + off_y, clip,
					       bw->scale, &new_ctx);
			if (res != NSERROR_OK) {
				plot_ok = false;
			}
		}
	}

	if (bw->window != NULL && ctx->plot->option_knockout) {
		/* Root browser window: end knockout */
		knockout_plot_end(ctx);
	}

	return plot_ok;
}


/* exported interface, documented in netsurf/browser_window.h */
bool browser_window_redraw_ready(struct browser_window *bw)
{
	if (bw == NULL) {
		NSLOG(netsurf, INFO, "NULL browser window");
		return false;
	} else if (bw->current_content != NULL) {
		/* Can't render locked contents */
		return !content_is_locked(bw->current_content);
	}

	return true;
}


/* exported interface, documented in browser_private.h */
void browser_window_update_extent(struct browser_window *bw)
{
	if (bw->window != NULL) {
		/* Front end window */
		guit->window->event(bw->window, GW_EVENT_UPDATE_EXTENT);
	} else {
		/* Core-managed browser window */
		browser_window_handle_scrollbars(bw);
	}
}


/* exported interface, documented in netsurf/browser_window.h */
void
browser_window_get_position(struct browser_window *bw,
			    bool root,
			    int *pos_x,
			    int *pos_y)
{
	*pos_x = 0;
	*pos_y = 0;

	assert(bw != NULL);

	while (bw) {
		switch (bw->browser_window_type) {

		case BROWSER_WINDOW_FRAMESET:
			*pos_x += bw->x * bw->scale;
			*pos_y += bw->y * bw->scale;
			break;

		case BROWSER_WINDOW_NORMAL:
			/* There is no offset to the root browser window */
			break;

		case BROWSER_WINDOW_FRAME:
			/* Iframe and Frame handling is identical;
			 * fall though */
		case BROWSER_WINDOW_IFRAME:
			*pos_x += (bw->x - scrollbar_get_offset(bw->scroll_x)) *
				bw->scale;
			*pos_y += (bw->y - scrollbar_get_offset(bw->scroll_y)) *
				bw->scale;
			break;
		}

		bw = bw->parent;

		if (!root) {
			/* return if we just wanted the position in the parent
			 * browser window. */
			return;
		}
	}
}


/* exported interface, documented in netsurf/browser_window.h */
void browser_window_set_position(struct browser_window *bw, int x, int y)
{
	assert(bw != NULL);

	if (bw->window == NULL) {
		/* Core managed browser window */
		bw->x = x;
		bw->y = y;
	} else {
		NSLOG(netsurf, INFO,
		      "Asked to set position of front end window.");
		assert(0);
	}
}


/* exported interface, documented in netsurf/browser_window.h */
void
browser_window_set_drag_type(struct browser_window *bw,
			     browser_drag_type type,
			     const struct rect *rect)
{
	struct browser_window *top_bw = browser_window_get_root(bw);
	gui_drag_type gtype;

	bw->drag.type = type;

	if (type == DRAGGING_NONE) {
		top_bw->drag.window = NULL;
	} else {
		top_bw->drag.window = bw;

		switch (type) {
		case DRAGGING_SELECTION:
			/** \todo tell front end */
			return;
		case DRAGGING_SCR_X:
		case DRAGGING_SCR_Y:
		case DRAGGING_CONTENT_SCROLLBAR:
			gtype = GDRAGGING_SCROLLBAR;
			break;
		default:
			gtype = GDRAGGING_OTHER;
			break;
		}

		guit->window->drag_start(top_bw->window, gtype, rect);
	}
}


/* exported interface, documented in netsurf/browser_window.h */
browser_drag_type browser_window_get_drag_type(struct browser_window *bw)
{
	return bw->drag.type;
}


/* exported interface, documented in netsurf/browser_window.h */
struct browser_window * browser_window_get_root(struct browser_window *bw)
{
	while (bw && bw->parent) {
		bw = bw->parent;
	}
	return bw;
}


/* exported interface, documented in netsurf/browser_window.h */
browser_editor_flags browser_window_get_editor_flags(struct browser_window *bw)
{
	browser_editor_flags ed_flags = BW_EDITOR_NONE;
	assert(bw->window);
	assert(bw->parent == NULL);

	if (bw->selection.bw != NULL) {
		ed_flags |= BW_EDITOR_CAN_COPY;

		if (!bw->selection.read_only)
			ed_flags |= BW_EDITOR_CAN_CUT;
	}

	if (bw->can_edit)
		ed_flags |= BW_EDITOR_CAN_PASTE;

	return ed_flags;
}


/* exported interface, documented in netsurf/browser_window.h */
bool browser_window_can_select(struct browser_window *bw)
{
	if (bw == NULL || bw->current_content == NULL)
		return false;

	/* TODO: We shouldn't have to know about specific content types
	 *       here.  There should be a content_is_selectable() call. */
	if (content_get_type(bw->current_content) != CONTENT_HTML &&
	    content_get_type(bw->current_content) !=
	    CONTENT_TEXTPLAIN)
		return false;

	return true;
}


/* exported interface, documented in netsurf/browser_window.h */
char * browser_window_get_selection(struct browser_window *bw)
{
	assert(bw->window);
	assert(bw->parent == NULL);

	if (bw->selection.bw == NULL ||
	    bw->selection.bw->current_content == NULL)
		return NULL;

	return content_get_selection(bw->selection.bw->current_content);
}


/* exported interface, documented in netsurf/browser_window.h */
bool browser_window_can_search(struct browser_window *bw)
{
	if (bw == NULL || bw->current_content == NULL)
		return false;

	/** \todo We shouldn't have to know about specific content
	 * types here. There should be a content_is_searchable() call.
	 */
	if ((content_get_type(bw->current_content) != CONTENT_HTML) &&
	    (content_get_type(bw->current_content) != CONTENT_TEXTPLAIN)) {
		return false;
	}

	return true;
}


/* exported interface, documented in netsurf/browser_window.h */
bool browser_window_is_frameset(struct browser_window *bw)
{
	return (bw->children != NULL);
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_get_scrollbar_type(struct browser_window *bw,
				  browser_scrolling *h,
				  browser_scrolling *v)
{
	*h = bw->scrolling;
	*v = bw->scrolling;

	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_get_features(struct browser_window *bw,
			    int x, int y,
			    struct browser_window_features *data)
{
	/* clear the features structure to empty values */
	data->link = NULL;
	data->object = NULL;
	data->main = NULL;
	data->form_features = CTX_FORM_NONE;

	return browser_window__get_contextual_content(bw,
						      x / bw->scale,
						      y / bw->scale,
						      data);
}


/* exported interface, documented in netsurf/browser_window.h */
bool
browser_window_scroll_at_point(struct browser_window *bw,
			       int x, int y,
			       int scrx, int scry)
{
	return browser_window_scroll_at_point_internal(bw,
						       x / bw->scale,
						       y / bw->scale,
						       scrx,
						       scry);
}


/* exported interface, documented in netsurf/browser_window.h */
bool
browser_window_drop_file_at_point(struct browser_window *bw,
				  int x, int y,
				  char *file)
{
	return browser_window_drop_file_at_point_internal(bw,
							  x / bw->scale,
							  y / bw->scale,
							  file);
}


/* exported interface, documented in netsurf/browser_window.h */
void
browser_window_set_gadget_filename(struct browser_window *bw,
				   struct form_control *gadget,
				   const char *fn)
{
	html_set_file_gadget_filename(bw->current_content, gadget, fn);
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_debug_dump(struct browser_window *bw,
			  FILE *f,
			  enum content_debug op)
{
	if (bw->current_content != NULL) {
		return content_debug_dump(bw->current_content, f, op);
	}
	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
nserror browser_window_debug(struct browser_window *bw, enum content_debug op)
{
	if (bw->current_content != NULL) {
		return content_debug(bw->current_content, op);
	}
	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
nserror
browser_window_create(enum browser_window_create_flags flags,
		      nsurl *url,
		      nsurl *referrer,
		      struct browser_window *existing,
		      struct browser_window **bw)
{
	gui_window_create_flags gw_flags = GW_CREATE_NONE;
	struct browser_window *ret;
	nserror err;

	/* Check parameters */
	if (flags & BW_CREATE_CLONE) {
		if (existing == NULL) {
			assert(0 && "Failed: No existing window provided.");
			return NSERROR_BAD_PARAMETER;
		}
	}

	if (!(flags & BW_CREATE_HISTORY)) {
		if (!(flags & BW_CREATE_CLONE) || existing == NULL) {
			assert(0 && "Failed: Must have existing for history.");
			return NSERROR_BAD_PARAMETER;
		}
	}

	ret = calloc(1, sizeof(struct browser_window));
	if (ret == NULL) {
		return NSERROR_NOMEM;
	}

	/* Initialise common parts */
	err = browser_window_initialise_common(flags, ret, existing);
	if (err != NSERROR_OK) {
		browser_window_destroy(ret);
		return err;
	}

	/* window characteristics */
	ret->browser_window_type = BROWSER_WINDOW_NORMAL;
	ret->scrolling = BW_SCROLLING_YES;
	ret->border = true;
	ret->no_resize = true;
	ret->focus = ret;

	/* initialise last action with creation time */
	nsu_getmonotonic_ms(&ret->last_action);

	/* The existing gui_window is on the top-level existing
	 * browser_window. */
	existing = browser_window_get_root(existing);

	/* Set up gui_window creation flags */
	if (flags & BW_CREATE_TAB)
		gw_flags |= GW_CREATE_TAB;
	if (flags & BW_CREATE_CLONE)
		gw_flags |= GW_CREATE_CLONE;
	if (flags & BW_CREATE_FOREGROUND)
		gw_flags |= GW_CREATE_FOREGROUND;

	ret->window = guit->window->create(ret,
					   (existing != NULL) ? existing->window : NULL,
					   gw_flags);

	if (ret->window == NULL) {
		browser_window_destroy(ret);
		return NSERROR_BAD_PARAMETER;
	}

	if (url != NULL) {
		enum browser_window_nav_flags nav_flags;
		nav_flags = BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE;
		if (flags & BW_CREATE_UNVERIFIABLE) {
			nav_flags |= BW_NAVIGATE_UNVERIFIABLE;
		}
		if (flags & BW_CREATE_HISTORY) {
			nav_flags |= BW_NAVIGATE_HISTORY;
		}
		browser_window_navigate(ret,
					url,
					referrer,
					nav_flags,
					NULL,
					NULL,
					NULL);
	}

	if (bw != NULL) {
		*bw = ret;
	}

	return NSERROR_OK;
}


/* exported internal interface, documented in desktop/browser_private.h */
nserror
browser_window_initialise_common(enum browser_window_create_flags flags,
				 struct browser_window *bw,
				 struct browser_window *existing)
{
	nserror err;
	assert(bw);

	/* new javascript context for each window/(i)frame */
	err = js_newcontext(nsoption_int(script_timeout),
			    slow_script, NULL, &bw->jsctx);
	if (err != NSERROR_OK)
		return err;

	if (flags & BW_CREATE_CLONE) {
		assert(existing != NULL);

		/* clone history */
		err = browser_window_history_clone(existing, bw);

		/* copy the scale */
		bw->scale = existing->scale;
	} else {
		/* create history */
		err = browser_window_history_create(bw);

		/* default scale */
		bw->scale = (float) nsoption_int(scale) / 100.0;
	}

	if (err != NSERROR_OK)
		return err;

	/* window characteristics */
	bw->refresh_interval = -1;

	bw->drag.type = DRAGGING_NONE;

	bw->scroll_x = NULL;
	bw->scroll_y = NULL;

	bw->focus = NULL;

	/* initialise status text cache */
	bw->status.text = NULL;
	bw->status.text_len = 0;
	bw->status.match = 0;
	bw->status.miss = 0;

	return NSERROR_OK;
}


/* exported interface, documented in netsurf/browser_window.h */
void browser_window_destroy(struct browser_window *bw)
{
	/* can't destoy child windows on their own */
	assert(!bw->parent);

	/* destroy */
	browser_window_destroy_internal(bw);
	free(bw);
}


/* exported interface, documented in netsurf/browser_window.h */
nserror browser_window_refresh_url_bar(struct browser_window *bw)
{
	nserror ret;
	nsurl *display_url, *url;

	assert(bw);

	if (bw->parent != NULL) {
		/* Not root window; don't set a URL in GUI URL bar */
		return NSERROR_OK;
	}

	if (bw->current_content == NULL) {
		/* no content so return about:blank */
		ret = browser_window_refresh_url_bar_internal(bw,
						corestring_nsurl_about_blank);
	} else if (bw->throbbing) {
		/* We're throbbing, so show the loading parameters url,
		 * or if there isn't one, the current parameters url
		 */
		if (bw->loading_parameters.url != NULL) {
			url = bw->loading_parameters.url;
		} else {
			url = bw->current_parameters.url;
		}
		ret = browser_window_refresh_url_bar_internal(bw, url);
	} else if (bw->frag_id == NULL) {
		if (bw->internal_nav) {
			url = bw->loading_parameters.url;
		} else {
			url = hlcache_handle_get_url(bw->current_content);
		}
		ret = browser_window_refresh_url_bar_internal(bw, url);
	} else {
		/* Combine URL and Fragment */
		if (bw->internal_nav) {
			url = bw->loading_parameters.url;
		} else {
			url = hlcache_handle_get_url(bw->current_content);
		}
		ret = nsurl_refragment(
				       url,
				       bw->frag_id, &display_url);
		if (ret == NSERROR_OK) {
			ret = browser_window_refresh_url_bar_internal(bw,
								display_url);
			nsurl_unref(display_url);
		}
	}

	return ret;
}


/* exported interface documented in netsurf/browser_window.h */
nserror
browser_window_navigate(struct browser_window *bw,
			nsurl *url,
			nsurl *referrer,
			enum browser_window_nav_flags flags,
			char *post_urlenc,
			struct fetch_multipart_data *post_multipart,
			hlcache_handle *parent)
{
	int depth = 0;
	struct browser_window *cur;
	uint32_t fetch_flags = 0;
	bool fetch_is_post = (post_urlenc != NULL || post_multipart != NULL);
	llcache_post_data post;
	hlcache_child_context child;
	nserror error;
	bool is_internal = false;
	struct browser_fetch_parameters params, *pass_params = NULL;

	assert(bw);
	assert(url);

	NSLOG(netsurf, INFO, "bw %p, url %s", bw, nsurl_access(url));

	/*
	 * determine if navigation is internal url, if so, we do not
	 * do certain things during the load.
	 */
	is_internal = is_internal_navigate_url(url);

	if (is_internal &&
	    !(flags & BW_NAVIGATE_INTERNAL)) {
		/* Internal navigation detected, but flag not set, only allow
		 * this is there's a fetch multipart
		 */
		if (post_multipart == NULL) {
			return NSERROR_NEED_DATA;
		}
		/* It *is* internal, set it as such */
		flags |= BW_NAVIGATE_INTERNAL | BW_NAVIGATE_HISTORY;
		/* If we were previously internal, don't update again */
		if (bw->internal_nav) {
			flags |= BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE;
		}
	}

	/* If we're navigating and we have a history entry and a content
	 * then update the history entry before we navigate to save our
	 * current state.  However since history navigation pre-moves
	 * the history state, we ensure that we only do this if we've not
	 * been suppressed.  In the suppressed case, the history code
	 * updates the history itself before navigating.
	 */
	if (bw->current_content != NULL &&
	    bw->history != NULL &&
	    bw->history->current != NULL &&
	    !is_internal &&
	    !(flags & BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE)) {
		browser_window_history_update(bw, bw->current_content);
	}

	/* don't allow massively nested framesets */
	for (cur = bw; cur->parent; cur = cur->parent) {
		depth++;
	}
	if (depth > FRAME_DEPTH) {
		NSLOG(netsurf, INFO, "frame depth too high.");
		return NSERROR_FRAME_DEPTH;
	}

	/* Set up retrieval parameters */
	if (!(flags & BW_NAVIGATE_UNVERIFIABLE)) {
		fetch_flags |= LLCACHE_RETRIEVE_VERIFIABLE;
	}

	if (post_multipart != NULL) {
		post.type = LLCACHE_POST_MULTIPART;
		post.data.multipart = post_multipart;
	} else if (post_urlenc != NULL) {
		post.type = LLCACHE_POST_URL_ENCODED;
		post.data.urlenc = post_urlenc;
	}

	child.charset = content_get_encoding(parent, CONTENT_ENCODING_NORMAL);
	if ((parent != NULL) && (content_get_type(parent) == CONTENT_HTML)) {
		child.quirks = content_get_quirks(parent);
	} else {
		child.quirks = false;
	}

	url = nsurl_ref(url);

	if (referrer != NULL) {
		referrer = nsurl_ref(referrer);
	}

	/* Get download out of the way */
	if ((flags & BW_NAVIGATE_DOWNLOAD) != 0) {
		error = browser_window_download(bw,
						url,
						referrer,
						fetch_flags,
						fetch_is_post,
						&post);
		nsurl_unref(url);
		if (referrer != NULL) {
			nsurl_unref(referrer);
		}
		return error;
	}

	if (bw->frag_id != NULL) {
		lwc_string_unref(bw->frag_id);
	}
	bw->frag_id = NULL;

	if (nsurl_has_component(url, NSURL_FRAGMENT)) {
		bool same_url = false;

		bw->frag_id = nsurl_get_component(url, NSURL_FRAGMENT);

		/* Compare new URL with existing one (ignoring fragments) */
		if ((bw->current_content != NULL) &&
		    (hlcache_handle_get_url(bw->current_content) != NULL)) {
			same_url = nsurl_compare(
				url,
				hlcache_handle_get_url(bw->current_content),
				NSURL_COMPLETE);
		}

		/* if we're simply moving to another ID on the same page,
		 * don't bother to fetch, just update the window.
		 */
		if ((same_url) &&
		    (fetch_is_post == false) &&
		    (nsurl_has_component(url, NSURL_QUERY) == false)) {
			nsurl_unref(url);

			if (referrer != NULL) {
				nsurl_unref(referrer);
			}

			if ((flags & BW_NAVIGATE_HISTORY) != 0) {
				browser_window_history_add(bw,
							   bw->current_content,
							   bw->frag_id);
			}

			browser_window_update(bw, false);

			if (bw->current_content != NULL) {
				browser_window_refresh_url_bar(bw);
			}
			return NSERROR_OK;
		}
	}

	browser_window_stop(bw);
	browser_window_remove_caret(bw, false);
	browser_window_destroy_children(bw);

	/* Set up the fetch parameters */
	memset(&params, 0, sizeof(params));

	params.url = nsurl_ref(url);

	if (referrer != NULL) {
		params.referrer = nsurl_ref(referrer);
	}

	params.flags = flags;

	if (post_urlenc != NULL) {
		params.post_urlenc = strdup(post_urlenc);
	}

	if (post_multipart != NULL) {
		params.post_multipart = fetch_multipart_data_clone(post_multipart);
	}

	if (parent != NULL) {
		params.parent_charset = strdup(child.charset);
		params.parent_quirks = child.quirks;
	}

	bw->internal_nav = is_internal;

	if (is_internal) {
		pass_params = &params;
	} else {
		/* At this point, we're navigating, so store the fetch parameters */
		browser_window__free_fetch_parameters(&bw->loading_parameters);
		memcpy(&bw->loading_parameters, &params, sizeof(params));
		memset(&params, 0, sizeof(params));
		pass_params = &bw->loading_parameters;
	}

	error = browser_window__navigate_internal(bw, pass_params);

	nsurl_unref(url);

	if (referrer != NULL) {
		nsurl_unref(referrer);
	}

	if (is_internal) {
		browser_window__free_fetch_parameters(&params);
	}

	return error;
}


/**
 * Internal navigation handler for normal fetches
 */
static nserror
navigate_internal_real(struct browser_window *bw,
		       struct browser_fetch_parameters *params)
{
	uint32_t fetch_flags = 0;
	bool fetch_is_post;
	llcache_post_data post;
	hlcache_child_context child;
	nserror res;
	hlcache_handle *c;

	NSLOG(netsurf, INFO, "Loading '%s'", nsurl_access(params->url));

	fetch_is_post = (params->post_urlenc != NULL || params->post_multipart != NULL);

	/* Clear SSL info for load */
	bw->loading_ssl_info.num = 0;

	/* Set up retrieval parameters */
	if (!(params->flags & BW_NAVIGATE_UNVERIFIABLE)) {
		fetch_flags |= LLCACHE_RETRIEVE_VERIFIABLE;
	}

	if (params->post_multipart != NULL) {
		post.type = LLCACHE_POST_MULTIPART;
		post.data.multipart = params->post_multipart;
	} else if (params->post_urlenc != NULL) {
		post.type = LLCACHE_POST_URL_ENCODED;
		post.data.urlenc = params->post_urlenc;
	}

	if (params->parent_charset != NULL) {
		child.charset = params->parent_charset;
		child.quirks = params->parent_quirks;
	}

	browser_window_set_status(bw, messages_get("Loading"));
	bw->history_add = (params->flags & BW_NAVIGATE_HISTORY);

	/* Verifiable fetches may trigger a download */
	if (!(params->flags & BW_NAVIGATE_UNVERIFIABLE)) {
		fetch_flags |= HLCACHE_RETRIEVE_MAY_DOWNLOAD;
	}

	res = hlcache_handle_retrieve(params->url,
				      fetch_flags | HLCACHE_RETRIEVE_SNIFF_TYPE,
				      params->referrer,
				      fetch_is_post ? &post : NULL,
				      browser_window_callback,
				      bw,
				      params->parent_charset != NULL ? &child : NULL,
				      CONTENT_ANY,
				      &c);

	switch (res) {
	case NSERROR_OK:
		bw->loading_content = c;
		browser_window_start_throbber(bw);
		if (bw->window != NULL) {
			guit->window->set_icon(bw->window, NULL);
		}
		if (bw->internal_nav == false) {
			res = browser_window_refresh_url_bar_internal(bw,
								      params->url);
		}
		break;

	case NSERROR_NO_FETCH_HANDLER: /* no handler for this type */
		/** \todo does this always try and download even
		 * unverifiable content?
		 */
		res = guit->misc->launch_url(params->url);
		break;

	default: /* report error to user */
		browser_window_set_status(bw, messages_get_errorcode(res));
		break;

	}

	/* Record time */
	nsu_getmonotonic_ms(&bw->last_action);

	return res;
}


/**
 * Internal navigation handler for the authentication query handler
 *
 * If the parameters indicate we're processing a *response* from the handler
 * then we deal with that, otherwise we pass it on to the about: handler
 */
static nserror
navigate_internal_query_auth(struct browser_window *bw,
			     struct browser_fetch_parameters *params)
{
	char *userpass = NULL;
	const char *username, *password, *realm, *siteurl;
	nsurl *sitensurl;
	nserror res;
	bool is_login = false, is_cancel = false;

	assert(params->post_multipart != NULL);

	is_login = fetch_multipart_data_find(params->post_multipart, "login") != NULL;
	is_cancel = fetch_multipart_data_find(params->post_multipart, "cancel") != NULL;

	if (!(is_login || is_cancel)) {
		/* This is a request, so pass it on */
		return navigate_internal_real(bw, params);
	}

	if (is_cancel) {
		/* We're processing a cancel, do a rough-and-ready nav to
		 * about:blank
		 */
		browser_window__free_fetch_parameters(&bw->loading_parameters);
		bw->loading_parameters.url = nsurl_ref(corestring_nsurl_about_blank);
		bw->loading_parameters.flags = BW_NAVIGATE_NO_TERMINAL_HISTORY_UPDATE | BW_NAVIGATE_INTERNAL;
		bw->internal_nav = true;
		return browser_window__navigate_internal(bw, &bw->loading_parameters);
	}

	/* We're processing a "login" attempt from the form */

	/* Retrieve the data */
	username = fetch_multipart_data_find(params->post_multipart, "username");
	password = fetch_multipart_data_find(params->post_multipart, "password");
	realm = fetch_multipart_data_find(params->post_multipart, "realm");
	siteurl = fetch_multipart_data_find(params->post_multipart, "siteurl");

	if (username == NULL || password == NULL ||
	    realm == NULL || siteurl == NULL) {
		/* Bad inputs, simply fail */
		return NSERROR_INVALID;
	}

	/* Parse the URL */
	res = nsurl_create(siteurl, &sitensurl);
	if (res != NSERROR_OK) {
		return res;
	}

	/* Construct the username/password */
	res = browser_window__build_userpass(username, password, &userpass);
	if (res != NSERROR_OK) {
		nsurl_unref(sitensurl);
		return res;
	}

	/* And let urldb know */
	urldb_set_auth_details(sitensurl, realm, userpass);

	/* Clean up */
	free(userpass);
	nsurl_unref(sitensurl);

	/* Finally navigate to the original loading parameters */
	bw->internal_nav = false;
	return navigate_internal_real(bw, &bw->loading_parameters);
}


/**
 * Internal navigation handler for the SSL/privacy query page.
 *
 * If the parameters indicate we're processing a *response* from the handler
 * then we deal with that, otherwise we pass it on to the about: handler
 */
static nserror
navigate_internal_query_ssl(struct browser_window *bw,
			    struct browser_fetch_parameters *params)
{
	bool is_proceed = false, is_back = false;

	assert(params->post_multipart != NULL);

	is_proceed = fetch_multipart_data_find(params->post_multipart, "proceed") != NULL;
	is_back = fetch_multipart_data_find(params->post_multipart, "back") != NULL;

	if (!(is_proceed || is_back)) {
		/* This is a request, so pass it on */
		return navigate_internal_real(bw, params);
	}

	return browser_window__handle_ssl_query_response(is_proceed, bw);
}


/**
 * Internal navigation handler for the timeout query page.
 *
 * If the parameters indicate we're processing a *response* from the handler
 * then we deal with that, otherwise we pass it on to the about: handler
 */
static nserror
navigate_internal_query_timeout(struct browser_window *bw,
				struct browser_fetch_parameters *params)
{
	bool is_retry = false, is_back = false;

	NSLOG(netsurf, INFO, "bw:%p params:%p", bw, params);

	assert(params->post_multipart != NULL);

	is_retry = fetch_multipart_data_find(params->post_multipart, "retry") != NULL;
	is_back = fetch_multipart_data_find(params->post_multipart, "back") != NULL;

	if (is_back) {
		/* do a rough-and-ready nav to the old 'current'
		 * parameters, with any post data stripped away
		 */
		return browser_window__reload_current_parameters(bw);
	}

	if (is_retry) {
		/* Finally navigate to the original loading parameters */
		bw->internal_nav = false;
		return navigate_internal_real(bw, &bw->loading_parameters);
	}

	return navigate_internal_real(bw, params);
}


/**
 * Internal navigation handler for the fetch error query page.
 *
 * If the parameters indicate we're processing a *response* from the handler
 * then we deal with that, otherwise we pass it on to the about: handler
 */
static nserror
navigate_internal_query_fetcherror(struct browser_window *bw,
				   struct browser_fetch_parameters *params)
{
	bool is_retry = false, is_back = false;

	NSLOG(netsurf, INFO, "bw:%p params:%p", bw, params);

	assert(params->post_multipart != NULL);

	is_retry = fetch_multipart_data_find(params->post_multipart, "retry") != NULL;
	is_back = fetch_multipart_data_find(params->post_multipart, "back") != NULL;

	if (is_back) {
		/* do a rough-and-ready nav to the old 'current'
		 * parameters, with any post data stripped away
		 */
		return browser_window__reload_current_parameters(bw);
	}

	if (is_retry) {
		/* Finally navigate to the original loading parameters */
		bw->internal_nav = false;
		return navigate_internal_real(bw, &bw->loading_parameters);
	}

	return navigate_internal_real(bw, params);
}


/**
 * dispatch to internal query handlers or normal navigation
 *
 * Here we determine if we're navigating to an internal query URI and
 * if so, what we need to do about it.
 *
 * \note these check must match those in is_internal_navigate_url()
 *
 * If we're not, then we just move on to the real navigate.
 */
nserror
browser_window__navigate_internal(struct browser_window *bw,
				  struct browser_fetch_parameters *params)
{
	lwc_string *scheme, *path;

	/* All our special URIs are in the about: scheme */
	scheme = nsurl_get_component(params->url, NSURL_SCHEME);
	if (scheme != corestring_lwc_about) {
		lwc_string_unref(scheme);
		goto normal_fetch;
	}
	lwc_string_unref(scheme);

	/* Is it the auth query handler? */
	path = nsurl_get_component(params->url, NSURL_PATH);
	if (path == corestring_lwc_query_auth) {
		lwc_string_unref(path);
		return navigate_internal_query_auth(bw, params);
	}
	if (path == corestring_lwc_query_ssl) {
		lwc_string_unref(path);
		return navigate_internal_query_ssl(bw, params);
	}
	if (path == corestring_lwc_query_timeout) {
		lwc_string_unref(path);
		return navigate_internal_query_timeout(bw, params);
	}
	if (path == corestring_lwc_query_fetcherror) {
		lwc_string_unref(path);
		return navigate_internal_query_fetcherror(bw, params);
	}
	lwc_string_unref(path);

	/* Fall through to a normal about: fetch */

 normal_fetch:
	return navigate_internal_real(bw, params);
}


/* Exported interface, documented in netsurf/browser_window.h */
bool browser_window_up_available(struct browser_window *bw)
{
	bool result = false;

	if (bw != NULL && bw->current_content != NULL) {
		nsurl *parent;
		nserror	err;
		err = nsurl_parent(hlcache_handle_get_url(bw->current_content),
				   &parent);
		if (err == NSERROR_OK) {
			result = nsurl_compare(hlcache_handle_get_url(
						      bw->current_content),
					       parent,
					       NSURL_COMPLETE) == false;
			nsurl_unref(parent);
		}
	}

	return result;
}


/* Exported interface, documented in netsurf/browser_window.h */
nserror browser_window_navigate_up(struct browser_window *bw, bool new_window)
{
	nsurl *current, *parent;
	nserror err;

	if (bw == NULL)
		return NSERROR_BAD_PARAMETER;

	current = browser_window_access_url(bw);

	err = nsurl_parent(current, &parent);
	if (err != NSERROR_OK) {
		return err;
	}

	if (nsurl_compare(current, parent, NSURL_COMPLETE) == true) {
		/* Can't go up to parent from here */
		nsurl_unref(parent);
		return NSERROR_OK;
	}

	if (new_window) {
		err = browser_window_create(BW_CREATE_CLONE,
					    parent, NULL, bw, NULL);
	} else {
		err = browser_window_navigate(bw, parent, NULL,
					      BW_NAVIGATE_HISTORY,
					      NULL, NULL, NULL);
	}

	nsurl_unref(parent);
	return err;
}


/* Exported interface, documented in include/netsurf/browser_window.h */
nsurl* browser_window_access_url(struct browser_window *bw)
{
	assert(bw != NULL);

	if (bw->current_content != NULL) {
		return hlcache_handle_get_url(bw->current_content);

	} else if (bw->loading_content != NULL) {
		/* TODO: should we return this? */
		return hlcache_handle_get_url(bw->loading_content);
	}

	return corestring_nsurl_about_blank;
}


/* Exported interface, documented in include/netsurf/browser_window.h */
nserror
browser_window_get_url(struct browser_window *bw, bool fragment,nsurl** url_out)
{
	nserror err;
	nsurl *url;

	assert(bw != NULL);

	if (!fragment || bw->frag_id == NULL || bw->loading_content != NULL) {
		/* If there's a loading content, then the bw->frag_id will have
		 * been trampled, possibly with a new frag_id, but we will
		 * still be returning the current URL, so in this edge case
		 * we just drop any fragment. */
		url = nsurl_ref(browser_window_access_url(bw));

	} else {
		err = nsurl_refragment(browser_window_access_url(bw),
				       bw->frag_id, &url);
		if (err != NSERROR_OK) {
			return err;
		}
	}

	*url_out = url;
	return NSERROR_OK;
}


/* Exported interface, documented in netsurf/browser_window.h */
const char* browser_window_get_title(struct browser_window *bw)
{
	assert(bw != NULL);

	if (bw->current_content != NULL) {
		return content_get_title(bw->current_content);
	}

	/* no content so return about:blank */
	return nsurl_access(corestring_nsurl_about_blank);
}


/* Exported interface, documented in netsurf/browser_window.h */
struct history * browser_window_get_history(struct browser_window *bw)
{
	assert(bw != NULL);

	return bw->history;
}


/* Exported interface, documented in netsurf/browser_window.h */
bool browser_window_has_content(struct browser_window *bw)
{
	assert(bw != NULL);

	if (bw->current_content == NULL) {
		return false;
	}

	return true;
}


/* Exported interface, documented in netsurf/browser_window.h */
struct hlcache_handle *browser_window_get_content(struct browser_window *bw)
{
	return bw->current_content;
}


/* Exported interface, documented in netsurf/browser_window.h */
nserror browser_window_get_extents(struct browser_window *bw, bool scaled,
				   int *width, int *height)
{
	assert(bw != NULL);

	if (bw->current_content == NULL) {
		*width = 0;
		*height = 0;
		return NSERROR_BAD_CONTENT;
	}

	*width = content_get_width(bw->current_content);
	*height = content_get_height(bw->current_content);

	if (scaled) {
		*width *= bw->scale;
		*height *= bw->scale;
	}

	return NSERROR_OK;
}


/* exported internal interface, documented in desktop/browser_private.h */
nserror
browser_window_get_dimensions(struct browser_window *bw,
			      int *width,
			      int *height)
{
	nserror res;
	assert(bw);

	if (bw->window == NULL) {
		/* Core managed browser window */
		*width = bw->width;
		*height = bw->height;
		res = NSERROR_OK;
	} else {
		/* Front end window */
		res = guit->window->get_dimensions(bw->window, width, height);
	}
	return res;
}


/* Exported interface, documented in netsurf/browser_window.h */
void
browser_window_set_dimensions(struct browser_window *bw, int width, int height)
{
	assert(bw);

	if (bw->window == NULL) {
		/* Core managed browser window */
		bw->width = width;
		bw->height = height;
	} else {
		NSLOG(netsurf, INFO,
		      "Asked to set dimensions of front end window.");
		assert(0);
	}
}


/* Exported interface, documented in netsurf/browser_window.h */
void browser_window_update(struct browser_window *bw, bool scroll_to_top)
{
	static const struct rect zrect = {
		.x0 = 0,
		.y0 = 0,
		.x1 = 0,
		.y1 = 0
	};

	if (bw->current_content == NULL) {
		return;
	}

	switch (bw->browser_window_type) {

	case BROWSER_WINDOW_NORMAL:
		/* Root browser window, constituting a front end window/tab */
		guit->window->set_title(bw->window,
					content_get_title(bw->current_content));

		browser_window_update_extent(bw);

		/* if frag_id exists, then try to scroll to it */
		/** @todo don't do this if the user has scrolled */
		if (!frag_scroll(bw)) {
			if (scroll_to_top) {
				browser_window_set_scroll(bw, &zrect);
			}
		}

		guit->window->invalidate(bw->window, NULL);

		break;

	case BROWSER_WINDOW_IFRAME:
		/* Internal iframe browser window */
		assert(bw->parent != NULL);
		assert(bw->parent->current_content != NULL);

		browser_window_update_extent(bw);

		if (scroll_to_top) {
			browser_window_set_scroll(bw, &zrect);
		}

		/* if frag_id exists, then try to scroll to it */
		/** @todo don't do this if the user has scrolled */
		frag_scroll(bw);

		html_redraw_a_box(bw->parent->current_content, bw->box);
		break;

	case BROWSER_WINDOW_FRAME:
		{
			struct rect rect;
			browser_window_update_extent(bw);

			if (scroll_to_top) {
				browser_window_set_scroll(bw, &zrect);
			}

			/* if frag_id exists, then try to scroll to it */
			/** @todo don't do this if the user has scrolled */
			frag_scroll(bw);

			rect.x0 = scrollbar_get_offset(bw->scroll_x);
			rect.y0 = scrollbar_get_offset(bw->scroll_y);
			rect.x1 = rect.x0 + bw->width;
			rect.y1 = rect.y0 + bw->height;

			browser_window_update_box(bw, &rect);
		}
		break;

	default:
	case BROWSER_WINDOW_FRAMESET:
		/* Nothing to do */
		break;
	}
}


/* Exported interface, documented in netsurf/browser_window.h */
void browser_window_update_box(struct browser_window *bw, struct rect *rect)
{
	int pos_x;
	int pos_y;
	struct browser_window *top = bw;

	assert(bw);

	if (bw->window == NULL) {
		/* Core managed browser window */
		browser_window_get_position(bw, true, &pos_x, &pos_y);

		top = browser_window_get_root(bw);

		rect->x0 += pos_x / bw->scale;
		rect->y0 += pos_y / bw->scale;
		rect->x1 += pos_x / bw->scale;
		rect->y1 += pos_y / bw->scale;
	}

	rect->x0 *= top->scale;
	rect->y0 *= top->scale;
	rect->x1 *= top->scale;
	rect->y1 *= top->scale;

	guit->window->invalidate(top->window, rect);
}


/* Exported interface, documented in netsurf/browser_window.h */
void browser_window_stop(struct browser_window *bw)
{
	int children, index;

	if (bw->loading_content != NULL) {
		hlcache_handle_abort(bw->loading_content);
		hlcache_handle_release(bw->loading_content);
		bw->loading_content = NULL;
	}

	if (bw->current_content != NULL &&
	    content_get_status(bw->current_content) != CONTENT_STATUS_DONE) {
		nserror error;
		assert(content_get_status(bw->current_content) ==
		       CONTENT_STATUS_READY);
		error = hlcache_handle_abort(bw->current_content);
		assert(error == NSERROR_OK);
	}

	guit->misc->schedule(-1, browser_window_refresh, bw);

	if (bw->children) {
		children = bw->rows * bw->cols;
		for (index = 0; index < children; index++)
			browser_window_stop(&bw->children[index]);
	}
	if (bw->iframes) {
		children = bw->iframe_count;
		for (index = 0; index < children; index++)
			browser_window_stop(&bw->iframes[index]);
	}

	if (bw->current_content != NULL) {
		browser_window_refresh_url_bar(bw);
	}

	browser_window_stop_throbber(bw);
}


/* Exported interface, documented in netsurf/browser_window.h */
nserror browser_window_reload(struct browser_window *bw, bool all)
{
	hlcache_handle *c;
	unsigned int i;
	struct nsurl *reload_url;

	if ((bw->current_content) == NULL ||
	    (bw->loading_content) != NULL) {
		return NSERROR_INVALID;
	}

	if (all && content_get_type(bw->current_content) == CONTENT_HTML) {
		struct html_stylesheet *sheets;
		struct content_html_object *object;
		unsigned int count;

		c = bw->current_content;

		/* invalidate objects */
		object = html_get_objects(c, &count);

		for (; object != NULL; object = object->next) {
			if (object->content != NULL)
				content_invalidate_reuse_data(object->content);
		}

		/* invalidate stylesheets */
		sheets = html_get_stylesheets(c, &count);

		for (i = STYLESHEET_START; i != count; i++) {
			if (sheets[i].sheet != NULL) {
				content_invalidate_reuse_data(sheets[i].sheet);
			}
		}
	}

	content_invalidate_reuse_data(bw->current_content);

	reload_url = hlcache_handle_get_url(bw->current_content);

	return browser_window_navigate(bw,
				       reload_url,
				       NULL,
				       BW_NAVIGATE_NONE,
				       NULL,
				       NULL,
				       NULL);
}


/* Exported interface, documented in netsurf/browser_window.h */
void browser_window_set_status(struct browser_window *bw, const char *text)
{
	int text_len;
	/* find topmost window */
	while (bw->parent)
		bw = bw->parent;

	if ((bw->status.text != NULL) &&
	    (strcmp(text, bw->status.text) == 0)) {
		/* status text is unchanged */
		bw->status.match++;
		return;
	}

	/* status text is changed */

	text_len = strlen(text);

	if ((bw->status.text == NULL) || (bw->status.text_len < text_len)) {
		/* no current string allocation or it is not long enough */
		free(bw->status.text);
		bw->status.text = strdup(text);
		bw->status.text_len = text_len;
	} else {
		/* current allocation has enough space */
		memcpy(bw->status.text, text, text_len + 1);
	}

	bw->status.miss++;
	guit->window->set_status(bw->window, bw->status.text);
}


/* Exported interface, documented in netsurf/browser_window.h */
void browser_window_set_pointer(struct browser_window *bw,
				browser_pointer_shape shape)
{
	struct browser_window *root = browser_window_get_root(bw);
	gui_pointer_shape gui_shape;
	bool loading;
	uint64_t ms_now;

	assert(root);
	assert(root->window);

	loading = ((bw->loading_content != NULL) ||
		   ((bw->current_content != NULL) &&
		    (content_get_status(bw->current_content) == CONTENT_STATUS_READY)));

	nsu_getmonotonic_ms(&ms_now);

	if (loading && ((ms_now - bw->last_action) < 1000)) {
		/* If loading and less than 1 second since last link followed,
		 * force progress indicator pointer */
		gui_shape = GUI_POINTER_PROGRESS;

	} else if (shape == BROWSER_POINTER_AUTO) {
		/* Up to browser window to decide */
		if (loading) {
			gui_shape = GUI_POINTER_PROGRESS;
		} else {
			gui_shape = GUI_POINTER_DEFAULT;
		}

	} else {
		/* Use what we were told */
		gui_shape = (gui_pointer_shape)shape;
	}

	guit->window->set_pointer(root->window, gui_shape);
}


/* exported function documented in netsurf/browser_window.h */
nserror browser_window_schedule_reformat(struct browser_window *bw)
{
	if (bw->window == NULL) {
		return NSERROR_BAD_PARAMETER;
	}

	return guit->misc->schedule(0, scheduled_reformat, bw);
}


/* exported function documented in netsurf/browser_window.h */
void
browser_window_reformat(struct browser_window *bw,
			bool background,
			int width,
			int height)
{
	hlcache_handle *c = bw->current_content;

	if (c == NULL)
		return;

	if (bw->browser_window_type != BROWSER_WINDOW_IFRAME) {
		/* Iframe dimensions are already scaled in parent's layout */
		width  /= bw->scale;
		height /= bw->scale;
	}

	if (bw->window == NULL) {
		/* Core managed browser window; subtract scrollbar width */
		width  -= bw->scroll_y ? SCROLLBAR_WIDTH : 0;
		height -= bw->scroll_x ? SCROLLBAR_WIDTH : 0;

		width  = width  > 0 ? width  : 0;
		height = height > 0 ? height : 0;
	}

	content_reformat(c, background, width, height);
}


/* exported interface documented in netsurf/browser_window.h */
nserror
browser_window_set_scale(struct browser_window *bw, float scale, bool absolute)
{
	nserror res;

	/* get top browser window */
	while (bw->parent) {
		bw = bw->parent;
	}

	if (!absolute) {
		/* snap small values around 1.0 */
		if ((scale + bw->scale) > (1.01 - scale) &&
		    (scale + bw->scale) < (0.99 + scale)) {
			scale = 1.0;
		} else {
			scale += bw->scale;
		}
	}

	/* clamp range between 0.1 and 10 (10% and 1000%) */
	if (scale < SCALE_MINIMUM) {
		scale = SCALE_MINIMUM;
	} else if (scale > SCALE_MAXIMUM) {
		scale = SCALE_MAXIMUM;
	}

	res = browser_window_set_scale_internal(bw, scale);
	if (res == NSERROR_OK) {
		browser_window_recalculate_frameset(bw);
	}

	return res;
}


/* exported interface documented in netsurf/browser_window.h */
float browser_window_get_scale(struct browser_window *bw)
{
	if (bw == NULL) {
		return 1.0;
	}

	return bw->scale;
}


/* exported interface documented in netsurf/browser_window.h */
struct browser_window *
browser_window_find_target(struct browser_window *bw,
			   const char *target,
			   browser_mouse_state mouse)
{
	struct browser_window *bw_target;
	struct browser_window *top;
	hlcache_handle *c;
	int rdepth;
	nserror error;

	/* use the base target if we don't have one */
	c = bw->current_content;
	if (target == NULL &&
	    c != NULL &&
	    content_get_type(c) == CONTENT_HTML) {
		target = html_get_base_target(c);
	}
	if (target == NULL) {
		target = TARGET_SELF;
	}

	/* allow the simple case of target="_blank" to be ignored if requested
	 */
	if ((!(mouse & BROWSER_MOUSE_CLICK_2)) &&
	    (!((mouse & BROWSER_MOUSE_CLICK_2) &&
	       (mouse & BROWSER_MOUSE_MOD_2))) &&
	    (!nsoption_bool(target_blank))) {
		/* not a mouse button 2 click
		 * not a mouse button 1 click with ctrl pressed
		 * configured to ignore target="_blank" */
		if ((target == TARGET_BLANK) || (!strcasecmp(target, "_blank")))
			return bw;
	}

	/* handle reserved keywords */
	if (((nsoption_bool(button_2_tab)) &&
	     (mouse & BROWSER_MOUSE_CLICK_2))||
	    ((!nsoption_bool(button_2_tab)) &&
	     ((mouse & BROWSER_MOUSE_CLICK_1) &&
	      (mouse & BROWSER_MOUSE_MOD_2))) ||
	    ((nsoption_bool(button_2_tab)) &&
	     ((target == TARGET_BLANK) ||
	      (!strcasecmp(target, "_blank"))))) {
		/* open in new tab if:
		 * - button_2 opens in new tab and button_2 was pressed
		 * OR
		 * - button_2 doesn't open in new tabs and button_1 was
		 *   pressed with ctrl held
		 * OR
		 * - button_2 opens in new tab and the link target is "_blank"
		 */
		error = browser_window_create(BW_CREATE_TAB |
					      BW_CREATE_HISTORY |
					      BW_CREATE_CLONE,
					      NULL,
					      NULL,
					      bw,
					      &bw_target);
		if (error != NSERROR_OK) {
			return bw;
		}
		return bw_target;
	} else if (((!nsoption_bool(button_2_tab)) &&
		    (mouse & BROWSER_MOUSE_CLICK_2)) ||
		   ((nsoption_bool(button_2_tab)) &&
		    ((mouse & BROWSER_MOUSE_CLICK_1) &&
		     (mouse & BROWSER_MOUSE_MOD_2))) ||
		   ((!nsoption_bool(button_2_tab)) &&
		    ((target == TARGET_BLANK) ||
		     (!strcasecmp(target, "_blank"))))) {
		/* open in new window if:
		 * - button_2 doesn't open in new tabs and button_2 was pressed
		 * OR
		 * - button_2 opens in new tab and button_1 was pressed with
		 *   ctrl held
		 * OR
		 * - button_2 doesn't open in new tabs and the link target is
		 *   "_blank"
		 */
		error = browser_window_create(BW_CREATE_HISTORY |
					      BW_CREATE_CLONE,
					      NULL,
					      NULL,
					      bw,
					      &bw_target);
		if (error != NSERROR_OK) {
			return bw;
		}
		return bw_target;
	} else if ((target == TARGET_SELF) || (!strcasecmp(target, "_self"))) {
		return bw;
	} else if ((target == TARGET_PARENT) ||
		   (!strcasecmp(target, "_parent"))) {
		if (bw->parent)
			return bw->parent;
		return bw;
	} else if ((target == TARGET_TOP) || (!strcasecmp(target, "_top"))) {
		while (bw->parent)
			bw = bw->parent;
		return bw;
	}

	/* find frame according to B.8, ie using the following priorities:
	 *
	 *  1) current frame
	 *  2) closest to front
	 */
	rdepth = -1;
	bw_target = NULL;
	for (top = bw; top->parent; top = top->parent);
	browser_window_find_target_internal(top, target, 0, bw, &rdepth,
					    &bw_target);
	if (bw_target)
		return bw_target;

	/* we require a new window using the target name */
	if (!nsoption_bool(target_blank))
		return bw;

	error = browser_window_create(BW_CREATE_CLONE | BW_CREATE_HISTORY,
				      NULL,
				      NULL,
				      bw,
				      &bw_target);
	if (error != NSERROR_OK) {
		return bw;
	}

	/* frame names should begin with an alphabetic character (a-z,A-Z),
	 * however in practice you get things such as '_new' and '2left'. The
	 * only real effect this has is when giving out names as it can be
	 * assumed that an author intended '_new' to create a new nameless
	 * window (ie '_blank') whereas in the case of '2left' the intention
	 * was for a new named window. As such we merely special case windows
	 * that begin with an underscore. */
	if (target[0] != '_') {
		bw_target->name = strdup(target);
	}
	return bw_target;
}


/* exported interface documented in netsurf/browser_window.h */
void
browser_window_mouse_track(struct browser_window *bw,
			   browser_mouse_state mouse,
			   int x, int y)
{
	browser_window_mouse_track_internal(bw,
					    mouse,
					    x / bw->scale,
					    y / bw->scale);
}

/* exported interface documented in netsurf/browser_window.h */
void
browser_window_mouse_click(struct browser_window *bw,
			   browser_mouse_state mouse,
			   int x, int y)
{
	browser_window_mouse_click_internal(bw,
					    mouse,
					    x / bw->scale,
					    y / bw->scale);
}


/* exported interface documented in netsurf/browser_window.h */
void browser_window_page_drag_start(struct browser_window *bw, int x, int y)
{
	assert(bw != NULL);

	browser_window_set_drag_type(bw, DRAGGING_PAGE_SCROLL, NULL);

	bw->drag.start_x = x;
	bw->drag.start_y = y;

	if (bw->window != NULL) {
		/* Front end window */
		guit->window->get_scroll(bw->window,
					 &bw->drag.start_scroll_x,
					 &bw->drag.start_scroll_y);

		guit->window->event(bw->window, GW_EVENT_SCROLL_START);
	} else {
		/* Core managed browser window */
		bw->drag.start_scroll_x = scrollbar_get_offset(bw->scroll_x);
		bw->drag.start_scroll_y = scrollbar_get_offset(bw->scroll_y);
	}
}


/* exported interface documented in netsurf/browser_window.h */
bool browser_window_back_available(struct browser_window *bw)
{
	if (bw != NULL && bw->internal_nav) {
		/* Internal nav, back is possible */
		return true;
	}
	return (bw && bw->history && browser_window_history_back_available(bw));
}


/* exported interface documented in netsurf/browser_window.h */
bool browser_window_forward_available(struct browser_window *bw)
{
	return (bw && bw->history && browser_window_history_forward_available(bw));
}

/* exported interface documented in netsurf/browser_window.h */
bool browser_window_reload_available(struct browser_window *bw)
{
	return (bw && bw->current_content && !bw->loading_content);
}


/* exported interface documented in netsurf/browser_window.h */
bool browser_window_stop_available(struct browser_window *bw)
{
	return (bw && (bw->loading_content ||
		       (bw->current_content &&
			(content_get_status(bw->current_content) !=
			 CONTENT_STATUS_DONE))));
}

/* exported interface documented in netsurf/browser_window.h */
bool
browser_window_exec(struct browser_window *bw, const char *src, size_t srclen)
{
	assert(bw != NULL);

	if (!bw->current_content) {
		NSLOG(netsurf, DEEPDEBUG, "Unable to exec, no content");
		return false;
	}

	if (content_get_status(bw->current_content) != CONTENT_STATUS_DONE) {
		NSLOG(netsurf, DEEPDEBUG, "Unable to exec, content not done");
		return false;
	}

	/* Okay it should be safe, forward the request through to the content
	 * itself.  Only HTML contents currently support executing code
	 */
	return content_exec(bw->current_content, src, srclen);
}


/* exported interface documented in browser_window.h */
nserror
browser_window_console_log(struct browser_window *bw,
			   browser_window_console_source src,
			   const char *msg,
			   size_t msglen,
			   browser_window_console_flags flags)
{
	browser_window_console_flags log_level = flags & BW_CS_FLAG_LEVEL_MASK;
	struct browser_window *root = browser_window_get_root(bw);

	assert(msg != NULL);
	/* We don't assert msglen > 0, if someone wants to log a real empty
	 * string then we won't stop them.  It does sometimes happen from
	 * JavaScript for example.
	 */

	/* bw is the target of the log, but root is where we log it */

	NSLOG(netsurf, DEEPDEBUG, "Logging message in %p targetted at %p", root, bw);
	NSLOG(netsurf, DEEPDEBUG, "Log came from %s",
	      ((src == BW_CS_INPUT) ? "user input" :
	       (src == BW_CS_SCRIPT_ERROR) ? "script error" :
	       (src == BW_CS_SCRIPT_CONSOLE) ? "script console" :
	       "unknown input location"));

	switch (log_level) {
	case BW_CS_FLAG_LEVEL_DEBUG:
		NSLOG(netsurf, DEBUG, "%.*s", (int)msglen, msg);
		break;
	case BW_CS_FLAG_LEVEL_LOG:
		NSLOG(netsurf, VERBOSE, "%.*s", (int)msglen, msg);
		break;
	case BW_CS_FLAG_LEVEL_INFO:
		NSLOG(netsurf, INFO, "%.*s", (int)msglen, msg);
		break;
	case BW_CS_FLAG_LEVEL_WARN:
		NSLOG(netsurf, WARNING, "%.*s", (int)msglen, msg);
		break;
	case BW_CS_FLAG_LEVEL_ERROR:
		NSLOG(netsurf, ERROR, "%.*s", (int)msglen, msg);
		break;
	default:
		/* Unreachable */
		break;
	}

	guit->window->console_log(root->window, src, msg, msglen, flags);

	return NSERROR_OK;
}


/* Exported interface, documented in browser_private.h */
nserror
browser_window__reload_current_parameters(struct browser_window *bw)
{
	assert(bw != NULL);

	if (bw->current_parameters.post_urlenc != NULL) {
		free(bw->current_parameters.post_urlenc);
		bw->current_parameters.post_urlenc = NULL;
	}

	if (bw->current_parameters.post_multipart != NULL) {
		fetch_multipart_data_destroy(bw->current_parameters.post_multipart);
		bw->current_parameters.post_multipart = NULL;
	}

	if (bw->current_parameters.url == NULL) {
		/* We have never navigated so go to about:blank */
		bw->current_parameters.url = nsurl_ref(corestring_nsurl_about_blank);
	}

	bw->current_parameters.flags &= ~BW_NAVIGATE_HISTORY;
	bw->internal_nav = false;

	browser_window__free_fetch_parameters(&bw->loading_parameters);
	memcpy(&bw->loading_parameters, &bw->current_parameters, sizeof(bw->loading_parameters));
	memset(&bw->current_parameters, 0, sizeof(bw->current_parameters));
	return browser_window__navigate_internal(bw, &bw->loading_parameters);
}

/* Exported interface, documented in browser_window.h */
browser_window_page_info_state browser_window_get_page_info_state(
	struct browser_window *bw)
{
	lwc_string *scheme;
	bool match;

	assert(bw != NULL);

	/* Do we have any content?  If not -- UNKNOWN */
	if (bw->current_content == NULL) {
		return PAGE_STATE_UNKNOWN;
	}

	scheme = nsurl_get_component(
		hlcache_handle_get_url(bw->current_content), NSURL_SCHEME);

	/* Is this an internal scheme? */
	if ((lwc_string_isequal(scheme, corestring_lwc_about,
				&match) == lwc_error_ok &&
	     (match == true)) ||
	    (lwc_string_isequal(scheme, corestring_lwc_data,
				&match) == lwc_error_ok &&
	     (match == true)) ||
	    (lwc_string_isequal(scheme, corestring_lwc_resource,
				&match) == lwc_error_ok &&
	     (match == true))) {
		lwc_string_unref(scheme);
		return PAGE_STATE_INTERNAL;
	}

	/* Is this file:/// ? */
	if (lwc_string_isequal(scheme, corestring_lwc_file,
			       &match) == lwc_error_ok &&
	    match == true) {
		lwc_string_unref(scheme);
		return PAGE_STATE_LOCAL;
	}

	/* If not https, from here on down that'd be insecure */
	if ((lwc_string_isequal(scheme, corestring_lwc_https,
			&match) == lwc_error_ok &&
			(match == false))) {
		/* Some remote content, not https, therefore insecure */
		lwc_string_unref(scheme);
		return PAGE_STATE_INSECURE;
	}

	lwc_string_unref(scheme);

	/* Did we have to override this SSL setting? */
	if (urldb_get_cert_permissions(bw->current_parameters.url)) {
		return PAGE_STATE_SECURE_OVERRIDE;
	}

	/* If we've seen insecure content internally then we need to say so */
	if (content_saw_insecure_objects(bw->current_content)) {
		return PAGE_STATE_SECURE_ISSUES;
	}

	/* All is well, return secure state */
	return PAGE_STATE_SECURE;
}

/* Exported interface, documented in browser_window.h */
nserror browser_window_get_ssl_chain(struct browser_window *bw, size_t *num,
				     struct ssl_cert_info **chain)
{
	assert(bw != NULL);

	if (bw->current_ssl_info.num == 0) {
		return NSERROR_NOT_FOUND;
	}

	*num = bw->current_ssl_info.num;
	*chain = &(bw->current_ssl_info.certs[0]);

	return NSERROR_OK;
}