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

//! The `Constellation`, Servo's Grand Central Station
//!
//! The constellation tracks all information kept globally by the
//! browser engine, which includes:
//!
//! * The set of all `EventLoop` objects. Each event loop is
//!   the constellation's view of a script thread. The constellation
//!   interacts with a script thread by message-passing.
//!
//! * The set of all `Pipeline` objects.  Each pipeline gives the
//!   constellation's view of a `Window`, with its script thread and
//!   layout.  Pipelines may share script threads.
//!
//! * The set of all `BrowsingContext` objects. Each browsing context
//!   gives the constellation's view of a `WindowProxy`.
//!   Each browsing context stores an independent
//!   session history, created by navigation. The session
//!   history can be traversed, for example by the back and forwards UI,
//!   so each session history maintains a list of past and future pipelines,
//!   as well as the current active pipeline.
//!
//! There are two kinds of browsing context: top-level ones (for
//! example tabs in a browser UI), and nested ones (typically caused
//! by `iframe` elements). Browsing contexts have a hierarchy
//! (typically caused by `iframe`s containing `iframe`s), giving rise
//! to a forest whose roots are top-level browsing context.  The logical
//! relationship between these types is:
//!
//! ```text
//! +------------+                      +------------+                 +---------+
//! |  Browsing  | ------parent?------> |  Pipeline  | --event_loop--> |  Event  |
//! |  Context   | ------current------> |            |                 |  Loop   |
//! |            | ------prev*--------> |            | <---pipeline*-- |         |
//! |            | ------next*--------> |            |                 +---------+
//! |            |                      |            |
//! |            | <-top_level--------- |            |
//! |            | <-browsing_context-- |            |
//! +------------+                      +------------+
//! ```
//
//! The constellation also maintains channels to threads, including:
//!
//! * The script thread.
//! * The graphics compositor.
//! * The font cache, image cache, and resource manager, which load
//!   and cache shared fonts, images, or other resources.
//! * The service worker manager.
//! * The devtools and webdriver servers.
//!
//! The constellation passes messages between the threads, and updates its state
//! to track the evolving state of the browsing context tree.
//!
//! The constellation acts as a logger, tracking any `warn!` messages from threads,
//! and converting any `error!` or `panic!` into a crash report.
//!
//! Since there is only one constellation, and its responsibilities include crash reporting,
//! it is very important that it does not panic.
//!
//! It's also important that the constellation not deadlock. In particular, we need
//! to be careful that we don't introduce any cycles in the can-block-on relation.
//! Blocking is typically introduced by `receiver.recv()`, which blocks waiting for the
//! sender to send some data. Servo tries to achieve deadlock-freedom by using the following
//! can-block-on relation:
//!
//! * Constellation can block on compositor
//! * Constellation can block on embedder
//! * Script can block on anything (other than script)
//! * Blocking is transitive (if T1 can block on T2 and T2 can block on T3 then T1 can block on T3)
//! * Nothing can block on itself!
//!
//! There is a complexity intoduced by IPC channels, since they do not support
//! non-blocking send. This means that as well as `receiver.recv()` blocking,
//! `sender.send(data)` can also block when the IPC buffer is full. For this reason it is
//! very important that all IPC receivers where we depend on non-blocking send
//! use a router to route IPC messages to an mpsc channel. The reason why that solves
//! the problem is that under the hood, the router uses a dedicated thread to forward
//! messages, and:
//!
//! * Anything (other than a routing thread) can block on a routing thread
//!
//! See <https://github.com/servo/servo/issues/14704>

use std::borrow::{Cow, ToOwned};
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet, VecDeque};
use std::marker::PhantomData;
use std::mem::replace;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
use std::{process, thread};

use background_hang_monitor::HangMonitorRegister;
use background_hang_monitor_api::{
    BackgroundHangMonitorControlMsg, BackgroundHangMonitorRegister, HangMonitorAlert,
};
use base::id::{
    BroadcastChannelRouterId, BrowsingContextGroupId, BrowsingContextId, HistoryStateId,
    MessagePortId, MessagePortRouterId, PipelineId, PipelineNamespace, PipelineNamespaceId,
    PipelineNamespaceRequest, TopLevelBrowsingContextId, WebViewId,
};
use base::Epoch;
use bluetooth_traits::BluetoothRequest;
use canvas_traits::canvas::{CanvasId, CanvasMsg};
use canvas_traits::webgl::WebGLThreads;
use canvas_traits::ConstellationCanvasMsg;
use compositing_traits::{
    CompositorMsg, CompositorProxy, ConstellationMsg as FromCompositorMsg,
    ForwardedToCompositorMsg, SendableFrameTree,
};
use crossbeam_channel::{after, never, select, unbounded, Receiver, Sender};
use devtools_traits::{
    ChromeToDevtoolsControlMsg, DevtoolsControlMsg, DevtoolsPageInfo, NavigationState,
    ScriptToDevtoolsControlMsg,
};
use embedder_traits::{
    Cursor, EmbedderMsg, EmbedderProxy, MediaSessionEvent, MediaSessionPlaybackState,
};
use euclid::default::Size2D as UntypedSize2D;
use euclid::Size2D;
use fonts::FontCacheThread;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use ipc_channel::Error as IpcError;
use keyboard_types::webdriver::Event as WebDriverInputEvent;
use keyboard_types::KeyboardEvent;
use log::{debug, error, info, trace, warn};
use media::{GLPlayerThreads, WindowGLContext};
use net_traits::pub_domains::reg_host;
use net_traits::request::{Referrer, RequestBuilder};
use net_traits::storage_thread::{StorageThreadMsg, StorageType};
use net_traits::{self, FetchResponseMsg, IpcSend, ResourceThreads};
use profile_traits::{mem, time};
use script_layout_interface::{LayoutFactory, ScriptThreadFactory};
use script_traits::CompositorEvent::{MouseButtonEvent, MouseMoveEvent};
use script_traits::{
    webdriver_msg, AnimationState, AnimationTickType, AuxiliaryBrowsingContextLoadInfo,
    BroadcastMsg, CompositorEvent, ConstellationControlMsg, DiscardBrowsingContext,
    DocumentActivity, DocumentState, GamepadEvent, HistoryEntryReplacement, IFrameLoadInfo,
    IFrameLoadInfoWithData, IFrameSandboxState, IFrameSizeMsg, Job, LayoutMsg as FromLayoutMsg,
    LoadData, LoadOrigin, LogEntry, MediaSessionActionType, MessagePortMsg, MouseEventType,
    PortMessageTask, SWManagerMsg, SWManagerSenders, ScriptMsg as FromScriptMsg,
    ScriptToConstellationChan, ServiceWorkerManagerFactory, ServiceWorkerMsg,
    StructuredSerializedData, TimerSchedulerMsg, TraversalDirection, UpdatePipelineIdReason,
    WebDriverCommandMsg, WindowSizeData, WindowSizeType,
};
use serde::{Deserialize, Serialize};
use servo_config::{opts, pref};
use servo_rand::{random, Rng, ServoRng, SliceRandom};
use servo_url::{Host, ImmutableOrigin, ServoUrl};
use style_traits::CSSPixel;
use tracing::{span, Level};
use webgpu::swapchain::WGPUImageMap;
use webgpu::{self, WebGPU, WebGPURequest, WebGPUResponse};
use webrender::{RenderApi, RenderApiSender};
use webrender_api::DocumentId;
use webrender_traits::{WebRenderNetApi, WebRenderScriptApi, WebrenderExternalImageRegistry};

use crate::browsingcontext::{
    AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator,
    NewBrowsingContextInfo,
};
use crate::event_loop::EventLoop;
use crate::network_listener::NetworkListener;
use crate::pipeline::{InitialPipelineState, Pipeline};
use crate::serviceworker::ServiceWorkerUnprivilegedContent;
use crate::session_history::{
    JointSessionHistory, NeedsToReload, SessionHistoryChange, SessionHistoryDiff,
};
use crate::timer_scheduler::TimerScheduler;
use crate::webview::WebViewManager;

type PendingApprovalNavigations = HashMap<PipelineId, (LoadData, HistoryEntryReplacement)>;

#[derive(Debug)]
/// The state used by MessagePortInfo to represent the various states the port can be in.
enum TransferState {
    /// The port is currently managed by a given global,
    /// identified by its router id.
    Managed(MessagePortRouterId),
    /// The port is currently in-transfer,
    /// and incoming tasks should be buffered until it becomes managed again.
    TransferInProgress(VecDeque<PortMessageTask>),
    /// A global has requested the transfer to be completed,
    /// it's pending a confirmation of either failure or success to complete the transfer.
    CompletionInProgress(MessagePortRouterId),
    /// While a completion of a transfer was in progress, the port was shipped,
    /// hence the transfer failed to complete.
    /// We start buffering incoming messages,
    /// while awaiting the return of the previous buffer from the global
    /// that failed to complete the transfer.
    CompletionFailed(VecDeque<PortMessageTask>),
    /// While a completion failed, another global requested to complete the transfer.
    /// We are still buffering messages, and awaiting the return of the buffer from the global who failed.
    CompletionRequested(MessagePortRouterId, VecDeque<PortMessageTask>),
    /// The entangled port has been removed while the port was in-transfer,
    /// the current port should be removed as well once it is managed again.
    EntangledRemoved,
}

#[derive(Debug)]
/// Info related to a message-port tracked by the constellation.
struct MessagePortInfo {
    /// The current state of the messageport.
    state: TransferState,

    /// The id of the entangled port, if any.
    entangled_with: Option<MessagePortId>,
}

/// Webrender related objects required by WebGPU threads
struct WebrenderWGPU {
    /// Webrender API.
    webrender_api: RenderApi,

    /// List of Webrender external images
    webrender_external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,

    /// WebGPU data that supplied to Webrender for rendering
    wgpu_image_map: WGPUImageMap,
}

/// Servo supports multiple top-level browsing contexts or “webviews”, so `Constellation` needs to
/// store webview-specific data for bookkeeping.
struct WebView {
    /// The currently focused browsing context in this webview for key events.
    /// The focused pipeline is the current entry of the focused browsing
    /// context.
    focused_browsing_context_id: BrowsingContextId,

    /// The joint session history for this webview.
    session_history: JointSessionHistory,
}

/// A browsing context group.
///
/// <https://html.spec.whatwg.org/multipage/#browsing-context-group>
#[derive(Clone, Default)]
struct BrowsingContextGroup {
    /// A browsing context group holds a set of top-level browsing contexts.
    top_level_browsing_context_set: HashSet<TopLevelBrowsingContextId>,

    /// The set of all event loops in this BrowsingContextGroup.
    /// We store the event loops in a map
    /// indexed by registered domain name (as a `Host`) to event loops.
    /// It is important that scripts with the same eTLD+1,
    /// who are part of the same browsing-context group
    /// share an event loop, since they can use `document.domain`
    /// to become same-origin, at which point they can share DOM objects.
    event_loops: HashMap<Host, Weak<EventLoop>>,

    /// The set of all WebGPU channels in this BrowsingContextGroup.
    webgpus: HashMap<Host, WebGPU>,
}

/// The `Constellation` itself. In the servo browser, there is one
/// constellation, which maintains all of the browser global data.
/// In embedded applications, there may be more than one constellation,
/// which are independent of each other.
///
/// The constellation may be in a different process from the pipelines,
/// and communicates using IPC.
///
/// It is parameterized over a `LayoutThreadFactory` and a
/// `ScriptThreadFactory` (which in practice are implemented by
/// `LayoutThread` in the `layout` crate, and `ScriptThread` in
/// the `script` crate). Script and layout communicate using a `Message`
/// type.
pub struct Constellation<STF, SWF> {
    /// An ipc-sender/threaded-receiver pair
    /// to facilitate installing pipeline namespaces in threads
    /// via a per-process installer.
    namespace_receiver: Receiver<Result<PipelineNamespaceRequest, IpcError>>,
    namespace_ipc_sender: IpcSender<PipelineNamespaceRequest>,

    /// An IPC channel for script threads to send messages to the constellation.
    /// This is the script threads' view of `script_receiver`.
    script_sender: IpcSender<(PipelineId, FromScriptMsg)>,

    /// A channel for the constellation to receive messages from script threads.
    /// This is the constellation's view of `script_sender`.
    script_receiver: Receiver<Result<(PipelineId, FromScriptMsg), IpcError>>,

    /// A handle to register components for hang monitoring.
    /// None when in multiprocess mode.
    background_monitor_register: Option<Box<dyn BackgroundHangMonitorRegister>>,

    /// Channels to control all background-hang monitors.
    /// TODO: store them on the relevant BrowsingContextGroup,
    /// so that they could be controlled on a "per-tab/event-loop" basis.
    background_monitor_control_senders: Vec<IpcSender<BackgroundHangMonitorControlMsg>>,

    /// A channel for the background hang monitor to send messages
    /// to the constellation.
    background_hang_monitor_sender: IpcSender<HangMonitorAlert>,

    /// A channel for the constellation to receiver messages
    /// from the background hang monitor.
    background_hang_monitor_receiver: Receiver<Result<HangMonitorAlert, IpcError>>,

    /// A factory for creating layouts. This allows customizing the kind
    /// of layout created for a [`Constellation`] and prevents a circular crate
    /// dependency between script and layout.
    layout_factory: Arc<dyn LayoutFactory>,

    /// An IPC channel for layout to send messages to the constellation.
    /// This is the layout's view of `layout_receiver`.
    layout_sender: IpcSender<FromLayoutMsg>,

    /// A channel for the constellation to receive messages from layout.
    /// This is the constellation's view of `layout_sender`.
    layout_receiver: Receiver<Result<FromLayoutMsg, IpcError>>,

    /// A channel for network listener to send messages to the constellation.
    network_listener_sender: Sender<(PipelineId, FetchResponseMsg)>,

    /// A channel for the constellation to receive messages from network listener.
    network_listener_receiver: Receiver<(PipelineId, FetchResponseMsg)>,

    /// A channel for the constellation to receive messages from the compositor thread.
    compositor_receiver: Receiver<FromCompositorMsg>,

    /// A channel through which messages can be sent to the embedder.
    embedder_proxy: EmbedderProxy,

    /// A channel (the implementation of which is port-specific) for the
    /// constellation to send messages to the compositor thread.
    compositor_proxy: CompositorProxy,

    /// Bookkeeping data for all webviews in the constellation.
    webviews: WebViewManager<WebView>,

    /// Channels for the constellation to send messages to the public
    /// resource-related threads. There are two groups of resource threads: one
    /// for public browsing, and one for private browsing.
    public_resource_threads: ResourceThreads,

    /// Channels for the constellation to send messages to the private
    /// resource-related threads.  There are two groups of resource
    /// threads: one for public browsing, and one for private
    /// browsing.
    private_resource_threads: ResourceThreads,

    /// A channel for the constellation to send messages to the font
    /// cache thread.
    font_cache_thread: FontCacheThread,

    /// A channel for the constellation to send messages to the
    /// devtools thread.
    devtools_sender: Option<Sender<DevtoolsControlMsg>>,

    /// An IPC channel for the constellation to send messages to the
    /// bluetooth thread.
    bluetooth_ipc_sender: IpcSender<BluetoothRequest>,

    /// A map of origin to sender to a Service worker manager.
    sw_managers: HashMap<ImmutableOrigin, IpcSender<ServiceWorkerMsg>>,

    /// An IPC channel for Service Worker Manager threads to send
    /// messages to the constellation.  This is the SW Manager thread's
    /// view of `swmanager_receiver`.
    swmanager_ipc_sender: IpcSender<SWManagerMsg>,

    /// A channel for the constellation to receive messages from the
    /// Service Worker Manager thread. This is the constellation's view of
    /// `swmanager_sender`.
    swmanager_receiver: Receiver<Result<SWManagerMsg, IpcError>>,

    /// A channel for the constellation to send messages to the
    /// time profiler thread.
    time_profiler_chan: time::ProfilerChan,

    /// A channel for the constellation to send messages to the
    /// memory profiler thread.
    mem_profiler_chan: mem::ProfilerChan,

    /// A channel for a pipeline to schedule timer events.
    scheduler_ipc_sender: IpcSender<TimerSchedulerMsg>,

    /// The receiver to which the IPC requests from scheduler_chan will be forwarded.
    scheduler_receiver: Receiver<Result<TimerSchedulerMsg, IpcError>>,

    /// The logic and data behing scheduling timer events.
    timer_scheduler: TimerScheduler,

    /// A single WebRender document the constellation operates on.
    webrender_document: DocumentId,

    /// Webrender related objects required by WebGPU threads
    webrender_wgpu: WebrenderWGPU,

    /// A channel for content processes to send messages that will
    /// be relayed to the WebRender thread.
    webrender_api_ipc_sender: WebRenderScriptApi,

    /// A channel for content process image caches to send messages
    /// that will be relayed to the WebRender thread.
    webrender_image_api_sender: WebRenderNetApi,

    /// A map of message-port Id to info.
    message_ports: HashMap<MessagePortId, MessagePortInfo>,

    /// A map of router-id to ipc-sender, to route messages to ports.
    message_port_routers: HashMap<MessagePortRouterId, IpcSender<MessagePortMsg>>,

    /// A map of broadcast routers to their IPC sender.
    broadcast_routers: HashMap<BroadcastChannelRouterId, IpcSender<BroadcastMsg>>,

    /// A map of origin to a map of channel-name to a list of relevant routers.
    broadcast_channels: HashMap<ImmutableOrigin, HashMap<String, Vec<BroadcastChannelRouterId>>>,

    /// The set of all the pipelines in the browser.  (See the `pipeline` module
    /// for more details.)
    pipelines: HashMap<PipelineId, Pipeline>,

    /// The set of all the browsing contexts in the browser.
    browsing_contexts: HashMap<BrowsingContextId, BrowsingContext>,

    /// A user agent holds a a set of browsing context groups.
    ///
    /// <https://html.spec.whatwg.org/multipage/#browsing-context-group-set>
    browsing_context_group_set: HashMap<BrowsingContextGroupId, BrowsingContextGroup>,

    /// The Id counter for BrowsingContextGroup.
    browsing_context_group_next_id: u32,

    /// When a navigation is performed, we do not immediately update
    /// the session history, instead we ask the event loop to begin loading
    /// the new document, and do not update the browsing context until the
    /// document is active. Between starting the load and it activating,
    /// we store a `SessionHistoryChange` object for the navigation in progress.
    pending_changes: Vec<SessionHistoryChange>,

    /// Pipeline IDs are namespaced in order to avoid name collisions,
    /// and the namespaces are allocated by the constellation.
    next_pipeline_namespace_id: PipelineNamespaceId,

    /// The size of the top-level window.
    window_size: WindowSizeData,

    /// Bits of state used to interact with the webdriver implementation
    webdriver: WebDriverData,

    /// Document states for loaded pipelines (used only when writing screenshots).
    document_states: HashMap<PipelineId, DocumentState>,

    /// Are we shutting down?
    shutting_down: bool,

    /// Have we seen any warnings? Hopefully always empty!
    /// The buffer contains `(thread_name, reason)` entries.
    handled_warnings: VecDeque<(Option<String>, String)>,

    /// The random number generator and probability for closing pipelines.
    /// This is for testing the hardening of the constellation.
    random_pipeline_closure: Option<(ServoRng, f32)>,

    /// Phantom data that keeps the Rust type system happy.
    phantom: PhantomData<(STF, SWF)>,

    /// Entry point to create and get channels to a WebGLThread.
    webgl_threads: Option<WebGLThreads>,

    /// The XR device registry
    webxr_registry: webxr_api::Registry,

    /// A channel through which messages can be sent to the canvas paint thread.
    canvas_sender: Sender<ConstellationCanvasMsg>,

    canvas_ipc_sender: IpcSender<CanvasMsg>,

    /// Navigation requests from script awaiting approval from the embedder.
    pending_approval_navigations: PendingApprovalNavigations,

    /// Bitmask which indicates which combination of mouse buttons are
    /// currently being pressed.
    pressed_mouse_buttons: u16,

    /// If True, exits on thread failure instead of displaying about:failure
    hard_fail: bool,

    /// If set with --disable-canvas-aa, disable antialiasing on the HTML
    /// canvas element.
    /// Like --disable-text-aa, this is useful for reftests where pixel perfect
    /// results are required.
    enable_canvas_antialiasing: bool,

    /// Entry point to create and get channels to a GLPlayerThread.
    glplayer_threads: Option<GLPlayerThreads>,

    /// Application window's GL Context for Media player
    player_context: WindowGLContext,

    /// Pipeline ID of the active media session.
    active_media_session: Option<PipelineId>,

    /// User agent string to report in network requests.
    user_agent: Cow<'static, str>,
}

/// State needed to construct a constellation.
pub struct InitialConstellationState {
    /// A channel through which messages can be sent to the embedder.
    pub embedder_proxy: EmbedderProxy,

    /// A channel through which messages can be sent to the compositor.
    pub compositor_proxy: CompositorProxy,

    /// A channel to the developer tools, if applicable.
    pub devtools_sender: Option<Sender<DevtoolsControlMsg>>,

    /// A channel to the bluetooth thread.
    pub bluetooth_thread: IpcSender<BluetoothRequest>,

    /// A channel to the font cache thread.
    pub font_cache_thread: FontCacheThread,

    /// A channel to the resource thread.
    pub public_resource_threads: ResourceThreads,

    /// A channel to the resource thread.
    pub private_resource_threads: ResourceThreads,

    /// A channel to the time profiler thread.
    pub time_profiler_chan: time::ProfilerChan,

    /// A channel to the memory profiler thread.
    pub mem_profiler_chan: mem::ProfilerChan,

    /// Webrender document ID.
    pub webrender_document: DocumentId,

    /// Webrender API.
    pub webrender_api_sender: RenderApiSender,

    /// Webrender external images
    pub webrender_external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,

    /// Entry point to create and get channels to a WebGLThread.
    pub webgl_threads: Option<WebGLThreads>,

    /// The XR device registry
    pub webxr_registry: webxr_api::Registry,

    pub glplayer_threads: Option<GLPlayerThreads>,

    /// Application window's GL Context for Media player
    pub player_context: WindowGLContext,

    /// User agent string to report in network requests.
    pub user_agent: Cow<'static, str>,

    pub wgpu_image_map: WGPUImageMap,
}

/// Data needed for webdriver
struct WebDriverData {
    load_channel: Option<(PipelineId, IpcSender<webdriver_msg::LoadStatus>)>,
    resize_channel: Option<IpcSender<WindowSizeData>>,
}

impl WebDriverData {
    fn new() -> WebDriverData {
        WebDriverData {
            load_channel: None,
            resize_channel: None,
        }
    }
}

/// When we are running reftests, we save an image to compare against a reference.
/// This enum gives the possible states of preparing such an image.
#[derive(Debug, PartialEq)]
enum ReadyToSave {
    NoTopLevelBrowsingContext,
    PendingChanges,
    DocumentLoading,
    EpochMismatch,
    PipelineUnknown,
    Ready,
}

/// When we are exiting a pipeline, we can either force exiting or not.
/// A normal exit waits for the compositor to update its state before
/// exiting, and delegates layout exit to script. A forced exit does
/// not notify the compositor, and exits layout without involving script.
#[derive(Clone, Copy, Debug)]
enum ExitPipelineMode {
    Normal,
    Force,
}

/// The number of warnings to include in each crash report.
const WARNINGS_BUFFER_SIZE: usize = 32;

/// Route an ipc receiver to an crossbeam receiver, preserving any errors.
fn route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors<T>(
    ipc_receiver: IpcReceiver<T>,
) -> Receiver<Result<T, IpcError>>
where
    T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
{
    let (crossbeam_sender, crossbeam_receiver) = unbounded();
    ROUTER.add_route(
        ipc_receiver.to_opaque(),
        Box::new(move |message| drop(crossbeam_sender.send(message.to::<T>()))),
    );
    crossbeam_receiver
}

impl<STF, SWF> Constellation<STF, SWF>
where
    STF: ScriptThreadFactory,
    SWF: ServiceWorkerManagerFactory,
{
    /// Create a new constellation thread.
    #[allow(clippy::too_many_arguments)]
    #[tracing::instrument(skip(state, layout_factory), fields(servo_profiling = true))]
    pub fn start(
        state: InitialConstellationState,
        layout_factory: Arc<dyn LayoutFactory>,
        initial_window_size: WindowSizeData,
        random_pipeline_closure_probability: Option<f32>,
        random_pipeline_closure_seed: Option<usize>,
        hard_fail: bool,
        enable_canvas_antialiasing: bool,
        canvas_create_sender: Sender<ConstellationCanvasMsg>,
        canvas_ipc_sender: IpcSender<CanvasMsg>,
    ) -> Sender<FromCompositorMsg> {
        let (compositor_sender, compositor_receiver) = unbounded();

        // service worker manager to communicate with constellation
        let (swmanager_ipc_sender, swmanager_ipc_receiver) =
            ipc::channel().expect("ipc channel failure");

        thread::Builder::new()
            .name("Constellation".to_owned())
            .spawn(move || {
                let (script_ipc_sender, script_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let script_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        script_ipc_receiver,
                    );

                let (namespace_ipc_sender, namespace_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let namespace_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        namespace_ipc_receiver,
                    );

                let (scheduler_ipc_sender, scheduler_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let scheduler_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        scheduler_ipc_receiver,
                    );

                let (background_hang_monitor_ipc_sender, background_hang_monitor_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let background_hang_monitor_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        background_hang_monitor_ipc_receiver,
                    );

                // If we are in multiprocess mode,
                // a dedicated per-process hang monitor will be initialized later inside the content process.
                // See run_content_process in servo/lib.rs
                let (background_monitor_register, background_hang_monitor_control_ipc_senders) =
                    if opts::multiprocess() {
                        (None, vec![])
                    } else {
                        let (
                            background_hang_monitor_control_ipc_sender,
                            background_hang_monitor_control_ipc_receiver,
                        ) = ipc::channel().expect("ipc channel failure");
                        (
                            Some(HangMonitorRegister::init(
                                background_hang_monitor_ipc_sender.clone(),
                                background_hang_monitor_control_ipc_receiver,
                                opts::get().background_hang_monitor,
                            )),
                            vec![background_hang_monitor_control_ipc_sender],
                        )
                    };

                let (layout_ipc_sender, layout_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let layout_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        layout_ipc_receiver,
                    );

                let (network_listener_sender, network_listener_receiver) = unbounded();

                let swmanager_receiver =
                    route_ipc_receiver_to_new_crossbeam_receiver_preserving_errors(
                        swmanager_ipc_receiver,
                    );

                // Zero is reserved for the embedder.
                PipelineNamespace::install(PipelineNamespaceId(1));

                let (webrender_ipc_sender, webrender_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");
                let (webrender_image_ipc_sender, webrender_image_ipc_receiver) =
                    ipc::channel().expect("ipc channel failure");

                let compositor_proxy = state.compositor_proxy.clone();
                ROUTER.add_route(
                    webrender_ipc_receiver.to_opaque(),
                    Box::new(move |message| {
                        compositor_proxy.send(CompositorMsg::Forwarded(
                            ForwardedToCompositorMsg::Layout(
                                message.to().expect("conversion failure"),
                            ),
                        ));
                    }),
                );

                let compositor_proxy = state.compositor_proxy.clone();
                ROUTER.add_route(
                    webrender_image_ipc_receiver.to_opaque(),
                    Box::new(move |message| {
                        compositor_proxy.send(CompositorMsg::Forwarded(
                            ForwardedToCompositorMsg::Net(
                                message.to().expect("conversion failure"),
                            ),
                        ));
                    }),
                );

                let webrender_wgpu = WebrenderWGPU {
                    webrender_api: state.webrender_api_sender.create_api(),
                    webrender_external_images: state.webrender_external_images,
                    wgpu_image_map: state.wgpu_image_map,
                };

                let mut constellation: Constellation<STF, SWF> = Constellation {
                    namespace_receiver,
                    namespace_ipc_sender,
                    script_sender: script_ipc_sender,
                    background_hang_monitor_sender: background_hang_monitor_ipc_sender,
                    background_hang_monitor_receiver,
                    background_monitor_register,
                    background_monitor_control_senders: background_hang_monitor_control_ipc_senders,
                    layout_sender: layout_ipc_sender,
                    script_receiver,
                    compositor_receiver,
                    layout_factory,
                    layout_receiver,
                    network_listener_sender,
                    network_listener_receiver,
                    embedder_proxy: state.embedder_proxy,
                    compositor_proxy: state.compositor_proxy,
                    webviews: WebViewManager::default(),
                    devtools_sender: state.devtools_sender,
                    bluetooth_ipc_sender: state.bluetooth_thread,
                    public_resource_threads: state.public_resource_threads,
                    private_resource_threads: state.private_resource_threads,
                    font_cache_thread: state.font_cache_thread,
                    sw_managers: Default::default(),
                    swmanager_receiver,
                    swmanager_ipc_sender,
                    browsing_context_group_set: Default::default(),
                    browsing_context_group_next_id: Default::default(),
                    message_ports: HashMap::new(),
                    message_port_routers: HashMap::new(),
                    broadcast_routers: HashMap::new(),
                    broadcast_channels: HashMap::new(),
                    pipelines: HashMap::new(),
                    browsing_contexts: HashMap::new(),
                    pending_changes: vec![],
                    // We initialize the namespace at 2, since we reserved
                    // namespace 0 for the embedder, and 0 for the constellation
                    next_pipeline_namespace_id: PipelineNamespaceId(2),
                    time_profiler_chan: state.time_profiler_chan,
                    mem_profiler_chan: state.mem_profiler_chan,
                    window_size: initial_window_size,
                    phantom: PhantomData,
                    webdriver: WebDriverData::new(),
                    timer_scheduler: TimerScheduler::new(),
                    scheduler_ipc_sender,
                    scheduler_receiver,
                    document_states: HashMap::new(),
                    webrender_document: state.webrender_document,
                    webrender_api_ipc_sender: WebRenderScriptApi::new(webrender_ipc_sender),
                    webrender_image_api_sender: WebRenderNetApi::new(webrender_image_ipc_sender),
                    webrender_wgpu,
                    shutting_down: false,
                    handled_warnings: VecDeque::new(),
                    random_pipeline_closure: random_pipeline_closure_probability.map(|prob| {
                        let seed = random_pipeline_closure_seed.unwrap_or_else(random);
                        let rng = ServoRng::new_manually_reseeded(seed as u64);
                        warn!("Randomly closing pipelines.");
                        info!("Using seed {} for random pipeline closure.", seed);
                        (rng, prob)
                    }),
                    webgl_threads: state.webgl_threads,
                    webxr_registry: state.webxr_registry,
                    canvas_sender: canvas_create_sender,
                    canvas_ipc_sender,
                    pending_approval_navigations: HashMap::new(),
                    pressed_mouse_buttons: 0,
                    hard_fail,
                    enable_canvas_antialiasing,
                    glplayer_threads: state.glplayer_threads,
                    player_context: state.player_context,
                    active_media_session: None,
                    user_agent: state.user_agent,
                };

                constellation.run();
            })
            .expect("Thread spawning failed");

        compositor_sender
    }

    /// The main event loop for the constellation.
    fn run(&mut self) {
        while !self.shutting_down || !self.pipelines.is_empty() {
            // Randomly close a pipeline if --random-pipeline-closure-probability is set
            // This is for testing the hardening of the constellation.
            self.maybe_close_random_pipeline();
            self.handle_request();
        }
        self.handle_shutdown();
    }

    /// Generate a new pipeline id namespace.
    fn next_pipeline_namespace_id(&mut self) -> PipelineNamespaceId {
        let namespace_id = self.next_pipeline_namespace_id;
        let PipelineNamespaceId(ref mut i) = self.next_pipeline_namespace_id;
        *i += 1;
        namespace_id
    }

    fn next_browsing_context_group_id(&mut self) -> BrowsingContextGroupId {
        let id = self.browsing_context_group_next_id;
        self.browsing_context_group_next_id += 1;
        BrowsingContextGroupId(id)
    }

    fn get_event_loop(
        &mut self,
        host: &Host,
        top_level_browsing_context_id: &TopLevelBrowsingContextId,
        opener: &Option<BrowsingContextId>,
    ) -> Result<Weak<EventLoop>, &'static str> {
        let bc_group = match opener {
            Some(browsing_context_id) => {
                let opener = self
                    .browsing_contexts
                    .get(browsing_context_id)
                    .ok_or("Opener was closed before the openee started")?;
                self.browsing_context_group_set
                    .get(&opener.bc_group_id)
                    .ok_or("Opener belongs to an unknown browsing context group")?
            },
            None => self
                .browsing_context_group_set
                .iter()
                .filter_map(|(_, bc_group)| {
                    if bc_group
                        .top_level_browsing_context_set
                        .contains(top_level_browsing_context_id)
                    {
                        Some(bc_group)
                    } else {
                        None
                    }
                })
                .last()
                .ok_or(
                    "Trying to get an event-loop for a top-level belonging to an unknown browsing context group",
                )?,
        };
        bc_group
            .event_loops
            .get(host)
            .ok_or("Trying to get an event-loop from an unknown browsing context group")
            .cloned()
    }

    fn set_event_loop(
        &mut self,
        event_loop: Weak<EventLoop>,
        host: Host,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        opener: Option<BrowsingContextId>,
    ) {
        let relevant_top_level = if let Some(opener) = opener {
            match self.browsing_contexts.get(&opener) {
                Some(opener) => opener.top_level_id,
                None => {
                    warn!("Setting event-loop for an unknown auxiliary");
                    return;
                },
            }
        } else {
            top_level_browsing_context_id
        };
        let maybe_bc_group_id = self
            .browsing_context_group_set
            .iter()
            .filter_map(|(id, bc_group)| {
                if bc_group
                    .top_level_browsing_context_set
                    .contains(&top_level_browsing_context_id)
                {
                    Some(*id)
                } else {
                    None
                }
            })
            .last();
        let bc_group_id = match maybe_bc_group_id {
            Some(id) => id,
            None => {
                warn!("Trying to add an event-loop to an unknown browsing context group");
                return;
            },
        };
        if let Some(bc_group) = self.browsing_context_group_set.get_mut(&bc_group_id) {
            if bc_group
                .event_loops
                .insert(host.clone(), event_loop)
                .is_some()
            {
                warn!(
                    "Double-setting an event-loop for {:?} at {:?}",
                    host, relevant_top_level
                );
            }
        }
    }

    /// Helper function for creating a pipeline
    #[allow(clippy::too_many_arguments)]
    fn new_pipeline(
        &mut self,
        pipeline_id: PipelineId,
        browsing_context_id: BrowsingContextId,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        parent_pipeline_id: Option<PipelineId>,
        opener: Option<BrowsingContextId>,
        initial_window_size: Size2D<f32, CSSPixel>,
        // TODO: we have to provide ownership of the LoadData
        // here, because it will be send on an ipc channel,
        // and ipc channels take onership of their data.
        // https://github.com/servo/ipc-channel/issues/138
        load_data: LoadData,
        sandbox: IFrameSandboxState,
        is_private: bool,
        throttled: bool,
    ) {
        if self.shutting_down {
            return;
        }
        debug!(
            "{}: Creating new pipeline in {}",
            pipeline_id, browsing_context_id
        );

        let (event_loop, host) = match sandbox {
            IFrameSandboxState::IFrameSandboxed => (None, None),
            IFrameSandboxState::IFrameUnsandboxed => {
                // If this is an about:blank or about:srcdoc load, it must share the creator's
                // event loop. This must match the logic in the script thread when determining
                // the proper origin.
                if load_data.url.as_str() != "about:blank" &&
                    load_data.url.as_str() != "about:srcdoc"
                {
                    match reg_host(&load_data.url) {
                        None => (None, None),
                        Some(host) => {
                            match self.get_event_loop(
                                &host,
                                &top_level_browsing_context_id,
                                &opener,
                            ) {
                                Err(err) => {
                                    warn!("{}", err);
                                    (None, Some(host))
                                },
                                Ok(event_loop) => {
                                    if let Some(event_loop) = event_loop.upgrade() {
                                        (Some(event_loop), None)
                                    } else {
                                        (None, Some(host))
                                    }
                                },
                            }
                        },
                    }
                } else if let Some(parent) =
                    parent_pipeline_id.and_then(|pipeline_id| self.pipelines.get(&pipeline_id))
                {
                    (Some(parent.event_loop.clone()), None)
                } else if let Some(creator) = load_data
                    .creator_pipeline_id
                    .and_then(|pipeline_id| self.pipelines.get(&pipeline_id))
                {
                    (Some(creator.event_loop.clone()), None)
                } else {
                    (None, None)
                }
            },
        };

        let resource_threads = if is_private {
            self.private_resource_threads.clone()
        } else {
            self.public_resource_threads.clone()
        };

        let result = Pipeline::spawn::<STF>(InitialPipelineState {
            id: pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            parent_pipeline_id,
            opener,
            script_to_constellation_chan: ScriptToConstellationChan {
                sender: self.script_sender.clone(),
                pipeline_id,
            },
            namespace_request_sender: self.namespace_ipc_sender.clone(),
            pipeline_namespace_id: self.next_pipeline_namespace_id(),
            background_monitor_register: self.background_monitor_register.clone(),
            background_hang_monitor_to_constellation_chan: self
                .background_hang_monitor_sender
                .clone(),
            layout_to_constellation_chan: self.layout_sender.clone(),
            layout_factory: self.layout_factory.clone(),
            scheduler_chan: self.scheduler_ipc_sender.clone(),
            compositor_proxy: self.compositor_proxy.clone(),
            devtools_sender: self.devtools_sender.clone(),
            bluetooth_thread: self.bluetooth_ipc_sender.clone(),
            swmanager_thread: self.swmanager_ipc_sender.clone(),
            font_cache_thread: self.font_cache_thread.clone(),
            resource_threads,
            time_profiler_chan: self.time_profiler_chan.clone(),
            mem_profiler_chan: self.mem_profiler_chan.clone(),
            window_size: WindowSizeData {
                initial_viewport: initial_window_size,
                device_pixel_ratio: self.window_size.device_pixel_ratio,
            },
            event_loop,
            load_data,
            prev_throttled: throttled,
            webrender_api_sender: self.webrender_api_ipc_sender.clone(),
            webrender_image_api_sender: self.webrender_image_api_sender.clone(),
            webrender_document: self.webrender_document,
            webgl_chan: self
                .webgl_threads
                .as_ref()
                .map(|threads| threads.pipeline()),
            webxr_registry: self.webxr_registry.clone(),
            player_context: self.player_context.clone(),
            user_agent: self.user_agent.clone(),
        });

        let pipeline = match result {
            Ok(result) => result,
            Err(e) => return self.handle_send_error(pipeline_id, e),
        };

        if let Some(chan) = pipeline.bhm_control_chan {
            self.background_monitor_control_senders.push(chan);
        }

        if let Some(host) = host {
            debug!(
                "{}: Adding new host entry {}",
                top_level_browsing_context_id, host,
            );
            self.set_event_loop(
                Rc::downgrade(&pipeline.pipeline.event_loop),
                host,
                top_level_browsing_context_id,
                opener,
            );
        }

        assert!(!self.pipelines.contains_key(&pipeline_id));
        self.pipelines.insert(pipeline_id, pipeline.pipeline);
    }

    /// Get an iterator for the fully active browsing contexts in a subtree.
    fn fully_active_descendant_browsing_contexts_iter(
        &self,
        browsing_context_id: BrowsingContextId,
    ) -> FullyActiveBrowsingContextsIterator {
        FullyActiveBrowsingContextsIterator {
            stack: vec![browsing_context_id],
            pipelines: &self.pipelines,
            browsing_contexts: &self.browsing_contexts,
        }
    }

    /// Get an iterator for the fully active browsing contexts in a tree.
    fn fully_active_browsing_contexts_iter(
        &self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
    ) -> FullyActiveBrowsingContextsIterator {
        self.fully_active_descendant_browsing_contexts_iter(BrowsingContextId::from(
            top_level_browsing_context_id,
        ))
    }

    /// Get an iterator for the browsing contexts in a subtree.
    fn all_descendant_browsing_contexts_iter(
        &self,
        browsing_context_id: BrowsingContextId,
    ) -> AllBrowsingContextsIterator {
        AllBrowsingContextsIterator {
            stack: vec![browsing_context_id],
            pipelines: &self.pipelines,
            browsing_contexts: &self.browsing_contexts,
        }
    }

    /// Create a new browsing context and update the internal bookkeeping.
    #[allow(clippy::too_many_arguments)]
    fn new_browsing_context(
        &mut self,
        browsing_context_id: BrowsingContextId,
        top_level_id: TopLevelBrowsingContextId,
        pipeline_id: PipelineId,
        parent_pipeline_id: Option<PipelineId>,
        size: Size2D<f32, CSSPixel>,
        is_private: bool,
        inherited_secure_context: Option<bool>,
        throttled: bool,
    ) {
        debug!("{}: Creating new browsing context", browsing_context_id);
        let bc_group_id = match self
            .browsing_context_group_set
            .iter_mut()
            .filter_map(|(id, bc_group)| {
                if bc_group
                    .top_level_browsing_context_set
                    .contains(&top_level_id)
                {
                    Some(id)
                } else {
                    None
                }
            })
            .last()
        {
            Some(id) => *id,
            None => {
                warn!("Top-level was unexpectedly removed from its top_level_browsing_context_set");
                return;
            },
        };
        let browsing_context = BrowsingContext::new(
            bc_group_id,
            browsing_context_id,
            top_level_id,
            pipeline_id,
            parent_pipeline_id,
            size,
            is_private,
            inherited_secure_context,
            throttled,
        );
        self.browsing_contexts
            .insert(browsing_context_id, browsing_context);

        // If this context is a nested container, attach it to parent pipeline.
        if let Some(parent_pipeline_id) = parent_pipeline_id {
            if let Some(parent) = self.pipelines.get_mut(&parent_pipeline_id) {
                parent.add_child(browsing_context_id);
            }
        }
    }

    fn add_pending_change(&mut self, change: SessionHistoryChange) {
        debug!(
            "adding pending session history change with {}",
            if change.replace.is_some() {
                "replacement"
            } else {
                "no replacement"
            },
        );
        self.pending_changes.push(change);
    }

    /// Handles loading pages, navigation, and granting access to the compositor
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request(&mut self) {
        #[derive(Debug)]
        enum Request {
            PipelineNamespace(PipelineNamespaceRequest),
            Script((PipelineId, FromScriptMsg)),
            BackgroundHangMonitor(HangMonitorAlert),
            Compositor(FromCompositorMsg),
            Layout(FromLayoutMsg),
            NetworkListener((PipelineId, FetchResponseMsg)),
            FromSWManager(SWManagerMsg),
            Timer(TimerSchedulerMsg),
        }

        // A timeout corresponding to the earliest scheduled timer event, if any.
        let scheduler_timeout = self
            .timer_scheduler
            .check_timers()
            .map(after)
            .unwrap_or(never());

        // Get one incoming request.
        // This is one of the few places where the compositor is
        // allowed to panic. If one of the receiver.recv() calls
        // fails, it is because the matching sender has been
        // reclaimed, but this can't happen in normal execution
        // because the constellation keeps a pointer to the sender,
        // so it should never be reclaimed. A possible scenario in
        // which receiver.recv() fails is if some unsafe code
        // produces undefined behaviour, resulting in the destructor
        // being called. If this happens, there's not much we can do
        // other than panic.
        let request = select! {
            recv(self.namespace_receiver) -> msg => {
                msg.expect("Unexpected script channel panic in constellation").map(Request::PipelineNamespace)
            }
            recv(self.script_receiver) -> msg => {
                msg.expect("Unexpected script channel panic in constellation").map(Request::Script)
            }
            recv(self.background_hang_monitor_receiver) -> msg => {
                msg.expect("Unexpected BHM channel panic in constellation").map(Request::BackgroundHangMonitor)
            }
            recv(self.compositor_receiver) -> msg => {
                Ok(Request::Compositor(msg.expect("Unexpected compositor channel panic in constellation")))
            }
            recv(self.layout_receiver) -> msg => {
                msg.expect("Unexpected layout channel panic in constellation").map(Request::Layout)
            }
            recv(self.network_listener_receiver) -> msg => {
                Ok(Request::NetworkListener(
                    msg.expect("Unexpected network listener channel panic in constellation")
                ))
            }
            recv(self.swmanager_receiver) -> msg => {
                msg.expect("Unexpected SW channel panic in constellation").map(Request::FromSWManager)
            }
            recv(self.scheduler_receiver) -> msg => {
                msg.expect("Unexpected schedule channel panic in constellation").map(Request::Timer)
            }
            recv(scheduler_timeout) -> _ => {
                // Note: by returning, we go back to the top,
                // where check_timers will be called.
                return;
            },
        };

        let request = match request {
            Ok(request) => request,
            Err(err) => return error!("Deserialization failed ({}).", err),
        };

        match request {
            Request::PipelineNamespace(message) => {
                self.handle_request_for_pipeline_namespace(message)
            },
            Request::Compositor(message) => self.handle_request_from_compositor(message),
            Request::Script(message) => {
                self.handle_request_from_script(message);
            },
            Request::BackgroundHangMonitor(message) => {
                self.handle_request_from_background_hang_monitor(message);
            },
            Request::Layout(message) => {
                self.handle_request_from_layout(message);
            },
            Request::NetworkListener(message) => {
                self.handle_request_from_network_listener(message);
            },
            Request::FromSWManager(message) => {
                self.handle_request_from_swmanager(message);
            },
            Request::Timer(message) => {
                self.timer_scheduler.handle_timer_request(message);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_for_pipeline_namespace(&mut self, request: PipelineNamespaceRequest) {
        let PipelineNamespaceRequest(sender) = request;
        let _ = sender.send(self.next_pipeline_namespace_id());
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_from_background_hang_monitor(&self, message: HangMonitorAlert) {
        match message {
            HangMonitorAlert::Profile(bytes) => self
                .embedder_proxy
                .send((None, EmbedderMsg::ReportProfile(bytes))),
            HangMonitorAlert::Hang(hang) => {
                // TODO: In case of a permanent hang being reported, add a "kill script" workflow,
                // via the embedder?
                warn!("Component hang alert: {:?}", hang);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_from_network_listener(&mut self, message: (PipelineId, FetchResponseMsg)) {
        let (id, message_) = message;
        let result = match self.pipelines.get(&id) {
            Some(pipeline) => {
                let msg = ConstellationControlMsg::NavigationResponse(id, message_);
                pipeline.event_loop.send(msg)
            },
            None => {
                return warn!("{}: Got fetch data after closure!", id);
            },
        };
        if let Err(e) = result {
            self.handle_send_error(id, e);
        }
    }

    fn handle_request_from_swmanager(&mut self, message: SWManagerMsg) {
        match message {
            SWManagerMsg::PostMessageToClient => {
                // TODO: implement posting a message to a SW client.
                // https://github.com/servo/servo/issues/24660
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_from_compositor(&mut self, message: FromCompositorMsg) {
        trace_msg_from_compositor!(message, "{message:?}");
        match message {
            FromCompositorMsg::Exit => {
                self.handle_exit();
            },
            FromCompositorMsg::GetBrowsingContext(pipeline_id, response_sender) => {
                self.handle_get_browsing_context(pipeline_id, response_sender);
            },
            FromCompositorMsg::GetPipeline(browsing_context_id, response_sender) => {
                self.handle_get_pipeline(browsing_context_id, response_sender);
            },
            FromCompositorMsg::GetFocusTopLevelBrowsingContext(resp_chan) => {
                let _ = resp_chan.send(self.webviews.focused_webview().map(|(id, _)| id));
            },
            FromCompositorMsg::Keyboard(key_event) => {
                self.handle_key_msg(key_event);
            },
            FromCompositorMsg::IMEDismissed => {
                self.handle_ime_dismissed();
            },
            // Perform a navigation previously requested by script, if approved by the embedder.
            // If there is already a pending page (self.pending_changes), it will not be overridden;
            // However, if the id is not encompassed by another change, it will be.
            FromCompositorMsg::AllowNavigationResponse(pipeline_id, allowed) => {
                let pending = self.pending_approval_navigations.remove(&pipeline_id);

                let top_level_browsing_context_id = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.top_level_browsing_context_id,
                    None => return warn!("{}: Attempted to navigate after closure", pipeline_id),
                };

                match pending {
                    Some((load_data, replace)) => {
                        if allowed {
                            self.load_url(
                                top_level_browsing_context_id,
                                pipeline_id,
                                load_data,
                                replace,
                            );
                        } else {
                            let pipeline_is_top_level_pipeline = self
                                .browsing_contexts
                                .get(&BrowsingContextId::from(top_level_browsing_context_id))
                                .map(|ctx| ctx.pipeline_id == pipeline_id)
                                .unwrap_or(false);
                            // If the navigation is refused, and this concerns an iframe,
                            // we need to take it out of it's "delaying-load-events-mode".
                            // https://html.spec.whatwg.org/multipage/#delaying-load-events-mode
                            if !pipeline_is_top_level_pipeline {
                                let msg = ConstellationControlMsg::StopDelayingLoadEventsMode(
                                    pipeline_id,
                                );
                                let result = match self.pipelines.get(&pipeline_id) {
                                    Some(pipeline) => pipeline.event_loop.send(msg),
                                    None => {
                                        return warn!(
                                            "{}: Attempted to navigate after closure",
                                            pipeline_id
                                        );
                                    },
                                };
                                if let Err(e) = result {
                                    self.handle_send_error(pipeline_id, e);
                                }
                            }
                        }
                    },
                    None => {
                        warn!(
                            "{}: AllowNavigationResponse for unknown request",
                            pipeline_id
                        )
                    },
                }
            },
            FromCompositorMsg::ClearCache => {
                self.public_resource_threads.clear_cache();
                self.private_resource_threads.clear_cache();
            },
            // Load a new page from a typed url
            // If there is already a pending page (self.pending_changes), it will not be overridden;
            // However, if the id is not encompassed by another change, it will be.
            FromCompositorMsg::LoadUrl(top_level_browsing_context_id, url) => {
                let load_data = LoadData::new(
                    LoadOrigin::Constellation,
                    url,
                    None,
                    Referrer::NoReferrer,
                    None,
                    None,
                );
                let ctx_id = BrowsingContextId::from(top_level_browsing_context_id);
                let pipeline_id = match self.browsing_contexts.get(&ctx_id) {
                    Some(ctx) => ctx.pipeline_id,
                    None => {
                        return warn!(
                            "{}: LoadUrl for unknown browsing context",
                            top_level_browsing_context_id
                        );
                    },
                };
                // Since this is a top-level load, initiated by the embedder, go straight to load_url,
                // bypassing schedule_navigation.
                self.load_url(
                    top_level_browsing_context_id,
                    pipeline_id,
                    load_data,
                    HistoryEntryReplacement::Disabled,
                );
            },
            FromCompositorMsg::IsReadyToSaveImage(pipeline_states) => {
                let is_ready = self.handle_is_ready_to_save_image(pipeline_states);
                debug!("Ready to save image {:?}.", is_ready);
                self.compositor_proxy
                    .send(CompositorMsg::IsReadyToSaveImageReply(
                        is_ready == ReadyToSave::Ready,
                    ));
            },
            // Create a new top level browsing context. Will use response_chan to return
            // the browsing context id.
            FromCompositorMsg::NewWebView(url, top_level_browsing_context_id) => {
                self.handle_new_top_level_browsing_context(url, top_level_browsing_context_id);
            },
            // A top level browsing context is created and opened in both constellation and
            // compositor.
            FromCompositorMsg::WebViewOpened(top_level_browsing_context_id) => {
                let msg = (
                    Some(top_level_browsing_context_id),
                    EmbedderMsg::WebViewOpened(top_level_browsing_context_id),
                );
                self.embedder_proxy.send(msg);
            },
            // Close a top level browsing context.
            FromCompositorMsg::CloseWebView(top_level_browsing_context_id) => {
                self.handle_close_top_level_browsing_context(top_level_browsing_context_id);
            },
            // Panic a top level browsing context.
            FromCompositorMsg::SendError(top_level_browsing_context_id, error) => {
                debug!("constellation got SendError message");
                if top_level_browsing_context_id.is_none() {
                    warn!("constellation got a SendError message without top level id");
                }
                self.handle_panic(top_level_browsing_context_id, error, None);
            },
            FromCompositorMsg::FocusWebView(top_level_browsing_context_id) => {
                if self.webviews.get(top_level_browsing_context_id).is_none() {
                    return warn!("{top_level_browsing_context_id}: FocusWebView on unknown top-level browsing context");
                }
                self.webviews.focus(top_level_browsing_context_id);
                self.embedder_proxy.send((
                    Some(top_level_browsing_context_id),
                    EmbedderMsg::WebViewFocused(top_level_browsing_context_id),
                ));
            },
            FromCompositorMsg::BlurWebView => {
                self.webviews.unfocus();
                self.embedder_proxy
                    .send((None, EmbedderMsg::WebViewBlurred));
            },
            // Handle a forward or back request
            FromCompositorMsg::TraverseHistory(top_level_browsing_context_id, direction) => {
                self.handle_traverse_history_msg(top_level_browsing_context_id, direction);
            },
            FromCompositorMsg::WindowSize(top_level_browsing_context_id, new_size, size_type) => {
                self.handle_window_size_msg(top_level_browsing_context_id, new_size, size_type);
            },
            FromCompositorMsg::TickAnimation(pipeline_id, tick_type) => {
                self.handle_tick_animation(pipeline_id, tick_type)
            },
            FromCompositorMsg::WebDriverCommand(command) => {
                self.handle_webdriver_msg(command);
            },
            FromCompositorMsg::Reload(top_level_browsing_context_id) => {
                self.handle_reload_msg(top_level_browsing_context_id);
            },
            FromCompositorMsg::LogEntry(top_level_browsing_context_id, thread_name, entry) => {
                self.handle_log_entry(top_level_browsing_context_id, thread_name, entry);
            },
            FromCompositorMsg::ForwardEvent(destination_pipeline_id, event) => {
                self.forward_event(destination_pipeline_id, event);
            },
            FromCompositorMsg::SetCursor(cursor) => self.handle_set_cursor_msg(cursor),
            FromCompositorMsg::EnableProfiler(rate, max_duration) => {
                for background_monitor_control_sender in &self.background_monitor_control_senders {
                    if let Err(e) = background_monitor_control_sender.send(
                        BackgroundHangMonitorControlMsg::EnableSampler(rate, max_duration),
                    ) {
                        warn!("error communicating with sampling profiler: {}", e);
                    }
                }
            },
            FromCompositorMsg::DisableProfiler => {
                for background_monitor_control_sender in &self.background_monitor_control_senders {
                    if let Err(e) = background_monitor_control_sender
                        .send(BackgroundHangMonitorControlMsg::DisableSampler)
                    {
                        warn!("error communicating with sampling profiler: {}", e);
                    }
                }
            },
            FromCompositorMsg::ExitFullScreen(top_level_browsing_context_id) => {
                self.handle_exit_fullscreen_msg(top_level_browsing_context_id);
            },
            FromCompositorMsg::MediaSessionAction(action) => {
                self.handle_media_session_action_msg(action);
            },
            FromCompositorMsg::SetWebViewThrottled(webview_id, throttled) => {
                self.set_webview_throttled(webview_id, throttled);
            },
            FromCompositorMsg::ReadyToPresent(webview_ids) => {
                let span = span!(
                    Level::TRACE,
                    "FromCompositorMsg::ReadyToPresent",
                    servo_profiling = true
                );
                let _enter = span.enter();
                self.embedder_proxy
                    .send((None, EmbedderMsg::ReadyToPresent(webview_ids)));
            },
            FromCompositorMsg::Gamepad(gamepad_event) => {
                self.handle_gamepad_msg(gamepad_event);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_from_script(&mut self, message: (PipelineId, FromScriptMsg)) {
        let (source_pipeline_id, content) = message;
        trace_script_msg!(content, "{source_pipeline_id}: {content:?}");

        let source_top_ctx_id = match self
            .pipelines
            .get(&source_pipeline_id)
            .map(|pipeline| pipeline.top_level_browsing_context_id)
        {
            None => return warn!("{}: ScriptMsg from closed pipeline", source_pipeline_id),
            Some(ctx) => ctx,
        };

        match content {
            FromScriptMsg::CompleteMessagePortTransfer(router_id, ports) => {
                self.handle_complete_message_port_transfer(router_id, ports);
            },
            FromScriptMsg::MessagePortTransferResult(router_id, succeeded, failed) => {
                self.handle_message_port_transfer_completed(router_id, succeeded);
                self.handle_message_port_transfer_failed(failed);
            },
            FromScriptMsg::RerouteMessagePort(port_id, task) => {
                self.handle_reroute_messageport(port_id, task);
            },
            FromScriptMsg::MessagePortShipped(port_id) => {
                self.handle_messageport_shipped(port_id);
            },
            FromScriptMsg::NewMessagePortRouter(router_id, ipc_sender) => {
                self.handle_new_messageport_router(router_id, ipc_sender);
            },
            FromScriptMsg::RemoveMessagePortRouter(router_id) => {
                self.handle_remove_messageport_router(router_id);
            },
            FromScriptMsg::NewMessagePort(router_id, port_id) => {
                self.handle_new_messageport(router_id, port_id);
            },
            FromScriptMsg::RemoveMessagePort(port_id) => {
                self.handle_remove_messageport(port_id);
            },
            FromScriptMsg::EntanglePorts(port1, port2) => {
                self.handle_entangle_messageports(port1, port2);
            },
            FromScriptMsg::NewBroadcastChannelRouter(router_id, response_sender, origin) => {
                self.handle_new_broadcast_channel_router(
                    source_pipeline_id,
                    router_id,
                    response_sender,
                    origin,
                );
            },
            FromScriptMsg::NewBroadcastChannelNameInRouter(router_id, channel_name, origin) => {
                self.handle_new_broadcast_channel_name_in_router(
                    source_pipeline_id,
                    router_id,
                    channel_name,
                    origin,
                );
            },
            FromScriptMsg::RemoveBroadcastChannelNameInRouter(router_id, channel_name, origin) => {
                self.handle_remove_broadcast_channel_name_in_router(
                    source_pipeline_id,
                    router_id,
                    channel_name,
                    origin,
                );
            },
            FromScriptMsg::RemoveBroadcastChannelRouter(router_id, origin) => {
                self.handle_remove_broadcast_channel_router(source_pipeline_id, router_id, origin);
            },
            FromScriptMsg::ScheduleBroadcast(router_id, message) => {
                self.handle_schedule_broadcast(source_pipeline_id, router_id, message);
            },
            FromScriptMsg::ForwardToEmbedder(embedder_msg) => {
                self.embedder_proxy
                    .send((Some(source_top_ctx_id), embedder_msg));
            },
            FromScriptMsg::PipelineExited => {
                self.handle_pipeline_exited(source_pipeline_id);
            },
            FromScriptMsg::DiscardDocument => {
                self.handle_discard_document(source_top_ctx_id, source_pipeline_id);
            },
            FromScriptMsg::DiscardTopLevelBrowsingContext => {
                self.handle_close_top_level_browsing_context(source_top_ctx_id);
            },

            FromScriptMsg::InitiateNavigateRequest(req_init, cancel_chan) => {
                self.handle_navigate_request(source_pipeline_id, req_init, cancel_chan);
            },
            FromScriptMsg::ScriptLoadedURLInIFrame(load_info) => {
                self.handle_script_loaded_url_in_iframe_msg(load_info);
            },
            FromScriptMsg::ScriptNewIFrame(load_info) => {
                self.handle_script_new_iframe(load_info);
            },
            FromScriptMsg::ScriptNewAuxiliary(load_info) => {
                self.handle_script_new_auxiliary(load_info);
            },
            FromScriptMsg::ChangeRunningAnimationsState(animation_state) => {
                self.handle_change_running_animations_state(source_pipeline_id, animation_state)
            },
            // Ask the embedder for permission to load a new page.
            FromScriptMsg::LoadUrl(load_data, replace) => {
                self.schedule_navigation(source_top_ctx_id, source_pipeline_id, load_data, replace);
            },
            FromScriptMsg::AbortLoadUrl => {
                self.handle_abort_load_url_msg(source_pipeline_id);
            },
            // A page loaded has completed all parsing, script, and reflow messages have been sent.
            FromScriptMsg::LoadComplete => {
                self.handle_load_complete_msg(source_top_ctx_id, source_pipeline_id)
            },
            // Handle navigating to a fragment
            FromScriptMsg::NavigatedToFragment(new_url, replacement_enabled) => {
                self.handle_navigated_to_fragment(source_pipeline_id, new_url, replacement_enabled);
            },
            // Handle a forward or back request
            FromScriptMsg::TraverseHistory(direction) => {
                self.handle_traverse_history_msg(source_top_ctx_id, direction);
            },
            // Handle a push history state request.
            FromScriptMsg::PushHistoryState(history_state_id, url) => {
                self.handle_push_history_state_msg(source_pipeline_id, history_state_id, url);
            },
            FromScriptMsg::ReplaceHistoryState(history_state_id, url) => {
                self.handle_replace_history_state_msg(source_pipeline_id, history_state_id, url);
            },
            // Handle a joint session history length request.
            FromScriptMsg::JointSessionHistoryLength(response_sender) => {
                self.handle_joint_session_history_length(source_top_ctx_id, response_sender);
            },
            // Notification that the new document is ready to become active
            FromScriptMsg::ActivateDocument => {
                self.handle_activate_document_msg(source_pipeline_id);
            },
            // Update pipeline url after redirections
            FromScriptMsg::SetFinalUrl(final_url) => {
                // The script may have finished loading after we already started shutting down.
                if let Some(ref mut pipeline) = self.pipelines.get_mut(&source_pipeline_id) {
                    pipeline.url = final_url;
                } else {
                    warn!("constellation got set final url message for dead pipeline");
                }
            },
            FromScriptMsg::PostMessage {
                target: browsing_context_id,
                source: source_pipeline_id,
                target_origin: origin,
                source_origin,
                data,
            } => {
                self.handle_post_message_msg(
                    browsing_context_id,
                    source_pipeline_id,
                    origin,
                    source_origin,
                    data,
                );
            },
            FromScriptMsg::Focus => {
                self.handle_focus_msg(source_pipeline_id);
            },
            FromScriptMsg::SetThrottledComplete(throttled) => {
                self.handle_set_throttled_complete(source_pipeline_id, throttled);
            },
            FromScriptMsg::RemoveIFrame(browsing_context_id, response_sender) => {
                let removed_pipeline_ids = self.handle_remove_iframe_msg(browsing_context_id);
                if let Err(e) = response_sender.send(removed_pipeline_ids) {
                    warn!("Error replying to remove iframe ({})", e);
                }
            },
            FromScriptMsg::CreateCanvasPaintThread(size, response_sender) => {
                self.handle_create_canvas_paint_thread_msg(size, response_sender)
            },
            FromScriptMsg::SetDocumentState(state) => {
                self.document_states.insert(source_pipeline_id, state);
            },
            FromScriptMsg::SetLayoutEpoch(epoch, response_sender) => {
                if let Some(pipeline) = self.pipelines.get_mut(&source_pipeline_id) {
                    pipeline.layout_epoch = epoch;
                }

                response_sender.send(true).unwrap_or_default();
            },
            FromScriptMsg::GetClientWindow(response_sender) => {
                self.compositor_proxy
                    .send(CompositorMsg::GetClientWindow(response_sender));
            },
            FromScriptMsg::GetScreenSize(response_sender) => {
                self.compositor_proxy
                    .send(CompositorMsg::GetScreenSize(response_sender));
            },
            FromScriptMsg::GetScreenAvailSize(response_sender) => {
                self.compositor_proxy
                    .send(CompositorMsg::GetScreenAvailSize(response_sender));
            },
            FromScriptMsg::LogEntry(thread_name, entry) => {
                self.handle_log_entry(Some(source_top_ctx_id), thread_name, entry);
            },
            FromScriptMsg::TouchEventProcessed(result) => self
                .compositor_proxy
                .send(CompositorMsg::TouchEventProcessed(result)),
            FromScriptMsg::GetBrowsingContextInfo(pipeline_id, response_sender) => {
                let result = self
                    .pipelines
                    .get(&pipeline_id)
                    .and_then(|pipeline| self.browsing_contexts.get(&pipeline.browsing_context_id))
                    .map(|ctx| (ctx.id, ctx.parent_pipeline_id));
                if let Err(e) = response_sender.send(result) {
                    warn!(
                        "Sending reply to get browsing context info failed ({:?}).",
                        e
                    );
                }
            },
            FromScriptMsg::GetTopForBrowsingContext(browsing_context_id, response_sender) => {
                let result = self
                    .browsing_contexts
                    .get(&browsing_context_id)
                    .map(|bc| bc.top_level_id);
                if let Err(e) = response_sender.send(result) {
                    warn!(
                        "Sending reply to get top for browsing context info failed ({:?}).",
                        e
                    );
                }
            },
            FromScriptMsg::GetChildBrowsingContextId(
                browsing_context_id,
                index,
                response_sender,
            ) => {
                let result = self
                    .browsing_contexts
                    .get(&browsing_context_id)
                    .and_then(|bc| self.pipelines.get(&bc.pipeline_id))
                    .and_then(|pipeline| pipeline.children.get(index))
                    .copied();
                if let Err(e) = response_sender.send(result) {
                    warn!(
                        "Sending reply to get child browsing context ID failed ({:?}).",
                        e
                    );
                }
            },
            FromScriptMsg::ScheduleJob(job) => {
                self.handle_schedule_serviceworker_job(source_pipeline_id, job);
            },
            FromScriptMsg::ForwardDOMMessage(msg_vec, scope_url) => {
                if let Some(mgr) = self.sw_managers.get(&scope_url.origin()) {
                    let _ = mgr.send(ServiceWorkerMsg::ForwardDOMMessage(msg_vec, scope_url));
                } else {
                    warn!("Unable to forward DOMMessage for postMessage call");
                }
            },
            FromScriptMsg::BroadcastStorageEvent(storage, url, key, old_value, new_value) => {
                self.handle_broadcast_storage_event(
                    source_pipeline_id,
                    storage,
                    url,
                    key,
                    old_value,
                    new_value,
                );
            },
            FromScriptMsg::MediaSessionEvent(pipeline_id, event) => {
                // Unlikely at this point, but we may receive events coming from
                // different media sessions, so we set the active media session based
                // on Playing events.
                // The last media session claiming to be in playing state is set to
                // the active media session.
                // Events coming from inactive media sessions are discarded.
                if self.active_media_session.is_some() {
                    if let MediaSessionEvent::PlaybackStateChange(ref state) = event {
                        if !matches!(
                            state,
                            MediaSessionPlaybackState::Playing | MediaSessionPlaybackState::Paused
                        ) {
                            return;
                        }
                    };
                }
                self.active_media_session = Some(pipeline_id);
                self.embedder_proxy.send((
                    Some(source_top_ctx_id),
                    EmbedderMsg::MediaSessionEvent(event),
                ));
            },
            FromScriptMsg::RequestAdapter(response_sender, options, ids) => self
                .handle_wgpu_request(
                    source_pipeline_id,
                    BrowsingContextId::from(source_top_ctx_id),
                    FromScriptMsg::RequestAdapter(response_sender, options, ids),
                ),
            FromScriptMsg::GetWebGPUChan(response_sender) => self.handle_wgpu_request(
                source_pipeline_id,
                BrowsingContextId::from(source_top_ctx_id),
                FromScriptMsg::GetWebGPUChan(response_sender),
            ),
            FromScriptMsg::TitleChanged(pipeline, title) => {
                if let Some(pipeline) = self.pipelines.get_mut(&pipeline) {
                    pipeline.title = title;
                }
            },
        }
    }

    /// Check the origin of a message against that of the pipeline it came from.
    /// Note: this is still limited as a security check,
    /// see <https://github.com/servo/servo/issues/11722>
    fn check_origin_against_pipeline(
        &self,
        pipeline_id: &PipelineId,
        origin: &ImmutableOrigin,
    ) -> Result<(), ()> {
        let pipeline_origin = match self.pipelines.get(pipeline_id) {
            Some(pipeline) => pipeline.load_data.url.origin(),
            None => {
                warn!("Received message from closed or unknown pipeline.");
                return Err(());
            },
        };
        if &pipeline_origin == origin {
            return Ok(());
        }
        Err(())
    }

    /// Broadcast a message via routers in various event-loops.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_schedule_broadcast(
        &self,
        pipeline_id: PipelineId,
        router_id: BroadcastChannelRouterId,
        message: BroadcastMsg,
    ) {
        if self
            .check_origin_against_pipeline(&pipeline_id, &message.origin)
            .is_err()
        {
            return warn!(
                "Attempt to schedule broadcast from an origin not matching the origin of the msg."
            );
        }
        if let Some(channels) = self.broadcast_channels.get(&message.origin) {
            let routers = match channels.get(&message.channel_name) {
                Some(routers) => routers,
                None => return warn!("Broadcast to channel name without active routers."),
            };
            for router in routers {
                // Exclude the sender of the broadcast.
                // Broadcasting locally is done at the point of sending.
                if router == &router_id {
                    continue;
                }

                if let Some(broadcast_ipc_sender) = self.broadcast_routers.get(router) {
                    if broadcast_ipc_sender.send(message.clone()).is_err() {
                        warn!("Failed to broadcast message to router: {:?}", router);
                    }
                } else {
                    warn!("No sender for broadcast router: {:?}", router);
                }
            }
        } else {
            warn!(
                "Attempt to schedule a broadcast for an origin without routers {:?}",
                message.origin
            );
        }
    }

    /// Remove a channel-name for a given broadcast router.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_remove_broadcast_channel_name_in_router(
        &mut self,
        pipeline_id: PipelineId,
        router_id: BroadcastChannelRouterId,
        channel_name: String,
        origin: ImmutableOrigin,
    ) {
        if self
            .check_origin_against_pipeline(&pipeline_id, &origin)
            .is_err()
        {
            return warn!("Attempt to remove channel name from an unexpected origin.");
        }
        if let Some(channels) = self.broadcast_channels.get_mut(&origin) {
            let is_empty = if let Some(routers) = channels.get_mut(&channel_name) {
                routers.retain(|router| router != &router_id);
                routers.is_empty()
            } else {
                return warn!(
                    "Multiple attempts to remove name for broadcast-channel {:?} at {:?}",
                    channel_name, origin
                );
            };
            if is_empty {
                channels.remove(&channel_name);
            }
        } else {
            warn!(
                "Attempt to remove a channel-name for an origin without channels {:?}",
                origin
            );
        }
    }

    /// Note a new channel-name relevant to a given broadcast router.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_new_broadcast_channel_name_in_router(
        &mut self,
        pipeline_id: PipelineId,
        router_id: BroadcastChannelRouterId,
        channel_name: String,
        origin: ImmutableOrigin,
    ) {
        if self
            .check_origin_against_pipeline(&pipeline_id, &origin)
            .is_err()
        {
            return warn!("Attempt to add channel name from an unexpected origin.");
        }
        let channels = self.broadcast_channels.entry(origin).or_default();

        let routers = channels.entry(channel_name).or_default();

        routers.push(router_id);
    }

    /// Remove a broadcast router.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_remove_broadcast_channel_router(
        &mut self,
        pipeline_id: PipelineId,
        router_id: BroadcastChannelRouterId,
        origin: ImmutableOrigin,
    ) {
        if self
            .check_origin_against_pipeline(&pipeline_id, &origin)
            .is_err()
        {
            return warn!("Attempt to remove broadcast router from an unexpected origin.");
        }
        if self.broadcast_routers.remove(&router_id).is_none() {
            warn!("Attempt to remove unknown broadcast-channel router.");
        }
    }

    /// Add a new broadcast router.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_new_broadcast_channel_router(
        &mut self,
        pipeline_id: PipelineId,
        router_id: BroadcastChannelRouterId,
        broadcast_ipc_sender: IpcSender<BroadcastMsg>,
        origin: ImmutableOrigin,
    ) {
        if self
            .check_origin_against_pipeline(&pipeline_id, &origin)
            .is_err()
        {
            return warn!("Attempt to add broadcast router from an unexpected origin.");
        }
        if self
            .broadcast_routers
            .insert(router_id, broadcast_ipc_sender)
            .is_some()
        {
            warn!("Multple attempt to add broadcast-channel router.");
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_wgpu_request(
        &mut self,
        source_pipeline_id: PipelineId,
        browsing_context_id: BrowsingContextId,
        request: FromScriptMsg,
    ) {
        let browsing_context_group_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(bc) => &bc.bc_group_id,
            None => return warn!("Browsing context not found"),
        };
        let source_pipeline = match self.pipelines.get(&source_pipeline_id) {
            Some(pipeline) => pipeline,
            None => return warn!("{}: ScriptMsg from closed pipeline", source_pipeline_id),
        };
        let host = match reg_host(&source_pipeline.url) {
            Some(host) => host,
            None => return warn!("Invalid host url"),
        };
        let browsing_context_group = if let Some(bcg) = self
            .browsing_context_group_set
            .get_mut(browsing_context_group_id)
        {
            bcg
        } else {
            return warn!("Browsing context group not found");
        };
        let webgpu_chan = match browsing_context_group.webgpus.entry(host) {
            Entry::Vacant(v) => WebGPU::new(
                self.webrender_wgpu.webrender_api.create_sender(),
                self.webrender_document,
                self.webrender_wgpu.webrender_external_images.clone(),
                self.webrender_wgpu.wgpu_image_map.clone(),
            )
            .map(|webgpu| {
                let msg = ConstellationControlMsg::SetWebGPUPort(webgpu.1);
                if let Err(e) = source_pipeline.event_loop.send(msg) {
                    warn!(
                        "{}: Failed to send SetWebGPUPort to pipeline ({:?})",
                        source_pipeline_id, e
                    );
                }
                v.insert(webgpu.0).clone()
            }),
            Entry::Occupied(o) => Some(o.get().clone()),
        };
        match request {
            FromScriptMsg::RequestAdapter(response_sender, options, ids) => match webgpu_chan {
                None => {
                    if let Err(e) = response_sender.send(WebGPUResponse::None) {
                        warn!("Failed to send request adapter message: {}", e)
                    }
                },
                Some(webgpu_chan) => {
                    let adapter_request = WebGPURequest::RequestAdapter {
                        sender: response_sender,
                        options,
                        ids,
                    };
                    if webgpu_chan.0.send(adapter_request).is_err() {
                        warn!("Failed to send request adapter message on WebGPU channel");
                    }
                },
            },
            FromScriptMsg::GetWebGPUChan(response_sender) => {
                if response_sender.send(webgpu_chan).is_err() {
                    warn!(
                        "{}: Failed to send WebGPU channel to pipeline",
                        source_pipeline_id
                    )
                }
            },
            _ => warn!("Wrong message type in handle_wgpu_request"),
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_request_from_layout(&mut self, message: FromLayoutMsg) {
        trace_layout_msg!(message, "{message:?}");
        match message {
            // Layout sends new sizes for all subframes. This needs to be reflected by all
            // frame trees in the navigation context containing the subframe.
            FromLayoutMsg::IFrameSizes(iframe_sizes) => {
                self.handle_iframe_size_msg(iframe_sizes);
            },
            FromLayoutMsg::PendingPaintMetric(pipeline_id, epoch) => {
                self.handle_pending_paint_metric(pipeline_id, epoch);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_message_port_transfer_completed(
        &mut self,
        router_id: Option<MessagePortRouterId>,
        ports: Vec<MessagePortId>,
    ) {
        let router_id = match router_id {
            Some(router_id) => router_id,
            None => {
                if !ports.is_empty() {
                    warn!("Constellation unable to process port transfer successes, since no router id was received");
                }
                return;
            },
        };
        for port_id in ports.into_iter() {
            let mut entry = match self.message_ports.entry(port_id) {
                Entry::Vacant(_) => {
                    warn!(
                        "Constellation received a port transfer completed msg for unknown messageport {:?}",
                        port_id
                    );
                    continue;
                },
                Entry::Occupied(entry) => entry,
            };
            match entry.get().state {
                TransferState::EntangledRemoved => {
                    // If the entangled port has been removed while this one was in-transfer,
                    // remove it now.
                    if let Some(ipc_sender) = self.message_port_routers.get(&router_id) {
                        let _ = ipc_sender.send(MessagePortMsg::RemoveMessagePort(port_id));
                    } else {
                        warn!("No message-port sender for {:?}", router_id);
                    }
                    entry.remove_entry();
                    continue;
                },
                TransferState::CompletionInProgress(expected_router_id) => {
                    // Here, the transfer was normally completed.

                    if expected_router_id != router_id {
                        return warn!(
                            "Transfer completed by an unexpected router: {:?}",
                            router_id
                        );
                    }
                    // Update the state to managed.
                    let new_info = MessagePortInfo {
                        state: TransferState::Managed(router_id),
                        entangled_with: entry.get().entangled_with,
                    };
                    entry.insert(new_info);
                },
                _ => warn!("Constellation received unexpected port transfer completed message"),
            }
        }
    }

    fn handle_message_port_transfer_failed(
        &mut self,
        ports: HashMap<MessagePortId, VecDeque<PortMessageTask>>,
    ) {
        for (port_id, mut previous_buffer) in ports.into_iter() {
            let entry = match self.message_ports.remove(&port_id) {
                None => {
                    warn!(
                        "Constellation received a port transfer completed msg for unknown messageport {:?}",
                        port_id
                    );
                    continue;
                },
                Some(entry) => entry,
            };
            let new_info = match entry.state {
                TransferState::EntangledRemoved => {
                    // If the entangled port has been removed while this one was in-transfer,
                    // just drop it.
                    continue;
                },
                TransferState::CompletionFailed(mut current_buffer) => {
                    // The transfer failed,
                    // and now the global has returned us the buffer we previously sent.
                    // So the next update is back to a "normal" transfer in progress.

                    // Tasks in the previous buffer are older,
                    // hence need to be added to the front of the current one.
                    while let Some(task) = previous_buffer.pop_back() {
                        current_buffer.push_front(task);
                    }
                    // Update the state to transfer-in-progress.
                    MessagePortInfo {
                        state: TransferState::TransferInProgress(current_buffer),
                        entangled_with: entry.entangled_with,
                    }
                },
                TransferState::CompletionRequested(target_router_id, mut current_buffer) => {
                    // Here, before the global who failed the last transfer could return us the buffer,
                    // another global already sent us a request to complete a new transfer.
                    // So we use the returned buffer to update
                    // the current-buffer(of new incoming messages),
                    // and we send everything to the global
                    // who is waiting for completion of the current transfer.

                    // Tasks in the previous buffer are older,
                    // hence need to be added to the front of the current one.
                    while let Some(task) = previous_buffer.pop_back() {
                        current_buffer.push_front(task);
                    }
                    // Forward the buffered message-queue to complete the current transfer.
                    if let Some(ipc_sender) = self.message_port_routers.get(&target_router_id) {
                        if ipc_sender
                            .send(MessagePortMsg::CompletePendingTransfer(
                                port_id,
                                current_buffer,
                            ))
                            .is_err()
                        {
                            warn!("Constellation failed to send complete port transfer response.");
                        }
                    } else {
                        warn!("No message-port sender for {:?}", target_router_id);
                    }

                    // Update the state to completion-in-progress.
                    MessagePortInfo {
                        state: TransferState::CompletionInProgress(target_router_id),
                        entangled_with: entry.entangled_with,
                    }
                },
                _ => {
                    warn!("Unexpected port transfer failed message received");
                    continue;
                },
            };
            self.message_ports.insert(port_id, new_info);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_complete_message_port_transfer(
        &mut self,
        router_id: MessagePortRouterId,
        ports: Vec<MessagePortId>,
    ) {
        let mut response = HashMap::new();
        for port_id in ports.into_iter() {
            let entry = match self.message_ports.remove(&port_id) {
                None => {
                    warn!(
                        "Constellation asked to complete transfer for unknown messageport {:?}",
                        port_id
                    );
                    continue;
                },
                Some(entry) => entry,
            };
            let new_info = match entry.state {
                TransferState::EntangledRemoved => {
                    // If the entangled port has been removed while this one was in-transfer,
                    // remove it now.
                    if let Some(ipc_sender) = self.message_port_routers.get(&router_id) {
                        let _ = ipc_sender.send(MessagePortMsg::RemoveMessagePort(port_id));
                    } else {
                        warn!("No message-port sender for {:?}", router_id);
                    }
                    continue;
                },
                TransferState::TransferInProgress(buffer) => {
                    response.insert(port_id, buffer);

                    // If the port was in transfer, and a global is requesting completion,
                    // we note the start of the completion.
                    MessagePortInfo {
                        state: TransferState::CompletionInProgress(router_id),
                        entangled_with: entry.entangled_with,
                    }
                },
                TransferState::CompletionFailed(buffer) |
                TransferState::CompletionRequested(_, buffer) => {
                    // If the completion had already failed,
                    // this is a request coming from a global to complete a new transfer,
                    // but we're still awaiting the return of the buffer
                    // from the first global who failed.
                    //
                    // So we note the request from the new global,
                    // and continue to buffer incoming messages
                    // and wait for the buffer used in the previous transfer to be returned.
                    //
                    // If another global requests completion in the CompletionRequested state,
                    // we simply swap the target router-id for the new one,
                    // keeping the buffer.
                    MessagePortInfo {
                        state: TransferState::CompletionRequested(router_id, buffer),
                        entangled_with: entry.entangled_with,
                    }
                },
                _ => {
                    warn!("Unexpected complete port transfer message received");
                    continue;
                },
            };
            self.message_ports.insert(port_id, new_info);
        }

        if !response.is_empty() {
            // Forward the buffered message-queue.
            if let Some(ipc_sender) = self.message_port_routers.get(&router_id) {
                if ipc_sender
                    .send(MessagePortMsg::CompleteTransfer(response))
                    .is_err()
                {
                    warn!("Constellation failed to send complete port transfer response.");
                }
            } else {
                warn!("No message-port sender for {:?}", router_id);
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_reroute_messageport(&mut self, port_id: MessagePortId, task: PortMessageTask) {
        let info = match self.message_ports.get_mut(&port_id) {
            Some(info) => info,
            None => {
                return warn!(
                    "Constellation asked to re-route msg to unknown messageport {:?}",
                    port_id
                )
            },
        };
        match &mut info.state {
            TransferState::Managed(router_id) | TransferState::CompletionInProgress(router_id) => {
                // In both the managed and completion of a transfer case, we forward the message.
                // Note that in both cases, if the port is transferred before the message is handled,
                // it will be sent back here and buffered while the transfer is ongoing.
                if let Some(ipc_sender) = self.message_port_routers.get(router_id) {
                    let _ = ipc_sender.send(MessagePortMsg::NewTask(port_id, task));
                } else {
                    warn!("No message-port sender for {:?}", router_id);
                }
            },
            TransferState::TransferInProgress(queue) => queue.push_back(task),
            TransferState::CompletionFailed(queue) => queue.push_back(task),
            TransferState::CompletionRequested(_, queue) => queue.push_back(task),
            TransferState::EntangledRemoved => warn!(
                "Messageport received a message, but entangled has alread been removed {:?}",
                port_id
            ),
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_messageport_shipped(&mut self, port_id: MessagePortId) {
        if let Some(info) = self.message_ports.get_mut(&port_id) {
            match info.state {
                TransferState::Managed(_) => {
                    // If shipped while managed, note the start of a transfer.
                    info.state = TransferState::TransferInProgress(VecDeque::new());
                },
                TransferState::CompletionInProgress(_) => {
                    // If shipped while completion of a transfer was in progress,
                    // the completion failed.
                    // This will be followed by a MessagePortTransferFailed message,
                    // containing the buffer we previously sent.
                    info.state = TransferState::CompletionFailed(VecDeque::new());
                },
                _ => warn!("Unexpected messageport shipped received"),
            }
        } else {
            warn!(
                "Constellation asked to mark unknown messageport as shipped {:?}",
                port_id
            );
        }
    }

    fn handle_new_messageport_router(
        &mut self,
        router_id: MessagePortRouterId,
        message_port_ipc_sender: IpcSender<MessagePortMsg>,
    ) {
        self.message_port_routers
            .insert(router_id, message_port_ipc_sender);
    }

    fn handle_remove_messageport_router(&mut self, router_id: MessagePortRouterId) {
        self.message_port_routers.remove(&router_id);
    }

    fn handle_new_messageport(&mut self, router_id: MessagePortRouterId, port_id: MessagePortId) {
        match self.message_ports.entry(port_id) {
            // If it's a new port, we should not know about it.
            Entry::Occupied(_) => warn!(
                "Constellation asked to start tracking an existing messageport {:?}",
                port_id
            ),
            Entry::Vacant(entry) => {
                let info = MessagePortInfo {
                    state: TransferState::Managed(router_id),
                    entangled_with: None,
                };
                entry.insert(info);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_remove_messageport(&mut self, port_id: MessagePortId) {
        let entangled = match self.message_ports.remove(&port_id) {
            Some(info) => info.entangled_with,
            None => {
                return warn!(
                    "Constellation asked to remove unknown messageport {:?}",
                    port_id
                );
            },
        };
        let entangled_id = match entangled {
            Some(id) => id,
            None => return,
        };
        let info = match self.message_ports.get_mut(&entangled_id) {
            Some(info) => info,
            None => {
                return warn!(
                    "Constellation asked to remove unknown entangled messageport {:?}",
                    entangled_id
                )
            },
        };
        let router_id = match info.state {
            TransferState::EntangledRemoved => return warn!(
                "Constellation asked to remove entangled messageport by a port that was already removed {:?}",
                port_id
            ),
            TransferState::TransferInProgress(_) |
            TransferState::CompletionInProgress(_) |
            TransferState::CompletionFailed(_) |
            TransferState::CompletionRequested(_, _) => {
                // Note: since the port is in-transer, we don't have a router to send it a message
                // to let it know that its entangled port has been removed.
                // Hence we mark it so that it will be messaged and removed once the transfer completes.
                info.state = TransferState::EntangledRemoved;
                return;
            },
            TransferState::Managed(router_id) => router_id,
        };
        if let Some(sender) = self.message_port_routers.get(&router_id) {
            let _ = sender.send(MessagePortMsg::RemoveMessagePort(entangled_id));
        } else {
            warn!("No message-port sender for {:?}", router_id);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_entangle_messageports(&mut self, port1: MessagePortId, port2: MessagePortId) {
        if let Some(info) = self.message_ports.get_mut(&port1) {
            info.entangled_with = Some(port2);
        } else {
            warn!(
                "Constellation asked to entangle unknown messageport: {:?}",
                port1
            );
        }
        if let Some(info) = self.message_ports.get_mut(&port2) {
            info.entangled_with = Some(port1);
        } else {
            warn!(
                "Constellation asked to entangle unknown messageport: {:?}",
                port2
            );
        }
    }

    /// <https://w3c.github.io/ServiceWorker/#schedule-job-algorithm>
    /// and
    /// <https://w3c.github.io/ServiceWorker/#dfn-job-queue>
    ///
    /// The Job Queue is essentially the channel to a SW manager,
    /// which are scoped per origin.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_schedule_serviceworker_job(&mut self, pipeline_id: PipelineId, job: Job) {
        let origin = job.scope_url.origin();

        if self
            .check_origin_against_pipeline(&pipeline_id, &origin)
            .is_err()
        {
            return warn!(
                "Attempt to schedule a serviceworker job from an origin not matching the origin of the job."
            );
        }

        // This match is equivalent to Entry.or_insert_with but allows for early return.
        let sw_manager = match self.sw_managers.entry(origin.clone()) {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let (own_sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");

                let sw_senders = SWManagerSenders {
                    swmanager_sender: self.swmanager_ipc_sender.clone(),
                    resource_sender: self.public_resource_threads.sender(),
                    own_sender: own_sender.clone(),
                    receiver,
                };
                let content = ServiceWorkerUnprivilegedContent::new(sw_senders, origin);

                if opts::multiprocess() {
                    if content.spawn_multiprocess().is_err() {
                        return warn!("Failed to spawn process for SW manager.");
                    }
                } else {
                    content.start::<SWF>();
                }
                entry.insert(own_sender)
            },
        };
        let _ = sw_manager.send(ServiceWorkerMsg::ScheduleJob(job));
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_broadcast_storage_event(
        &self,
        pipeline_id: PipelineId,
        storage: StorageType,
        url: ServoUrl,
        key: Option<String>,
        old_value: Option<String>,
        new_value: Option<String>,
    ) {
        let origin = url.origin();
        for pipeline in self.pipelines.values() {
            if (pipeline.id != pipeline_id) && (pipeline.url.origin() == origin) {
                let msg = ConstellationControlMsg::DispatchStorageEvent(
                    pipeline.id,
                    storage,
                    url.clone(),
                    key.clone(),
                    old_value.clone(),
                    new_value.clone(),
                );
                if let Err(err) = pipeline.event_loop.send(msg) {
                    warn!(
                        "{}: Failed to broadcast storage event to pipeline ({:?}).",
                        pipeline.id, err
                    );
                }
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_exit(&mut self) {
        debug!("Handling exit.");

        // TODO: add a timer, which forces shutdown if threads aren't responsive.
        if self.shutting_down {
            return;
        }
        self.shutting_down = true;

        self.mem_profiler_chan.send(mem::ProfilerMsg::Exit);

        // Tell all BHMs to exit,
        // and to ensure their monitored components exit
        // even when currently hanging(on JS or sync XHR).
        // This must be done before starting the process of closing all pipelines.
        for chan in &self.background_monitor_control_senders {
            let (exit_ipc_sender, exit_ipc_receiver) =
                ipc::channel().expect("Failed to create IPC channel!");
            if let Err(e) = chan.send(BackgroundHangMonitorControlMsg::Exit(exit_ipc_sender)) {
                warn!("error communicating with bhm: {}", e);
                continue;
            }
            if exit_ipc_receiver.recv().is_err() {
                warn!("Failed to receive exit confirmation from BHM.");
            }
        }

        // Close the top-level browsing contexts
        let browsing_context_ids: Vec<BrowsingContextId> = self
            .browsing_contexts
            .values()
            .filter(|browsing_context| browsing_context.is_top_level())
            .map(|browsing_context| browsing_context.id)
            .collect();
        for browsing_context_id in browsing_context_ids {
            debug!(
                "{}: Removing top-level browsing context",
                browsing_context_id
            );
            self.close_browsing_context(browsing_context_id, ExitPipelineMode::Normal);
        }

        // Close any pending changes and pipelines
        while let Some(pending) = self.pending_changes.pop() {
            debug!(
                "{}: Removing pending browsing context",
                pending.browsing_context_id
            );
            self.close_browsing_context(pending.browsing_context_id, ExitPipelineMode::Normal);
            debug!("{}: Removing pending pipeline", pending.new_pipeline_id);
            self.close_pipeline(
                pending.new_pipeline_id,
                DiscardBrowsingContext::Yes,
                ExitPipelineMode::Normal,
            );
        }

        // In case there are browsing contexts which weren't attached, we close them.
        let browsing_context_ids: Vec<BrowsingContextId> =
            self.browsing_contexts.keys().cloned().collect();
        for browsing_context_id in browsing_context_ids {
            debug!(
                "{}: Removing detached browsing context",
                browsing_context_id
            );
            self.close_browsing_context(browsing_context_id, ExitPipelineMode::Normal);
        }

        // In case there are pipelines which weren't attached to the pipeline tree, we close them.
        let pipeline_ids: Vec<PipelineId> = self.pipelines.keys().cloned().collect();
        for pipeline_id in pipeline_ids {
            debug!("{}: Removing detached pipeline", pipeline_id);
            self.close_pipeline(
                pipeline_id,
                DiscardBrowsingContext::Yes,
                ExitPipelineMode::Normal,
            );
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_shutdown(&mut self) {
        debug!("Handling shutdown.");

        // At this point, there are no active pipelines,
        // so we can safely block on other threads, without worrying about deadlock.
        // Channels to receive signals when threads are done exiting.
        let (core_ipc_sender, core_ipc_receiver) =
            ipc::channel().expect("Failed to create IPC channel!");
        let (storage_ipc_sender, storage_ipc_receiver) =
            ipc::channel().expect("Failed to create IPC channel!");
        let mut webgl_threads_receiver = None;

        debug!("Exiting core resource threads.");
        if let Err(e) = self
            .public_resource_threads
            .send(net_traits::CoreResourceMsg::Exit(core_ipc_sender))
        {
            warn!("Exit resource thread failed ({})", e);
        }

        if let Some(ref chan) = self.devtools_sender {
            debug!("Exiting devtools.");
            let msg = DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::ServerExitMsg);
            if let Err(e) = chan.send(msg) {
                warn!("Exit devtools failed ({:?})", e);
            }
        }

        debug!("Exiting storage resource threads.");
        if let Err(e) = self
            .public_resource_threads
            .send(StorageThreadMsg::Exit(storage_ipc_sender))
        {
            warn!("Exit storage thread failed ({})", e);
        }

        debug!("Exiting bluetooth thread.");
        if let Err(e) = self.bluetooth_ipc_sender.send(BluetoothRequest::Exit) {
            warn!("Exit bluetooth thread failed ({})", e);
        }

        debug!("Exiting service worker manager thread.");
        for (_, mgr) in self.sw_managers.drain() {
            if let Err(e) = mgr.send(ServiceWorkerMsg::Exit) {
                warn!("Exit service worker manager failed ({})", e);
            }
        }

        debug!("Exiting Canvas Paint thread.");
        if let Err(e) = self.canvas_sender.send(ConstellationCanvasMsg::Exit) {
            warn!("Exit Canvas Paint thread failed ({})", e);
        }

        debug!("Exiting WebGPU threads.");
        let receivers = self
            .browsing_context_group_set
            .values()
            .flat_map(|browsing_context_group| {
                browsing_context_group.webgpus.values().map(|webgpu| {
                    let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");
                    if let Err(e) = webgpu.exit(sender) {
                        warn!("Exit WebGPU Thread failed ({})", e);
                        None
                    } else {
                        Some(receiver)
                    }
                })
            })
            .flatten();

        for receiver in receivers {
            if let Err(e) = receiver.recv() {
                warn!("Failed to receive exit response from WebGPU ({:?})", e);
            }
        }

        if let Some(webgl_threads) = self.webgl_threads.as_ref() {
            let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");
            webgl_threads_receiver = Some(receiver);
            debug!("Exiting WebGL thread.");

            if let Err(e) = webgl_threads.exit(sender) {
                warn!("Exit WebGL Thread failed ({e})");
            }
        }

        debug!("Exiting GLPlayer thread.");
        if let Some(glplayer_threads) = self.glplayer_threads.as_ref() {
            if let Err(e) = glplayer_threads.exit() {
                warn!("Exit GLPlayer Thread failed ({})", e);
            }
        }

        debug!("Exiting font cache thread.");
        self.font_cache_thread.exit();

        // Receive exit signals from threads.
        if let Err(e) = core_ipc_receiver.recv() {
            warn!("Exit resource thread failed ({:?})", e);
        }
        if let Err(e) = storage_ipc_receiver.recv() {
            warn!("Exit storage thread failed ({:?})", e);
        }
        if self.webgl_threads.is_some() {
            if let Err(e) = webgl_threads_receiver
                .expect("webgl_threads_receiver to be Some")
                .recv()
            {
                warn!("Exit WebGL thread failed ({:?})", e);
            }
        }

        debug!("Asking compositor to complete shutdown.");
        self.compositor_proxy.send(CompositorMsg::ShutdownComplete);

        debug!("Shutting-down IPC router thread in constellation.");
        ROUTER.shutdown();
    }

    fn handle_pipeline_exited(&mut self, pipeline_id: PipelineId) {
        debug!("{}: Exited", pipeline_id);
        self.pipelines.remove(&pipeline_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_send_error(&mut self, pipeline_id: PipelineId, err: IpcError) {
        // Treat send error the same as receiving a panic message
        error!("{}: Send error ({})", pipeline_id, err);
        let top_level_browsing_context_id = self
            .pipelines
            .get(&pipeline_id)
            .map(|pipeline| pipeline.top_level_browsing_context_id);
        let reason = format!("Send failed ({})", err);
        self.handle_panic(top_level_browsing_context_id, reason, None);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_panic(
        &mut self,
        top_level_browsing_context_id: Option<TopLevelBrowsingContextId>,
        reason: String,
        backtrace: Option<String>,
    ) {
        if self.hard_fail {
            // It's quite difficult to make Servo exit cleanly if some threads have failed.
            // Hard fail exists for test runners so we crash and that's good enough.
            println!("Pipeline failed in hard-fail mode.  Crashing!");
            process::exit(1);
        }

        let top_level_browsing_context_id = match top_level_browsing_context_id {
            Some(id) => id,
            None => return,
        };

        debug!(
            "{}: Panic handler for top-level browsing context: {}",
            top_level_browsing_context_id, reason
        );

        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);

        self.embedder_proxy.send((
            Some(top_level_browsing_context_id),
            EmbedderMsg::Panic(reason.clone(), backtrace.clone()),
        ));

        let browsing_context = match self.browsing_contexts.get(&browsing_context_id) {
            Some(context) => context,
            None => return warn!("failed browsing context is missing"),
        };
        let window_size = browsing_context.size;
        let pipeline_id = browsing_context.pipeline_id;
        let throttled = browsing_context.throttled;

        let pipeline = match self.pipelines.get(&pipeline_id) {
            Some(p) => p,
            None => return warn!("failed pipeline is missing"),
        };
        let opener = pipeline.opener;

        self.close_browsing_context_children(
            browsing_context_id,
            DiscardBrowsingContext::No,
            ExitPipelineMode::Force,
        );

        let old_pipeline_id = pipeline_id;
        let old_load_data = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline.load_data.clone(),
            None => return warn!("failed pipeline is missing"),
        };
        if old_load_data.crash.is_some() {
            return error!("crash page crashed");
        }

        warn!("creating replacement pipeline for crash page");

        let new_pipeline_id = PipelineId::new();
        let new_load_data = LoadData {
            crash: Some(
                backtrace
                    .map(|b| format!("{}\n{}", reason, b))
                    .unwrap_or(reason),
            ),
            ..old_load_data.clone()
        };

        let sandbox = IFrameSandboxState::IFrameSandboxed;
        let is_private = false;
        self.new_pipeline(
            new_pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            None,
            opener,
            window_size,
            new_load_data,
            sandbox,
            is_private,
            throttled,
        );
        self.add_pending_change(SessionHistoryChange {
            top_level_browsing_context_id,
            browsing_context_id,
            new_pipeline_id,
            // Pipeline already closed by close_browsing_context_children, so we can pass Yes here
            // to avoid closing again in handle_activate_document_msg (though it would be harmless)
            replace: Some(NeedsToReload::Yes(old_pipeline_id, old_load_data)),
            new_browsing_context_info: None,
            window_size,
        });
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_log_entry(
        &mut self,
        top_level_browsing_context_id: Option<TopLevelBrowsingContextId>,
        thread_name: Option<String>,
        entry: LogEntry,
    ) {
        if let LogEntry::Panic(ref reason, ref backtrace) = entry {
            self.handle_panic(
                top_level_browsing_context_id,
                reason.clone(),
                Some(backtrace.clone()),
            );
        }

        match entry {
            LogEntry::Panic(reason, _) | LogEntry::Error(reason) | LogEntry::Warn(reason) => {
                // VecDeque::truncate is unstable
                if WARNINGS_BUFFER_SIZE <= self.handled_warnings.len() {
                    self.handled_warnings.pop_front();
                }
                self.handled_warnings.push_back((thread_name, reason));
            },
        }
    }

    fn forward_event(&mut self, destination_pipeline_id: PipelineId, event: CompositorEvent) {
        if let MouseButtonEvent(event_type, button, ..) = &event {
            match event_type {
                MouseEventType::MouseDown | MouseEventType::Click => {
                    self.pressed_mouse_buttons |= *button as u16;
                },
                MouseEventType::MouseUp => {
                    self.pressed_mouse_buttons &= !(*button as u16);
                },
            }
        }

        let event = match event {
            MouseButtonEvent(event_type, button, point, node_address, point_in_node, _) => {
                MouseButtonEvent(
                    event_type,
                    button,
                    point,
                    node_address,
                    point_in_node,
                    self.pressed_mouse_buttons,
                )
            },
            MouseMoveEvent(point, node_address, _) => {
                MouseMoveEvent(point, node_address, self.pressed_mouse_buttons)
            },
            _ => event,
        };

        if let MouseButtonEvent(MouseEventType::Click, ..) = event {
            self.pressed_mouse_buttons = 0;
        }

        let pipeline = match self.pipelines.get(&destination_pipeline_id) {
            None => {
                debug!("{}: Got event after closure", destination_pipeline_id);
                return;
            },
            Some(pipeline) => pipeline,
        };

        self.embedder_proxy.send((
            Some(pipeline.top_level_browsing_context_id),
            EmbedderMsg::EventDelivered((&event).into()),
        ));

        if let Err(e) = pipeline.event_loop.send(ConstellationControlMsg::SendEvent(
            destination_pipeline_id,
            event,
        )) {
            self.handle_send_error(destination_pipeline_id, e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_new_top_level_browsing_context(
        &mut self,
        url: ServoUrl,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
    ) {
        let window_size = self.window_size.initial_viewport;
        let pipeline_id = PipelineId::new();
        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        let load_data = LoadData::new(
            LoadOrigin::Constellation,
            url,
            None,
            Referrer::NoReferrer,
            None,
            None,
        );
        let sandbox = IFrameSandboxState::IFrameUnsandboxed;
        let is_private = false;
        let throttled = false;

        // Register this new top-level browsing context id as a webview and set
        // its focused browsing context to be itself.
        self.webviews.add(
            top_level_browsing_context_id,
            WebView {
                focused_browsing_context_id: browsing_context_id,
                session_history: JointSessionHistory::new(),
            },
        );

        // https://html.spec.whatwg.org/multipage/#creating-a-new-browsing-context-group
        let mut new_bc_group: BrowsingContextGroup = Default::default();
        let new_bc_group_id = self.next_browsing_context_group_id();
        new_bc_group
            .top_level_browsing_context_set
            .insert(top_level_browsing_context_id);
        self.browsing_context_group_set
            .insert(new_bc_group_id, new_bc_group);

        self.new_pipeline(
            pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            None,
            None,
            window_size,
            load_data,
            sandbox,
            is_private,
            throttled,
        );
        self.add_pending_change(SessionHistoryChange {
            top_level_browsing_context_id,
            browsing_context_id,
            new_pipeline_id: pipeline_id,
            replace: None,
            new_browsing_context_info: Some(NewBrowsingContextInfo {
                parent_pipeline_id: None,
                is_private,
                inherited_secure_context: None,
                throttled,
            }),
            window_size,
        });
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_close_top_level_browsing_context(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
    ) {
        debug!("{top_level_browsing_context_id}: Closing");
        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        let browsing_context =
            self.close_browsing_context(browsing_context_id, ExitPipelineMode::Normal);
        if self.webviews.focused_webview().map(|(id, _)| id) == Some(top_level_browsing_context_id)
        {
            self.embedder_proxy
                .send((None, EmbedderMsg::WebViewBlurred));
        }
        self.webviews.remove(top_level_browsing_context_id);
        self.compositor_proxy
            .send(CompositorMsg::RemoveWebView(top_level_browsing_context_id));
        self.embedder_proxy.send((
            Some(top_level_browsing_context_id),
            EmbedderMsg::WebViewClosed(top_level_browsing_context_id),
        ));

        let Some(browsing_context) = browsing_context else {
            return;
        };
        // https://html.spec.whatwg.org/multipage/#bcg-remove
        let bc_group_id = browsing_context.bc_group_id;
        let Some(bc_group) = self.browsing_context_group_set.get_mut(&bc_group_id) else {
            warn!("{}: Browsing context group not found!", bc_group_id);
            return;
        };
        if !bc_group
            .top_level_browsing_context_set
            .remove(&top_level_browsing_context_id)
        {
            warn!(
                "{top_level_browsing_context_id}: Top-level browsing context not found in {bc_group_id}",
            );
        }
        if bc_group.top_level_browsing_context_set.is_empty() {
            self.browsing_context_group_set
                .remove(&browsing_context.bc_group_id);
        }

        debug!("{top_level_browsing_context_id}: Closed");
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_iframe_size_msg(&mut self, iframe_sizes: Vec<IFrameSizeMsg>) {
        for IFrameSizeMsg {
            browsing_context_id,
            size,
            type_,
        } in iframe_sizes
        {
            let window_size = WindowSizeData {
                initial_viewport: size,
                device_pixel_ratio: self.window_size.device_pixel_ratio,
            };

            self.resize_browsing_context(window_size, type_, browsing_context_id);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_subframe_loaded(&mut self, pipeline_id: PipelineId) {
        let browsing_context_id = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline.browsing_context_id,
            None => return warn!("{}: Subframe loaded after closure", pipeline_id),
        };
        let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(browsing_context) => browsing_context.parent_pipeline_id,
            None => {
                return warn!(
                    "{}: Subframe loaded in closed {}",
                    pipeline_id, browsing_context_id,
                );
            },
        };
        let parent_pipeline_id = match parent_pipeline_id {
            Some(parent_pipeline_id) => parent_pipeline_id,
            None => return warn!("{}: Subframe has no parent", pipeline_id),
        };
        // https://html.spec.whatwg.org/multipage/#the-iframe-element:completely-loaded
        // When a Document in an iframe is marked as completely loaded,
        // the user agent must run the iframe load event steps.
        let msg = ConstellationControlMsg::DispatchIFrameLoadEvent {
            target: browsing_context_id,
            parent: parent_pipeline_id,
            child: pipeline_id,
        };
        let result = match self.pipelines.get(&parent_pipeline_id) {
            Some(parent) => parent.event_loop.send(msg),
            None => {
                return warn!(
                    "{}: Parent pipeline browsing context loaded after closure",
                    parent_pipeline_id
                );
            },
        };
        if let Err(e) = result {
            self.handle_send_error(parent_pipeline_id, e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_navigate_request(
        &self,
        id: PipelineId,
        request_builder: RequestBuilder,
        cancel_chan: IpcReceiver<()>,
    ) {
        let listener = NetworkListener::new(
            request_builder,
            id,
            self.public_resource_threads.clone(),
            self.network_listener_sender.clone(),
        );

        listener.initiate_fetch(Some(cancel_chan));
    }

    // The script thread associated with pipeline_id has loaded a URL in an
    // iframe via script. This will result in a new pipeline being spawned and
    // a child being added to the parent browsing context. This message is never
    // the result of a page navigation.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_script_loaded_url_in_iframe_msg(&mut self, load_info: IFrameLoadInfoWithData) {
        let IFrameLoadInfo {
            parent_pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            new_pipeline_id,
            is_private,
            mut replace,
            ..
        } = load_info.info;

        // If no url is specified, reload.
        let old_pipeline = load_info
            .old_pipeline_id
            .and_then(|id| self.pipelines.get(&id));

        // Replacement enabled also takes into account whether the document is "completely loaded",
        // see https://html.spec.whatwg.org/multipage/#the-iframe-element:completely-loaded
        if let Some(old_pipeline) = old_pipeline {
            if !old_pipeline.completely_loaded {
                replace = HistoryEntryReplacement::Enabled;
            }
            debug!(
                "{:?}: Old pipeline is {}completely loaded",
                load_info.old_pipeline_id,
                if old_pipeline.completely_loaded {
                    ""
                } else {
                    "not "
                }
            );
        }

        let is_parent_private = {
            let parent_browsing_context_id = match self.pipelines.get(&parent_pipeline_id) {
                Some(pipeline) => pipeline.browsing_context_id,
                None => {
                    return warn!(
                        "{}: Script loaded url in iframe {} in closed parent pipeline",
                        parent_pipeline_id, browsing_context_id,
                    );
                },
            };
            let is_parent_private = match self.browsing_contexts.get(&parent_browsing_context_id) {
                Some(ctx) => ctx.is_private,
                None => {
                    return warn!(
                        "{}: Script loaded url in iframe {} in closed parent browsing context",
                        parent_browsing_context_id, browsing_context_id,
                    );
                },
            };
            is_parent_private
        };
        let is_private = is_private || is_parent_private;

        let browsing_context = match self.browsing_contexts.get(&browsing_context_id) {
            Some(ctx) => ctx,
            None => {
                return warn!(
                    "{}: Script loaded url in iframe with closed browsing context",
                    browsing_context_id,
                );
            },
        };

        let replace = match replace {
            HistoryEntryReplacement::Enabled => {
                Some(NeedsToReload::No(browsing_context.pipeline_id))
            },
            HistoryEntryReplacement::Disabled => None,
        };

        // https://github.com/rust-lang/rust/issues/59159
        let browsing_context_size = browsing_context.size;
        let browsing_context_throttled = browsing_context.throttled;
        // TODO(servo#30571) revert to debug_assert_eq!() once underlying bug is fixed
        #[cfg(debug_assertions)]
        if !(browsing_context_size == load_info.window_size.initial_viewport) {
            log::warn!("debug assertion failed! browsing_context_size == load_info.window_size.initial_viewport");
        }

        // Create the new pipeline, attached to the parent and push to pending changes
        self.new_pipeline(
            new_pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            Some(parent_pipeline_id),
            None,
            browsing_context_size,
            load_info.load_data,
            load_info.sandbox,
            is_private,
            browsing_context_throttled,
        );
        self.add_pending_change(SessionHistoryChange {
            top_level_browsing_context_id,
            browsing_context_id,
            new_pipeline_id,
            replace,
            // Browsing context for iframe already exists.
            new_browsing_context_info: None,
            window_size: load_info.window_size.initial_viewport,
        });
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_script_new_iframe(&mut self, load_info: IFrameLoadInfoWithData) {
        let IFrameLoadInfo {
            parent_pipeline_id,
            new_pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            is_private,
            ..
        } = load_info.info;

        let (script_sender, parent_browsing_context_id) =
            match self.pipelines.get(&parent_pipeline_id) {
                Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
                None => {
                    return warn!(
                        "{}: Script loaded url in closed iframe pipeline",
                        parent_pipeline_id
                    )
                },
            };
        let (is_parent_private, is_parent_throttled, is_parent_secure) =
            match self.browsing_contexts.get(&parent_browsing_context_id) {
                Some(ctx) => (ctx.is_private, ctx.throttled, ctx.inherited_secure_context),
                None => {
                    return warn!(
                        "{}: New iframe {} loaded in closed parent browsing context",
                        parent_browsing_context_id, browsing_context_id,
                    );
                },
            };
        let is_private = is_private || is_parent_private;
        let pipeline = Pipeline::new(
            new_pipeline_id,
            browsing_context_id,
            top_level_browsing_context_id,
            None,
            script_sender,
            self.compositor_proxy.clone(),
            is_parent_throttled,
            load_info.load_data,
        );

        assert!(!self.pipelines.contains_key(&new_pipeline_id));
        self.pipelines.insert(new_pipeline_id, pipeline);
        self.add_pending_change(SessionHistoryChange {
            top_level_browsing_context_id,
            browsing_context_id,
            new_pipeline_id,
            replace: None,
            // Browsing context for iframe doesn't exist yet.
            new_browsing_context_info: Some(NewBrowsingContextInfo {
                parent_pipeline_id: Some(parent_pipeline_id),
                is_private,
                inherited_secure_context: is_parent_secure,
                throttled: is_parent_throttled,
            }),
            window_size: load_info.window_size.initial_viewport,
        });
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_script_new_auxiliary(&mut self, load_info: AuxiliaryBrowsingContextLoadInfo) {
        let AuxiliaryBrowsingContextLoadInfo {
            load_data,
            opener_pipeline_id,
            new_top_level_browsing_context_id,
            new_browsing_context_id,
            new_pipeline_id,
        } = load_info;

        let (script_sender, opener_browsing_context_id) =
            match self.pipelines.get(&opener_pipeline_id) {
                Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
                None => {
                    return warn!(
                        "{}: Auxiliary loaded url in closed iframe pipeline",
                        opener_pipeline_id
                    );
                },
            };
        let (is_opener_private, is_opener_throttled, is_opener_secure) =
            match self.browsing_contexts.get(&opener_browsing_context_id) {
                Some(ctx) => (ctx.is_private, ctx.throttled, ctx.inherited_secure_context),
                None => {
                    return warn!(
                        "{}: New auxiliary {} loaded in closed opener browsing context",
                        opener_browsing_context_id, new_browsing_context_id,
                    );
                },
            };
        let pipeline = Pipeline::new(
            new_pipeline_id,
            new_browsing_context_id,
            new_top_level_browsing_context_id,
            Some(opener_browsing_context_id),
            script_sender,
            self.compositor_proxy.clone(),
            is_opener_throttled,
            load_data,
        );

        assert!(!self.pipelines.contains_key(&new_pipeline_id));
        self.pipelines.insert(new_pipeline_id, pipeline);
        self.webviews.add(
            new_top_level_browsing_context_id,
            WebView {
                focused_browsing_context_id: new_browsing_context_id,
                session_history: JointSessionHistory::new(),
            },
        );

        // https://html.spec.whatwg.org/multipage/#bcg-append
        let opener = match self.browsing_contexts.get(&opener_browsing_context_id) {
            Some(id) => id,
            None => {
                warn!("Trying to append an unknown auxiliary to a browsing context group");
                return;
            },
        };
        let bc_group = match self.browsing_context_group_set.get_mut(&opener.bc_group_id) {
            Some(bc_group) => bc_group,
            None => {
                warn!("Trying to add a top-level to an unknown group.");
                return;
            },
        };
        bc_group
            .top_level_browsing_context_set
            .insert(new_top_level_browsing_context_id);

        self.add_pending_change(SessionHistoryChange {
            top_level_browsing_context_id: new_top_level_browsing_context_id,
            browsing_context_id: new_browsing_context_id,
            new_pipeline_id,
            replace: None,
            new_browsing_context_info: Some(NewBrowsingContextInfo {
                // Auxiliary browsing contexts are always top-level.
                parent_pipeline_id: None,
                is_private: is_opener_private,
                inherited_secure_context: is_opener_secure,
                throttled: is_opener_throttled,
            }),
            window_size: self.window_size.initial_viewport,
        });
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_pending_paint_metric(&self, pipeline_id: PipelineId, epoch: Epoch) {
        self.compositor_proxy
            .send(CompositorMsg::PendingPaintMetric(pipeline_id, epoch))
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_set_cursor_msg(&mut self, cursor: Cursor) {
        self.embedder_proxy
            .send((None, EmbedderMsg::SetCursor(cursor)))
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_change_running_animations_state(
        &mut self,
        pipeline_id: PipelineId,
        animation_state: AnimationState,
    ) {
        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
            if pipeline.animation_state != animation_state {
                pipeline.animation_state = animation_state;
                self.compositor_proxy
                    .send(CompositorMsg::ChangeRunningAnimationsState(
                        pipeline_id,
                        animation_state,
                    ))
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_tick_animation(&mut self, pipeline_id: PipelineId, tick_type: AnimationTickType) {
        let pipeline = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline,
            None => return warn!("{}: Got script tick after closure", pipeline_id),
        };

        let message = ConstellationControlMsg::TickAllAnimations(pipeline_id, tick_type);
        if let Err(e) = pipeline.event_loop.send(message) {
            self.handle_send_error(pipeline_id, e);
        }
    }

    /// Schedule a navigation(via load_url).
    /// 1: Ask the embedder for permission.
    /// 2: Store the details of the navigation, pending approval from the embedder.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn schedule_navigation(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        source_id: PipelineId,
        load_data: LoadData,
        replace: HistoryEntryReplacement,
    ) {
        match self.pending_approval_navigations.entry(source_id) {
            Entry::Occupied(_) => {
                return warn!(
                    "{}: Tried to schedule a navigation while one is already pending",
                    source_id
                );
            },
            Entry::Vacant(entry) => {
                let _ = entry.insert((load_data.clone(), replace));
            },
        };
        // Allow the embedder to handle the url itself
        let msg = (
            Some(top_level_browsing_context_id),
            EmbedderMsg::AllowNavigationRequest(source_id, load_data.url.clone()),
        );
        self.embedder_proxy.send(msg);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn load_url(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        source_id: PipelineId,
        load_data: LoadData,
        replace: HistoryEntryReplacement,
    ) -> Option<PipelineId> {
        debug!(
            "{}: Loading ({}replacing): {}",
            source_id,
            match replace {
                HistoryEntryReplacement::Enabled => "",
                HistoryEntryReplacement::Disabled => "not ",
            },
            load_data.url,
        );
        // If this load targets an iframe, its framing element may exist
        // in a separate script thread than the framed document that initiated
        // the new load. The framing element must be notified about the
        // requested change so it can update its internal state.
        //
        // If replace is true, the current entry is replaced instead of a new entry being added.
        let (browsing_context_id, opener) = match self.pipelines.get(&source_id) {
            Some(pipeline) => (pipeline.browsing_context_id, pipeline.opener),
            None => {
                warn!("{}: Loaded after closure", source_id);
                return None;
            },
        };
        let (window_size, pipeline_id, parent_pipeline_id, is_private, is_throttled) =
            match self.browsing_contexts.get(&browsing_context_id) {
                Some(ctx) => (
                    ctx.size,
                    ctx.pipeline_id,
                    ctx.parent_pipeline_id,
                    ctx.is_private,
                    ctx.throttled,
                ),
                None => {
                    // This should technically never happen (since `load_url` is
                    // only called on existing browsing contexts), but we prefer to
                    // avoid `expect`s or `unwrap`s in `Constellation` to ward
                    // against future changes that might break things.
                    warn!(
                        "{}: Loaded url in closed {}",
                        source_id, browsing_context_id,
                    );
                    return None;
                },
            };

        match parent_pipeline_id {
            Some(parent_pipeline_id) => {
                // Find the script thread for the pipeline containing the iframe
                // and issue an iframe load through there.
                let msg = ConstellationControlMsg::NavigateIframe(
                    parent_pipeline_id,
                    browsing_context_id,
                    load_data,
                    replace,
                );
                let result = match self.pipelines.get(&parent_pipeline_id) {
                    Some(parent_pipeline) => parent_pipeline.event_loop.send(msg),
                    None => {
                        warn!("{}: Child loaded after closure", parent_pipeline_id);
                        return None;
                    },
                };
                if let Err(e) = result {
                    self.handle_send_error(parent_pipeline_id, e);
                }
                None
            },
            None => {
                // Make sure no pending page would be overridden.
                for change in &self.pending_changes {
                    if change.browsing_context_id == browsing_context_id {
                        // id that sent load msg is being changed already; abort
                        return None;
                    }
                }

                if self.get_activity(source_id) == DocumentActivity::Inactive {
                    // Disregard this load if the navigating pipeline is not actually
                    // active. This could be caused by a delayed navigation (eg. from
                    // a timer) or a race between multiple navigations (such as an
                    // onclick handler on an anchor element).
                    return None;
                }

                // Being here means either there are no pending changes, or none of the pending
                // changes would be overridden by changing the subframe associated with source_id.

                // Create the new pipeline

                let replace = match replace {
                    HistoryEntryReplacement::Enabled => Some(NeedsToReload::No(pipeline_id)),
                    HistoryEntryReplacement::Disabled => None,
                };

                let new_pipeline_id = PipelineId::new();
                let sandbox = IFrameSandboxState::IFrameUnsandboxed;
                self.new_pipeline(
                    new_pipeline_id,
                    browsing_context_id,
                    top_level_browsing_context_id,
                    None,
                    opener,
                    window_size,
                    load_data,
                    sandbox,
                    is_private,
                    is_throttled,
                );
                self.add_pending_change(SessionHistoryChange {
                    top_level_browsing_context_id,
                    browsing_context_id,
                    new_pipeline_id,
                    replace,
                    // `load_url` is always invoked on an existing browsing context.
                    new_browsing_context_info: None,
                    window_size,
                });
                Some(new_pipeline_id)
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_abort_load_url_msg(&mut self, new_pipeline_id: PipelineId) {
        let pending_index = self
            .pending_changes
            .iter()
            .rposition(|change| change.new_pipeline_id == new_pipeline_id);

        // If it is found, remove it from the pending changes.
        if let Some(pending_index) = pending_index {
            self.pending_changes.remove(pending_index);
            self.close_pipeline(
                new_pipeline_id,
                DiscardBrowsingContext::No,
                ExitPipelineMode::Normal,
            );
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_load_complete_msg(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        pipeline_id: PipelineId,
    ) {
        let mut webdriver_reset = false;
        if let Some((expected_pipeline_id, ref reply_chan)) = self.webdriver.load_channel {
            debug!("Sending load to WebDriver");
            if expected_pipeline_id == pipeline_id {
                let _ = reply_chan.send(webdriver_msg::LoadStatus::LoadComplete);
                webdriver_reset = true;
            }
        }
        if webdriver_reset {
            self.webdriver.load_channel = None;
        }

        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
            debug!("{}: Marking as loaded", pipeline_id);
            pipeline.completely_loaded = true;
        }

        // Notify the embedder that the TopLevelBrowsingContext current document
        // has finished loading.
        // We need to make sure the pipeline that has finished loading is the current
        // pipeline and that no pending pipeline will replace the current one.
        let pipeline_is_top_level_pipeline = self
            .browsing_contexts
            .get(&BrowsingContextId::from(top_level_browsing_context_id))
            .map(|ctx| ctx.pipeline_id == pipeline_id)
            .unwrap_or(false);
        if pipeline_is_top_level_pipeline {
            // Is there any pending pipeline that will replace the current top level pipeline
            let current_top_level_pipeline_will_be_replaced = self
                .pending_changes
                .iter()
                .any(|change| change.browsing_context_id == top_level_browsing_context_id);

            if !current_top_level_pipeline_will_be_replaced {
                // Notify embedder and compositor top level document finished loading.
                self.compositor_proxy
                    .send(CompositorMsg::LoadComplete(top_level_browsing_context_id));
            }
        } else {
            self.handle_subframe_loaded(pipeline_id);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_navigated_to_fragment(
        &mut self,
        pipeline_id: PipelineId,
        new_url: ServoUrl,
        replacement_enabled: HistoryEntryReplacement,
    ) {
        let (top_level_browsing_context_id, old_url) = match self.pipelines.get_mut(&pipeline_id) {
            Some(pipeline) => {
                let old_url = replace(&mut pipeline.url, new_url.clone());
                (pipeline.top_level_browsing_context_id, old_url)
            },
            None => {
                return warn!("{}: Navigated to fragment after closure", pipeline_id);
            },
        };

        match replacement_enabled {
            HistoryEntryReplacement::Disabled => {
                let diff = SessionHistoryDiff::Hash {
                    pipeline_reloader: NeedsToReload::No(pipeline_id),
                    new_url,
                    old_url,
                };
                self.get_joint_session_history(top_level_browsing_context_id)
                    .push_diff(diff);
                self.notify_history_changed(top_level_browsing_context_id);
            },
            HistoryEntryReplacement::Enabled => {},
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_traverse_history_msg(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        direction: TraversalDirection,
    ) {
        let mut browsing_context_changes = HashMap::<BrowsingContextId, NeedsToReload>::new();
        let mut pipeline_changes = HashMap::<PipelineId, (Option<HistoryStateId>, ServoUrl)>::new();
        let mut url_to_load = HashMap::<PipelineId, ServoUrl>::new();
        {
            let session_history = self.get_joint_session_history(top_level_browsing_context_id);
            match direction {
                TraversalDirection::Forward(forward) => {
                    let future_length = session_history.future.len();

                    if future_length < forward {
                        return warn!("Cannot traverse that far into the future.");
                    }

                    for diff in session_history
                        .future
                        .drain(future_length - forward..)
                        .rev()
                    {
                        match diff {
                            SessionHistoryDiff::BrowsingContext {
                                browsing_context_id,
                                ref new_reloader,
                                ..
                            } => {
                                browsing_context_changes
                                    .insert(browsing_context_id, new_reloader.clone());
                            },
                            SessionHistoryDiff::Pipeline {
                                ref pipeline_reloader,
                                new_history_state_id,
                                ref new_url,
                                ..
                            } => match *pipeline_reloader {
                                NeedsToReload::No(pipeline_id) => {
                                    pipeline_changes.insert(
                                        pipeline_id,
                                        (Some(new_history_state_id), new_url.clone()),
                                    );
                                },
                                NeedsToReload::Yes(pipeline_id, ..) => {
                                    url_to_load.insert(pipeline_id, new_url.clone());
                                },
                            },
                            SessionHistoryDiff::Hash {
                                ref pipeline_reloader,
                                ref new_url,
                                ..
                            } => match *pipeline_reloader {
                                NeedsToReload::No(pipeline_id) => {
                                    let state = pipeline_changes
                                        .get(&pipeline_id)
                                        .and_then(|change| change.0);
                                    pipeline_changes.insert(pipeline_id, (state, new_url.clone()));
                                },
                                NeedsToReload::Yes(pipeline_id, ..) => {
                                    url_to_load.insert(pipeline_id, new_url.clone());
                                },
                            },
                        }
                        session_history.past.push(diff);
                    }
                },
                TraversalDirection::Back(back) => {
                    let past_length = session_history.past.len();

                    if past_length < back {
                        return warn!("Cannot traverse that far into the past.");
                    }

                    for diff in session_history.past.drain(past_length - back..).rev() {
                        match diff {
                            SessionHistoryDiff::BrowsingContext {
                                browsing_context_id,
                                ref old_reloader,
                                ..
                            } => {
                                browsing_context_changes
                                    .insert(browsing_context_id, old_reloader.clone());
                            },
                            SessionHistoryDiff::Pipeline {
                                ref pipeline_reloader,
                                old_history_state_id,
                                ref old_url,
                                ..
                            } => match *pipeline_reloader {
                                NeedsToReload::No(pipeline_id) => {
                                    pipeline_changes.insert(
                                        pipeline_id,
                                        (old_history_state_id, old_url.clone()),
                                    );
                                },
                                NeedsToReload::Yes(pipeline_id, ..) => {
                                    url_to_load.insert(pipeline_id, old_url.clone());
                                },
                            },
                            SessionHistoryDiff::Hash {
                                ref pipeline_reloader,
                                ref old_url,
                                ..
                            } => match *pipeline_reloader {
                                NeedsToReload::No(pipeline_id) => {
                                    let state = pipeline_changes
                                        .get(&pipeline_id)
                                        .and_then(|change| change.0);
                                    pipeline_changes.insert(pipeline_id, (state, old_url.clone()));
                                },
                                NeedsToReload::Yes(pipeline_id, ..) => {
                                    url_to_load.insert(pipeline_id, old_url.clone());
                                },
                            },
                        }
                        session_history.future.push(diff);
                    }
                },
            }
        }

        for (browsing_context_id, mut pipeline_reloader) in browsing_context_changes.drain() {
            if let NeedsToReload::Yes(pipeline_id, ref mut load_data) = pipeline_reloader {
                if let Some(url) = url_to_load.get(&pipeline_id) {
                    load_data.url = url.clone();
                }
            }
            self.update_browsing_context(browsing_context_id, pipeline_reloader);
        }

        for (pipeline_id, (history_state_id, url)) in pipeline_changes.drain() {
            self.update_pipeline(pipeline_id, history_state_id, url);
        }

        self.notify_history_changed(top_level_browsing_context_id);

        self.trim_history(top_level_browsing_context_id);
        self.update_webview_in_compositor(top_level_browsing_context_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn update_browsing_context(
        &mut self,
        browsing_context_id: BrowsingContextId,
        new_reloader: NeedsToReload,
    ) {
        let new_pipeline_id = match new_reloader {
            NeedsToReload::No(pipeline_id) => pipeline_id,
            NeedsToReload::Yes(pipeline_id, load_data) => {
                debug!(
                    "{}: Reloading document {}",
                    browsing_context_id, pipeline_id,
                );

                // TODO: Save the sandbox state so it can be restored here.
                let sandbox = IFrameSandboxState::IFrameUnsandboxed;
                let (
                    top_level_id,
                    old_pipeline_id,
                    parent_pipeline_id,
                    window_size,
                    is_private,
                    throttled,
                ) = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(ctx) => (
                        ctx.top_level_id,
                        ctx.pipeline_id,
                        ctx.parent_pipeline_id,
                        ctx.size,
                        ctx.is_private,
                        ctx.throttled,
                    ),
                    None => return warn!("No browsing context to traverse!"),
                };
                let opener = match self.pipelines.get(&old_pipeline_id) {
                    Some(pipeline) => pipeline.opener,
                    None => None,
                };
                let new_pipeline_id = PipelineId::new();
                self.new_pipeline(
                    new_pipeline_id,
                    browsing_context_id,
                    top_level_id,
                    parent_pipeline_id,
                    opener,
                    window_size,
                    load_data.clone(),
                    sandbox,
                    is_private,
                    throttled,
                );
                self.add_pending_change(SessionHistoryChange {
                    top_level_browsing_context_id: top_level_id,
                    browsing_context_id,
                    new_pipeline_id,
                    replace: Some(NeedsToReload::Yes(pipeline_id, load_data)),
                    // Browsing context must exist at this point.
                    new_browsing_context_info: None,
                    window_size,
                });
                return;
            },
        };

        let (old_pipeline_id, parent_pipeline_id, top_level_id) =
            match self.browsing_contexts.get_mut(&browsing_context_id) {
                Some(browsing_context) => {
                    let old_pipeline_id = browsing_context.pipeline_id;
                    browsing_context.update_current_entry(new_pipeline_id);
                    (
                        old_pipeline_id,
                        browsing_context.parent_pipeline_id,
                        browsing_context.top_level_id,
                    )
                },
                None => {
                    return warn!("{}: Closed during traversal", browsing_context_id);
                },
            };

        if let Some(old_pipeline) = self.pipelines.get(&old_pipeline_id) {
            old_pipeline.set_throttled(true);
        }
        if let Some(new_pipeline) = self.pipelines.get(&new_pipeline_id) {
            if let Some(ref chan) = self.devtools_sender {
                let state = NavigationState::Start(new_pipeline.url.clone());
                let _ = chan.send(DevtoolsControlMsg::FromScript(
                    ScriptToDevtoolsControlMsg::Navigate(browsing_context_id, state),
                ));
                let page_info = DevtoolsPageInfo {
                    title: new_pipeline.title.clone(),
                    url: new_pipeline.url.clone(),
                };
                let state = NavigationState::Stop(new_pipeline.id, page_info);
                let _ = chan.send(DevtoolsControlMsg::FromScript(
                    ScriptToDevtoolsControlMsg::Navigate(browsing_context_id, state),
                ));
            }

            new_pipeline.set_throttled(false);
        }

        self.update_activity(old_pipeline_id);
        self.update_activity(new_pipeline_id);

        if let Some(parent_pipeline_id) = parent_pipeline_id {
            let msg = ConstellationControlMsg::UpdatePipelineId(
                parent_pipeline_id,
                browsing_context_id,
                top_level_id,
                new_pipeline_id,
                UpdatePipelineIdReason::Traversal,
            );
            let result = match self.pipelines.get(&parent_pipeline_id) {
                None => {
                    return warn!("{}: Child traversed after closure", parent_pipeline_id);
                },
                Some(pipeline) => pipeline.event_loop.send(msg),
            };
            if let Err(e) = result {
                self.handle_send_error(parent_pipeline_id, e);
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn update_pipeline(
        &mut self,
        pipeline_id: PipelineId,
        history_state_id: Option<HistoryStateId>,
        url: ServoUrl,
    ) {
        let result = match self.pipelines.get_mut(&pipeline_id) {
            None => {
                return warn!("{}: History state updated after closure", pipeline_id);
            },
            Some(pipeline) => {
                let msg = ConstellationControlMsg::UpdateHistoryState(
                    pipeline_id,
                    history_state_id,
                    url.clone(),
                );
                pipeline.history_state_id = history_state_id;
                pipeline.url = url;
                pipeline.event_loop.send(msg)
            },
        };
        if let Err(e) = result {
            self.handle_send_error(pipeline_id, e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_joint_session_history_length(
        &self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        response_sender: IpcSender<u32>,
    ) {
        let length = self
            .webviews
            .get(top_level_browsing_context_id)
            .map(|webview| webview.session_history.history_length())
            .unwrap_or(1);
        let _ = response_sender.send(length as u32);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_push_history_state_msg(
        &mut self,
        pipeline_id: PipelineId,
        history_state_id: HistoryStateId,
        url: ServoUrl,
    ) {
        let (top_level_browsing_context_id, old_state_id, old_url) =
            match self.pipelines.get_mut(&pipeline_id) {
                Some(pipeline) => {
                    let old_history_state_id = pipeline.history_state_id;
                    let old_url = replace(&mut pipeline.url, url.clone());
                    pipeline.history_state_id = Some(history_state_id);
                    pipeline.history_states.insert(history_state_id);
                    (
                        pipeline.top_level_browsing_context_id,
                        old_history_state_id,
                        old_url,
                    )
                },
                None => {
                    return warn!(
                        "{}: Push history state {} for closed pipeline",
                        pipeline_id, history_state_id,
                    );
                },
            };

        let diff = SessionHistoryDiff::Pipeline {
            pipeline_reloader: NeedsToReload::No(pipeline_id),
            new_history_state_id: history_state_id,
            new_url: url,
            old_history_state_id: old_state_id,
            old_url,
        };
        self.get_joint_session_history(top_level_browsing_context_id)
            .push_diff(diff);
        self.notify_history_changed(top_level_browsing_context_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_replace_history_state_msg(
        &mut self,
        pipeline_id: PipelineId,
        history_state_id: HistoryStateId,
        url: ServoUrl,
    ) {
        let top_level_browsing_context_id = match self.pipelines.get_mut(&pipeline_id) {
            Some(pipeline) => {
                pipeline.history_state_id = Some(history_state_id);
                pipeline.url = url.clone();
                pipeline.top_level_browsing_context_id
            },
            None => {
                return warn!(
                    "{}: Replace history state {} for closed pipeline",
                    history_state_id, pipeline_id
                );
            },
        };

        let session_history = self.get_joint_session_history(top_level_browsing_context_id);
        session_history.replace_history_state(pipeline_id, history_state_id, url);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_ime_dismissed(&mut self) {
        // Send to the focused browsing contexts' current pipeline.
        let focused_browsing_context_id = self
            .webviews
            .focused_webview()
            .map(|(_, webview)| webview.focused_browsing_context_id);
        if let Some(browsing_context_id) = focused_browsing_context_id {
            let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                Some(ctx) => ctx.pipeline_id,
                None => {
                    return warn!(
                        "{}: Got IME dismissed event for nonexistent browsing context",
                        browsing_context_id,
                    );
                },
            };
            let msg =
                ConstellationControlMsg::SendEvent(pipeline_id, CompositorEvent::IMEDismissedEvent);
            let result = match self.pipelines.get(&pipeline_id) {
                Some(pipeline) => pipeline.event_loop.send(msg),
                None => {
                    return debug!("{}: Got IME dismissed event after closure", pipeline_id);
                },
            };
            if let Err(e) = result {
                self.handle_send_error(pipeline_id, e);
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_key_msg(&mut self, event: KeyboardEvent) {
        // Send to the focused browsing contexts' current pipeline.  If it
        // doesn't exist, fall back to sending to the compositor.
        let focused_browsing_context_id = self
            .webviews
            .focused_webview()
            .map(|(_, webview)| webview.focused_browsing_context_id);
        match focused_browsing_context_id {
            Some(browsing_context_id) => {
                let event = CompositorEvent::KeyboardEvent(event);
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(ctx) => ctx.pipeline_id,
                    None => {
                        return warn!(
                            "{}: Got key event for nonexistent browsing context",
                            browsing_context_id,
                        );
                    },
                };
                let msg = ConstellationControlMsg::SendEvent(pipeline_id, event);
                let result = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.event_loop.send(msg),
                    None => {
                        return debug!("{}: Got key event after closure", pipeline_id);
                    },
                };
                if let Err(e) = result {
                    self.handle_send_error(pipeline_id, e);
                }
            },
            None => {
                warn!("No focused browsing context! Falling back to sending key to compositor");
                let event = (None, EmbedderMsg::Keyboard(event));
                self.embedder_proxy.send(event);
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_reload_msg(&mut self, top_level_browsing_context_id: TopLevelBrowsingContextId) {
        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(browsing_context) => browsing_context.pipeline_id,
            None => {
                return warn!("{}: Got reload event after closure", browsing_context_id);
            },
        };
        let msg = ConstellationControlMsg::Reload(pipeline_id);
        let result = match self.pipelines.get(&pipeline_id) {
            None => return warn!("{}: Got reload event after closure", pipeline_id),
            Some(pipeline) => pipeline.event_loop.send(msg),
        };
        if let Err(e) = result {
            self.handle_send_error(pipeline_id, e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_post_message_msg(
        &mut self,
        browsing_context_id: BrowsingContextId,
        source_pipeline: PipelineId,
        origin: Option<ImmutableOrigin>,
        source_origin: ImmutableOrigin,
        data: StructuredSerializedData,
    ) {
        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            None => {
                return warn!(
                    "{}: PostMessage to closed browsing context",
                    browsing_context_id
                );
            },
            Some(browsing_context) => browsing_context.pipeline_id,
        };
        let source_browsing_context = match self.pipelines.get(&source_pipeline) {
            Some(pipeline) => pipeline.top_level_browsing_context_id,
            None => return warn!("{}: PostMessage from closed pipeline", source_pipeline),
        };
        let msg = ConstellationControlMsg::PostMessage {
            target: pipeline_id,
            source: source_pipeline,
            source_browsing_context,
            target_origin: origin,
            source_origin,
            data,
        };
        let result = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline.event_loop.send(msg),
            None => return warn!("{}: PostMessage to closed pipeline", pipeline_id),
        };
        if let Err(e) = result {
            self.handle_send_error(pipeline_id, e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_get_pipeline(
        &mut self,
        browsing_context_id: BrowsingContextId,
        response_sender: IpcSender<Option<PipelineId>>,
    ) {
        let current_pipeline_id = self
            .browsing_contexts
            .get(&browsing_context_id)
            .map(|browsing_context| browsing_context.pipeline_id);
        let pipeline_id_loaded = self
            .pending_changes
            .iter()
            .rev()
            .find(|x| x.browsing_context_id == browsing_context_id)
            .map(|x| x.new_pipeline_id)
            .or(current_pipeline_id);
        if let Err(e) = response_sender.send(pipeline_id_loaded) {
            warn!("Failed get_pipeline response ({}).", e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_get_browsing_context(
        &mut self,
        pipeline_id: PipelineId,
        response_sender: IpcSender<Option<BrowsingContextId>>,
    ) {
        let browsing_context_id = self
            .pipelines
            .get(&pipeline_id)
            .map(|pipeline| pipeline.browsing_context_id);
        if let Err(e) = response_sender.send(browsing_context_id) {
            warn!("Failed get_browsing_context response ({}).", e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_focus_msg(&mut self, pipeline_id: PipelineId) {
        let (browsing_context_id, top_level_browsing_context_id) =
            match self.pipelines.get(&pipeline_id) {
                Some(pipeline) => (
                    pipeline.browsing_context_id,
                    pipeline.top_level_browsing_context_id,
                ),
                None => return warn!("{}: Focus parent after closure", pipeline_id),
            };

        // Focus the top-level browsing context.
        self.webviews.focus(top_level_browsing_context_id);
        self.embedder_proxy.send((
            Some(top_level_browsing_context_id),
            EmbedderMsg::WebViewFocused(top_level_browsing_context_id),
        ));

        // Update the webview’s focused browsing context.
        match self.webviews.get_mut(top_level_browsing_context_id) {
            Some(webview) => {
                webview.focused_browsing_context_id = browsing_context_id;
            },
            None => {
                return warn!(
                    "{}: Browsing context for focus msg does not exist",
                    top_level_browsing_context_id
                );
            },
        };

        // Focus parent iframes recursively
        self.focus_parent_pipeline(browsing_context_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn focus_parent_pipeline(&mut self, browsing_context_id: BrowsingContextId) {
        let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(ctx) => ctx.parent_pipeline_id,
            None => {
                return warn!("{}: Focus parent after closure", browsing_context_id);
            },
        };
        let parent_pipeline_id = match parent_pipeline_id {
            Some(parent_id) => parent_id,
            None => {
                return debug!("{}: Focus has no parent", browsing_context_id);
            },
        };

        // Send a message to the parent of the provided browsing context (if it
        // exists) telling it to mark the iframe element as focused.
        let msg = ConstellationControlMsg::FocusIFrame(parent_pipeline_id, browsing_context_id);
        let (result, parent_browsing_context_id) = match self.pipelines.get(&parent_pipeline_id) {
            Some(pipeline) => {
                let result = pipeline.event_loop.send(msg);
                (result, pipeline.browsing_context_id)
            },
            None => return warn!("{}: Focus after closure", parent_pipeline_id),
        };
        if let Err(e) = result {
            self.handle_send_error(parent_pipeline_id, e);
        }
        self.focus_parent_pipeline(parent_browsing_context_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_remove_iframe_msg(
        &mut self,
        browsing_context_id: BrowsingContextId,
    ) -> Vec<PipelineId> {
        let result = self
            .all_descendant_browsing_contexts_iter(browsing_context_id)
            .flat_map(|browsing_context| browsing_context.pipelines.iter().cloned())
            .collect();
        self.close_browsing_context(browsing_context_id, ExitPipelineMode::Normal);
        result
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_set_throttled_complete(&mut self, pipeline_id: PipelineId, throttled: bool) {
        let browsing_context_id = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline.browsing_context_id,
            None => {
                return warn!(
                    "{}: Visibility change for closed browsing context",
                    pipeline_id
                )
            },
        };
        let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(ctx) => ctx.parent_pipeline_id,
            None => {
                return warn!("{}: Visibility change for closed pipeline", pipeline_id);
            },
        };

        if let Some(parent_pipeline_id) = parent_pipeline_id {
            let msg = ConstellationControlMsg::SetThrottledInContainingIframe(
                parent_pipeline_id,
                browsing_context_id,
                throttled,
            );
            let result = match self.pipelines.get(&parent_pipeline_id) {
                None => return warn!("{}: Parent pipeline closed", parent_pipeline_id),
                Some(parent_pipeline) => parent_pipeline.event_loop.send(msg),
            };

            if let Err(e) = result {
                self.handle_send_error(parent_pipeline_id, e);
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_create_canvas_paint_thread_msg(
        &mut self,
        size: UntypedSize2D<u64>,
        response_sender: IpcSender<(IpcSender<CanvasMsg>, CanvasId)>,
    ) {
        let (canvas_id_sender, canvas_id_receiver) = unbounded();

        if let Err(e) = self.canvas_sender.send(ConstellationCanvasMsg::Create {
            id_sender: canvas_id_sender,
            size,
            antialias: self.enable_canvas_antialiasing,
        }) {
            return warn!("Create canvas paint thread failed ({})", e);
        }
        let canvas_id = match canvas_id_receiver.recv() {
            Ok(canvas_id) => canvas_id,
            Err(e) => return warn!("Create canvas paint thread id response failed ({})", e),
        };
        if let Err(e) = response_sender.send((self.canvas_ipc_sender.clone(), canvas_id)) {
            warn!("Create canvas paint thread response failed ({})", e);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_webdriver_msg(&mut self, msg: WebDriverCommandMsg) {
        // Find the script channel for the given parent pipeline,
        // and pass the event to that script thread.
        match msg {
            WebDriverCommandMsg::GetWindowSize(_, response_sender) => {
                let _ = response_sender.send(self.window_size);
            },
            WebDriverCommandMsg::SetWindowSize(
                top_level_browsing_context_id,
                size,
                response_sender,
            ) => {
                self.webdriver.resize_channel = Some(response_sender);
                self.embedder_proxy.send((
                    Some(top_level_browsing_context_id),
                    EmbedderMsg::ResizeTo(size),
                ));
            },
            WebDriverCommandMsg::LoadUrl(
                top_level_browsing_context_id,
                load_data,
                response_sender,
            ) => {
                self.load_url_for_webdriver(
                    top_level_browsing_context_id,
                    load_data,
                    response_sender,
                    HistoryEntryReplacement::Disabled,
                );
            },
            WebDriverCommandMsg::Refresh(top_level_browsing_context_id, response_sender) => {
                let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(browsing_context) => browsing_context.pipeline_id,
                    None => {
                        return warn!("{}: Refresh after closure", browsing_context_id);
                    },
                };
                let load_data = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.load_data.clone(),
                    None => return warn!("{}: Refresh after closure", pipeline_id),
                };
                self.load_url_for_webdriver(
                    top_level_browsing_context_id,
                    load_data,
                    response_sender,
                    HistoryEntryReplacement::Enabled,
                );
            },
            WebDriverCommandMsg::ScriptCommand(browsing_context_id, cmd) => {
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(browsing_context) => browsing_context.pipeline_id,
                    None => {
                        return warn!("{}: ScriptCommand after closure", browsing_context_id);
                    },
                };
                let control_msg = ConstellationControlMsg::WebDriverScriptCommand(pipeline_id, cmd);
                let result = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.event_loop.send(control_msg),
                    None => return warn!("{}: ScriptCommand after closure", pipeline_id),
                };
                if let Err(e) = result {
                    self.handle_send_error(pipeline_id, e);
                }
            },
            WebDriverCommandMsg::SendKeys(browsing_context_id, cmd) => {
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(browsing_context) => browsing_context.pipeline_id,
                    None => {
                        return warn!("{}: SendKeys after closure", browsing_context_id);
                    },
                };
                let event_loop = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.event_loop.clone(),
                    None => return warn!("{}: SendKeys after closure", pipeline_id),
                };
                for event in cmd {
                    let event = match event {
                        WebDriverInputEvent::Keyboard(event) => {
                            CompositorEvent::KeyboardEvent(event)
                        },
                        WebDriverInputEvent::Composition(event) => {
                            CompositorEvent::CompositionEvent(event)
                        },
                    };
                    let control_msg = ConstellationControlMsg::SendEvent(pipeline_id, event);
                    if let Err(e) = event_loop.send(control_msg) {
                        return self.handle_send_error(pipeline_id, e);
                    }
                }
            },
            WebDriverCommandMsg::KeyboardAction(browsing_context_id, event) => {
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(browsing_context) => browsing_context.pipeline_id,
                    None => {
                        return warn!("{}: KeyboardAction after closure", browsing_context_id);
                    },
                };
                let event_loop = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.event_loop.clone(),
                    None => return warn!("{}: KeyboardAction after closure", pipeline_id),
                };
                let control_msg = ConstellationControlMsg::SendEvent(
                    pipeline_id,
                    CompositorEvent::KeyboardEvent(event),
                );
                if let Err(e) = event_loop.send(control_msg) {
                    self.handle_send_error(pipeline_id, e)
                }
            },
            WebDriverCommandMsg::MouseButtonAction(mouse_event_type, mouse_button, x, y) => {
                self.compositor_proxy
                    .send(CompositorMsg::WebDriverMouseButtonEvent(
                        mouse_event_type,
                        mouse_button,
                        x,
                        y,
                    ));
            },
            WebDriverCommandMsg::MouseMoveAction(x, y) => {
                self.compositor_proxy
                    .send(CompositorMsg::WebDriverMouseMoveEvent(x, y));
            },
            WebDriverCommandMsg::TakeScreenshot(_, rect, response_sender) => {
                self.compositor_proxy
                    .send(CompositorMsg::CreatePng(rect, response_sender));
            },
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn set_webview_throttled(&mut self, webview_id: WebViewId, throttled: bool) {
        let browsing_context_id = BrowsingContextId::from(webview_id);
        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(browsing_context) => browsing_context.pipeline_id,
            None => {
                return warn!("{browsing_context_id}: Tried to SetWebViewThrottled after closure");
            },
        };
        match self.pipelines.get(&pipeline_id) {
            None => warn!("{pipeline_id}: Tried to SetWebViewThrottled after closure"),
            Some(pipeline) => pipeline.set_throttled(throttled),
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn notify_history_changed(&self, top_level_browsing_context_id: TopLevelBrowsingContextId) {
        // Send a flat projection of the history to embedder.
        // The final vector is a concatenation of the LoadData of the past
        // entries, the current entry and the future entries.
        // LoadData of inner frames are ignored and replaced with the LoadData
        // of the parent.

        let session_history = match self.webviews.get(top_level_browsing_context_id) {
            Some(webview) => &webview.session_history,
            None => {
                return warn!(
                    "{}: Session history does not exist for browsing context",
                    top_level_browsing_context_id
                );
            },
        };

        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        let browsing_context = match self.browsing_contexts.get(&browsing_context_id) {
            Some(browsing_context) => browsing_context,
            None => {
                return warn!(
                    "notify_history_changed error after top-level browsing context closed."
                );
            },
        };

        let current_load_data = match self.pipelines.get(&browsing_context.pipeline_id) {
            Some(pipeline) => pipeline.load_data.clone(),
            None => {
                return warn!("{}: Refresh after closure", browsing_context.pipeline_id);
            },
        };

        // If LoadData was ignored, use the LoadData of the previous SessionHistoryEntry, which
        // is the LoadData of the parent browsing context.
        let resolve_load_data_future =
            |previous_load_data: &mut LoadData, diff: &SessionHistoryDiff| match *diff {
                SessionHistoryDiff::BrowsingContext {
                    browsing_context_id,
                    ref new_reloader,
                    ..
                } => {
                    if browsing_context_id == top_level_browsing_context_id {
                        let load_data = match *new_reloader {
                            NeedsToReload::No(pipeline_id) => {
                                match self.pipelines.get(&pipeline_id) {
                                    Some(pipeline) => pipeline.load_data.clone(),
                                    None => previous_load_data.clone(),
                                }
                            },
                            NeedsToReload::Yes(_, ref load_data) => load_data.clone(),
                        };
                        *previous_load_data = load_data.clone();
                        Some(load_data)
                    } else {
                        Some(previous_load_data.clone())
                    }
                },
                _ => Some(previous_load_data.clone()),
            };

        let resolve_load_data_past =
            |previous_load_data: &mut LoadData, diff: &SessionHistoryDiff| match *diff {
                SessionHistoryDiff::BrowsingContext {
                    browsing_context_id,
                    ref old_reloader,
                    ..
                } => {
                    if browsing_context_id == top_level_browsing_context_id {
                        let load_data = match *old_reloader {
                            NeedsToReload::No(pipeline_id) => {
                                match self.pipelines.get(&pipeline_id) {
                                    Some(pipeline) => pipeline.load_data.clone(),
                                    None => previous_load_data.clone(),
                                }
                            },
                            NeedsToReload::Yes(_, ref load_data) => load_data.clone(),
                        };
                        *previous_load_data = load_data.clone();
                        Some(load_data)
                    } else {
                        Some(previous_load_data.clone())
                    }
                },
                _ => Some(previous_load_data.clone()),
            };

        let mut entries: Vec<LoadData> = session_history
            .past
            .iter()
            .rev()
            .scan(current_load_data.clone(), &resolve_load_data_past)
            .collect();

        entries.reverse();

        let current_index = entries.len();

        entries.push(current_load_data.clone());

        entries.extend(
            session_history
                .future
                .iter()
                .rev()
                .scan(current_load_data, &resolve_load_data_future),
        );
        let urls = entries.iter().map(|entry| entry.url.clone()).collect();
        let msg = (
            Some(top_level_browsing_context_id),
            EmbedderMsg::HistoryChanged(urls, current_index),
        );
        self.embedder_proxy.send(msg);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn load_url_for_webdriver(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        load_data: LoadData,
        response_sender: IpcSender<webdriver_msg::LoadStatus>,
        replace: HistoryEntryReplacement,
    ) {
        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
            Some(browsing_context) => browsing_context.pipeline_id,
            None => {
                return warn!(
                    "{}: Webdriver load for closed browsing context",
                    browsing_context_id
                );
            },
        };
        if let Some(new_pipeline_id) = self.load_url(
            top_level_browsing_context_id,
            pipeline_id,
            load_data,
            replace,
        ) {
            self.webdriver.load_channel = Some((new_pipeline_id, response_sender));
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn change_session_history(&mut self, change: SessionHistoryChange) {
        debug!(
            "{}: Setting to {}",
            change.browsing_context_id, change.new_pipeline_id
        );

        // If the currently focused browsing context is a child of the browsing
        // context in which the page is being loaded, then update the focused
        // browsing context to be the one where the page is being loaded.
        if self.focused_browsing_context_is_descendant_of(change.browsing_context_id) {
            if let Some(webview) = self.webviews.get_mut(change.top_level_browsing_context_id) {
                webview.focused_browsing_context_id = change.browsing_context_id;
            }
        }

        let (old_pipeline_id, top_level_id) =
            match self.browsing_contexts.get_mut(&change.browsing_context_id) {
                Some(browsing_context) => {
                    debug!("Adding pipeline to existing browsing context.");
                    let old_pipeline_id = browsing_context.pipeline_id;
                    browsing_context.pipelines.insert(change.new_pipeline_id);
                    browsing_context.update_current_entry(change.new_pipeline_id);
                    (Some(old_pipeline_id), Some(browsing_context.top_level_id))
                },
                None => {
                    debug!("Adding pipeline to new browsing context.");
                    (None, None)
                },
            };

        match old_pipeline_id {
            None => {
                let new_context_info = match change.new_browsing_context_info {
                    Some(info) => info,
                    None => {
                        return warn!(
                            "{}: No NewBrowsingContextInfo for browsing context",
                            change.browsing_context_id,
                        );
                    },
                };
                self.new_browsing_context(
                    change.browsing_context_id,
                    change.top_level_browsing_context_id,
                    change.new_pipeline_id,
                    new_context_info.parent_pipeline_id,
                    change.window_size,
                    new_context_info.is_private,
                    new_context_info.inherited_secure_context,
                    new_context_info.throttled,
                );
                self.update_activity(change.new_pipeline_id);
            },
            Some(old_pipeline_id) => {
                if let Some(pipeline) = self.pipelines.get(&old_pipeline_id) {
                    pipeline.set_throttled(true);
                }

                // https://html.spec.whatwg.org/multipage/#unload-a-document
                self.unload_document(old_pipeline_id);
                // Deactivate the old pipeline, and activate the new one.
                let (pipelines_to_close, states_to_close) = if let Some(replace_reloader) =
                    change.replace
                {
                    self.get_joint_session_history(change.top_level_browsing_context_id)
                        .replace_reloader(
                            replace_reloader.clone(),
                            NeedsToReload::No(change.new_pipeline_id),
                        );

                    match replace_reloader {
                        NeedsToReload::No(pipeline_id) => (Some(vec![pipeline_id]), None),
                        NeedsToReload::Yes(..) => (None, None),
                    }
                } else {
                    let diff = SessionHistoryDiff::BrowsingContext {
                        browsing_context_id: change.browsing_context_id,
                        new_reloader: NeedsToReload::No(change.new_pipeline_id),
                        old_reloader: NeedsToReload::No(old_pipeline_id),
                    };

                    let mut pipelines_to_close = vec![];
                    let mut states_to_close = HashMap::new();

                    let diffs_to_close = self
                        .get_joint_session_history(change.top_level_browsing_context_id)
                        .push_diff(diff);

                    for diff in diffs_to_close {
                        match diff {
                            SessionHistoryDiff::BrowsingContext { new_reloader, .. } => {
                                if let Some(pipeline_id) = new_reloader.alive_pipeline_id() {
                                    pipelines_to_close.push(pipeline_id);
                                }
                            },
                            SessionHistoryDiff::Pipeline {
                                pipeline_reloader,
                                new_history_state_id,
                                ..
                            } => {
                                if let Some(pipeline_id) = pipeline_reloader.alive_pipeline_id() {
                                    let states =
                                        states_to_close.entry(pipeline_id).or_insert(Vec::new());
                                    states.push(new_history_state_id);
                                }
                            },
                            _ => {},
                        }
                    }

                    (Some(pipelines_to_close), Some(states_to_close))
                };

                self.update_activity(old_pipeline_id);
                self.update_activity(change.new_pipeline_id);

                if let Some(states_to_close) = states_to_close {
                    for (pipeline_id, states) in states_to_close {
                        let msg = ConstellationControlMsg::RemoveHistoryStates(pipeline_id, states);
                        let result = match self.pipelines.get(&pipeline_id) {
                            None => {
                                return warn!(
                                    "{}: Removed history states after closure",
                                    pipeline_id
                                );
                            },
                            Some(pipeline) => pipeline.event_loop.send(msg),
                        };
                        if let Err(e) = result {
                            self.handle_send_error(pipeline_id, e);
                        }
                    }
                }

                if let Some(pipelines_to_close) = pipelines_to_close {
                    for pipeline_id in pipelines_to_close {
                        self.close_pipeline(
                            pipeline_id,
                            DiscardBrowsingContext::No,
                            ExitPipelineMode::Normal,
                        );
                    }
                }
            },
        }

        if let Some(top_level_id) = top_level_id {
            self.trim_history(top_level_id);
        }

        self.notify_history_changed(change.top_level_browsing_context_id);
        self.update_webview_in_compositor(change.top_level_browsing_context_id);
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn focused_browsing_context_is_descendant_of(
        &self,
        browsing_context_id: BrowsingContextId,
    ) -> bool {
        let focused_browsing_context_id = self
            .webviews
            .focused_webview()
            .map(|(_, webview)| webview.focused_browsing_context_id);
        focused_browsing_context_id.is_some_and(|focus_ctx_id| {
            focus_ctx_id == browsing_context_id ||
                self.fully_active_descendant_browsing_contexts_iter(browsing_context_id)
                    .any(|nested_ctx| nested_ctx.id == focus_ctx_id)
        })
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn trim_history(&mut self, top_level_browsing_context_id: TopLevelBrowsingContextId) {
        let pipelines_to_evict = {
            let session_history = self.get_joint_session_history(top_level_browsing_context_id);

            let history_length = pref!(session_history.max_length) as usize;

            // The past is stored with older entries at the front.
            // We reverse the iter so that newer entries are at the front and then
            // skip _n_ entries and evict the remaining entries.
            let mut pipelines_to_evict = session_history
                .past
                .iter()
                .rev()
                .map(|diff| diff.alive_old_pipeline())
                .skip(history_length)
                .flatten()
                .collect::<Vec<_>>();

            // The future is stored with oldest entries front, so we must
            // reverse the iterator like we do for the `past`.
            pipelines_to_evict.extend(
                session_history
                    .future
                    .iter()
                    .rev()
                    .map(|diff| diff.alive_new_pipeline())
                    .skip(history_length)
                    .flatten(),
            );

            pipelines_to_evict
        };

        let mut dead_pipelines = vec![];
        for evicted_id in pipelines_to_evict {
            let load_data = match self.pipelines.get(&evicted_id) {
                Some(pipeline) => {
                    let mut load_data = pipeline.load_data.clone();
                    load_data.url = pipeline.url.clone();
                    load_data
                },
                None => continue,
            };

            dead_pipelines.push((evicted_id, NeedsToReload::Yes(evicted_id, load_data)));
            self.close_pipeline(
                evicted_id,
                DiscardBrowsingContext::No,
                ExitPipelineMode::Normal,
            );
        }

        let session_history = self.get_joint_session_history(top_level_browsing_context_id);

        for (alive_id, dead) in dead_pipelines {
            session_history.replace_reloader(NeedsToReload::No(alive_id), dead);
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_activate_document_msg(&mut self, pipeline_id: PipelineId) {
        debug!("{}: Document ready to activate", pipeline_id);

        // Find the pending change whose new pipeline id is pipeline_id.
        let pending_index = self
            .pending_changes
            .iter()
            .rposition(|change| change.new_pipeline_id == pipeline_id);

        // If it is found, remove it from the pending changes, and make it
        // the active document of its frame.
        if let Some(pending_index) = pending_index {
            let change = self.pending_changes.swap_remove(pending_index);
            // Notify the parent (if there is one).
            let parent_pipeline_id = match change.new_browsing_context_info {
                // This will be a new browsing context.
                Some(ref info) => info.parent_pipeline_id,
                // This is an existing browsing context.
                None => match self.browsing_contexts.get(&change.browsing_context_id) {
                    Some(ctx) => ctx.parent_pipeline_id,
                    None => {
                        return warn!(
                            "{}: Activated document after closure of {}",
                            change.new_pipeline_id, change.browsing_context_id,
                        );
                    },
                },
            };
            if let Some(parent_pipeline_id) = parent_pipeline_id {
                if let Some(parent_pipeline) = self.pipelines.get(&parent_pipeline_id) {
                    let msg = ConstellationControlMsg::UpdatePipelineId(
                        parent_pipeline_id,
                        change.browsing_context_id,
                        change.top_level_browsing_context_id,
                        pipeline_id,
                        UpdatePipelineIdReason::Navigation,
                    );
                    let _ = parent_pipeline.event_loop.send(msg);
                }
            }
            self.change_session_history(change);
        }
    }

    /// Called when the window is resized.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_window_size_msg(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        new_size: WindowSizeData,
        size_type: WindowSizeType,
    ) {
        debug!(
            "handle_window_size_msg: {:?}",
            new_size.initial_viewport.to_untyped()
        );

        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        self.resize_browsing_context(new_size, size_type, browsing_context_id);

        if let Some(response_sender) = self.webdriver.resize_channel.take() {
            let _ = response_sender.send(new_size);
        }

        self.window_size = new_size;
    }

    /// Called when the window exits from fullscreen mode
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_exit_fullscreen_msg(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
    ) {
        let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
        self.switch_fullscreen_mode(browsing_context_id);
    }

    /// Checks the state of all script and layout pipelines to see if they are idle
    /// and compares the current layout state to what the compositor has. This is used
    /// to check if the output image is "stable" and can be written as a screenshot
    /// for reftests.
    /// Since this function is only used in reftests, we do not harden it against panic.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_is_ready_to_save_image(
        &mut self,
        pipeline_states: HashMap<PipelineId, Epoch>,
    ) -> ReadyToSave {
        // Note that this function can panic, due to ipc-channel creation
        // failure. Avoiding this panic would require a mechanism for dealing
        // with low-resource scenarios.
        //
        // If there is no focus browsing context yet, the initial page has
        // not loaded, so there is nothing to save yet.
        let Some(top_level_browsing_context_id) = self.webviews.focused_webview().map(|(id, _)| id)
        else {
            return ReadyToSave::NoTopLevelBrowsingContext;
        };

        // If there are pending loads, wait for those to complete.
        if !self.pending_changes.is_empty() {
            return ReadyToSave::PendingChanges;
        }

        // Step through the fully active browsing contexts, checking that the script thread is idle,
        // and that the current epoch of the layout matches what the compositor has painted. If all
        // these conditions are met, then the output image should not change and a reftest
        // screenshot can safely be written.
        for browsing_context in
            self.fully_active_browsing_contexts_iter(top_level_browsing_context_id)
        {
            let pipeline_id = browsing_context.pipeline_id;
            trace!(
                "{}: Checking readiness of {}",
                browsing_context.id,
                pipeline_id
            );

            let pipeline = match self.pipelines.get(&pipeline_id) {
                None => {
                    warn!("{}: Screenshot while closing", pipeline_id);
                    continue;
                },
                Some(pipeline) => pipeline,
            };

            // See if this pipeline has reached idle script state yet.
            match self.document_states.get(&browsing_context.pipeline_id) {
                Some(&DocumentState::Idle) => {},
                Some(&DocumentState::Pending) | None => {
                    return ReadyToSave::DocumentLoading;
                },
            }

            // Check the visible rectangle for this pipeline. If the constellation has received a
            // size for the pipeline, then its painting should be up to date.
            //
            // If the rectangle for this pipeline is zero sized, it will
            // never be painted. In this case, don't query the layout
            // thread as it won't contribute to the final output image.
            if browsing_context.size == Size2D::zero() {
                continue;
            }

            // Get the epoch that the compositor has drawn for this pipeline and then check if the
            // last laid out epoch matches what the compositor has drawn. If they match (and script
            // is idle) then this pipeline won't change again and can be considered stable.
            let compositor_epoch = pipeline_states.get(&browsing_context.pipeline_id);
            match compositor_epoch {
                Some(compositor_epoch) => {
                    if pipeline.layout_epoch != *compositor_epoch {
                        return ReadyToSave::EpochMismatch;
                    }
                },
                None => {
                    // The compositor doesn't know about this pipeline yet.
                    // Assume it hasn't rendered yet.
                    return ReadyToSave::PipelineUnknown;
                },
            }
        }

        // All script threads are idle and layout epochs match compositor, so output image!
        ReadyToSave::Ready
    }

    /// Get the current activity of a pipeline.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn get_activity(&self, pipeline_id: PipelineId) -> DocumentActivity {
        let mut ancestor_id = pipeline_id;
        loop {
            if let Some(ancestor) = self.pipelines.get(&ancestor_id) {
                if let Some(browsing_context) =
                    self.browsing_contexts.get(&ancestor.browsing_context_id)
                {
                    if browsing_context.pipeline_id == ancestor_id {
                        if let Some(parent_pipeline_id) = browsing_context.parent_pipeline_id {
                            ancestor_id = parent_pipeline_id;
                            continue;
                        } else {
                            return DocumentActivity::FullyActive;
                        }
                    }
                }
            }
            if pipeline_id == ancestor_id {
                return DocumentActivity::Inactive;
            } else {
                return DocumentActivity::Active;
            }
        }
    }

    /// Set the current activity of a pipeline.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn set_activity(&self, pipeline_id: PipelineId, activity: DocumentActivity) {
        debug!("{}: Setting activity to {:?}", pipeline_id, activity);
        if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
            pipeline.set_activity(activity);
            let child_activity = if activity == DocumentActivity::Inactive {
                DocumentActivity::Active
            } else {
                activity
            };
            for child_id in &pipeline.children {
                if let Some(child) = self.browsing_contexts.get(child_id) {
                    self.set_activity(child.pipeline_id, child_activity);
                }
            }
        }
    }

    /// Update the current activity of a pipeline.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn update_activity(&self, pipeline_id: PipelineId) {
        self.set_activity(pipeline_id, self.get_activity(pipeline_id));
    }

    /// Handle updating the size of a browsing context.
    /// This notifies every pipeline in the context of the new size.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn resize_browsing_context(
        &mut self,
        new_size: WindowSizeData,
        size_type: WindowSizeType,
        browsing_context_id: BrowsingContextId,
    ) {
        if let Some(browsing_context) = self.browsing_contexts.get_mut(&browsing_context_id) {
            browsing_context.size = new_size.initial_viewport;
            // Send Resize (or ResizeInactive) messages to each pipeline in the frame tree.
            let pipeline_id = browsing_context.pipeline_id;
            let pipeline = match self.pipelines.get(&pipeline_id) {
                None => return warn!("{}: Resized after closing", pipeline_id),
                Some(pipeline) => pipeline,
            };
            let _ = pipeline.event_loop.send(ConstellationControlMsg::Resize(
                pipeline.id,
                new_size,
                size_type,
            ));
            let pipeline_ids = browsing_context
                .pipelines
                .iter()
                .filter(|pipeline_id| **pipeline_id != pipeline.id);
            for id in pipeline_ids {
                if let Some(pipeline) = self.pipelines.get(id) {
                    let _ = pipeline
                        .event_loop
                        .send(ConstellationControlMsg::ResizeInactive(
                            pipeline.id,
                            new_size,
                        ));
                }
            }
        }

        // Send resize message to any pending pipelines that aren't loaded yet.
        for change in &self.pending_changes {
            let pipeline_id = change.new_pipeline_id;
            let pipeline = match self.pipelines.get(&pipeline_id) {
                None => {
                    warn!("{}: Pending pipeline is closed", pipeline_id);
                    continue;
                },
                Some(pipeline) => pipeline,
            };
            if pipeline.browsing_context_id == browsing_context_id {
                let _ = pipeline.event_loop.send(ConstellationControlMsg::Resize(
                    pipeline.id,
                    new_size,
                    size_type,
                ));
            }
        }
    }

    // Handle switching from fullscreen mode
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn switch_fullscreen_mode(&mut self, browsing_context_id: BrowsingContextId) {
        if let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) {
            let pipeline_id = browsing_context.pipeline_id;
            let pipeline = match self.pipelines.get(&pipeline_id) {
                None => {
                    return warn!(
                        "{}: Switched from fullscreen mode after closing",
                        pipeline_id
                    )
                },
                Some(pipeline) => pipeline,
            };
            let _ = pipeline
                .event_loop
                .send(ConstellationControlMsg::ExitFullScreen(pipeline.id));
        }
    }

    // Close and return the browsing context with the given id (and its children), if it exists.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn close_browsing_context(
        &mut self,
        browsing_context_id: BrowsingContextId,
        exit_mode: ExitPipelineMode,
    ) -> Option<BrowsingContext> {
        debug!("{}: Closing", browsing_context_id);

        self.close_browsing_context_children(
            browsing_context_id,
            DiscardBrowsingContext::Yes,
            exit_mode,
        );

        let browsing_context = match self.browsing_contexts.remove(&browsing_context_id) {
            Some(ctx) => ctx,
            None => {
                warn!("{browsing_context_id}: Closing twice");
                return None;
            },
        };

        {
            let session_history = self.get_joint_session_history(browsing_context.top_level_id);
            session_history.remove_entries_for_browsing_context(browsing_context_id);
        }

        if let Some(parent_pipeline_id) = browsing_context.parent_pipeline_id {
            match self.pipelines.get_mut(&parent_pipeline_id) {
                None => {
                    warn!("{parent_pipeline_id}: Child closed after parent");
                },
                Some(parent_pipeline) => parent_pipeline.remove_child(browsing_context_id),
            };
        }
        debug!("{}: Closed", browsing_context_id);
        Some(browsing_context)
    }

    // Close the children of a browsing context
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn close_browsing_context_children(
        &mut self,
        browsing_context_id: BrowsingContextId,
        dbc: DiscardBrowsingContext,
        exit_mode: ExitPipelineMode,
    ) {
        debug!("{}: Closing browsing context children", browsing_context_id);
        // Store information about the pipelines to be closed. Then close the
        // pipelines, before removing ourself from the browsing_contexts hash map. This
        // ordering is vital - so that if close_pipeline() ends up closing
        // any child browsing contexts, they can be removed from the parent browsing context correctly.
        let mut pipelines_to_close: Vec<PipelineId> = self
            .pending_changes
            .iter()
            .filter(|change| change.browsing_context_id == browsing_context_id)
            .map(|change| change.new_pipeline_id)
            .collect();

        if let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) {
            pipelines_to_close.extend(&browsing_context.pipelines)
        }

        for pipeline_id in pipelines_to_close {
            self.close_pipeline(pipeline_id, dbc, exit_mode);
        }

        debug!("{}: Closed browsing context children", browsing_context_id);
    }

    // Discard the pipeline for a given document, udpdate the joint session history.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_discard_document(
        &mut self,
        top_level_browsing_context_id: TopLevelBrowsingContextId,
        pipeline_id: PipelineId,
    ) {
        match self.webviews.get_mut(top_level_browsing_context_id) {
            Some(webview) => {
                let load_data = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.load_data.clone(),
                    None => return warn!("{}: Discarding closed pipeline", pipeline_id),
                };
                webview.session_history.replace_reloader(
                    NeedsToReload::No(pipeline_id),
                    NeedsToReload::Yes(pipeline_id, load_data),
                );
            },
            None => {
                return warn!(
                    "{}: Discarding after closure of {}",
                    pipeline_id, top_level_browsing_context_id,
                );
            },
        };
        self.close_pipeline(
            pipeline_id,
            DiscardBrowsingContext::No,
            ExitPipelineMode::Normal,
        );
    }

    // Send a message to script requesting the document associated with this pipeline runs the 'unload' algorithm.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn unload_document(&self, pipeline_id: PipelineId) {
        if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
            let msg = ConstellationControlMsg::UnloadDocument(pipeline_id);
            let _ = pipeline.event_loop.send(msg);
        }
    }

    // Close all pipelines at and beneath a given browsing context
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn close_pipeline(
        &mut self,
        pipeline_id: PipelineId,
        dbc: DiscardBrowsingContext,
        exit_mode: ExitPipelineMode,
    ) {
        debug!("{}: Closing", pipeline_id);

        // Sever connection to browsing context
        let browsing_context_id = self
            .pipelines
            .get(&pipeline_id)
            .map(|pipeline| pipeline.browsing_context_id);
        if let Some(browsing_context) = browsing_context_id
            .and_then(|browsing_context_id| self.browsing_contexts.get_mut(&browsing_context_id))
        {
            browsing_context.pipelines.remove(&pipeline_id);
        }

        // Store information about the browsing contexts to be closed. Then close the
        // browsing contexts, before removing ourself from the pipelines hash map. This
        // ordering is vital - so that if close_browsing_context() ends up closing
        // any child pipelines, they can be removed from the parent pipeline correctly.
        let browsing_contexts_to_close = {
            let mut browsing_contexts_to_close = vec![];

            if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
                browsing_contexts_to_close.extend_from_slice(&pipeline.children);
            }

            browsing_contexts_to_close
        };

        // Remove any child browsing contexts
        for child_browsing_context in &browsing_contexts_to_close {
            self.close_browsing_context(*child_browsing_context, exit_mode);
        }

        // Note, we don't remove the pipeline now, we wait for the message to come back from
        // the pipeline.
        let pipeline = match self.pipelines.get(&pipeline_id) {
            Some(pipeline) => pipeline,
            None => return warn!("{}: Closing twice", pipeline_id),
        };

        // Remove this pipeline from pending changes if it hasn't loaded yet.
        let pending_index = self
            .pending_changes
            .iter()
            .position(|change| change.new_pipeline_id == pipeline_id);
        if let Some(pending_index) = pending_index {
            self.pending_changes.remove(pending_index);
        }

        // Inform script, compositor that this pipeline has exited.
        match exit_mode {
            ExitPipelineMode::Normal => pipeline.exit(dbc),
            ExitPipelineMode::Force => pipeline.force_exit(dbc),
        }
        debug!("{}: Closed", pipeline_id);
    }

    // Randomly close a pipeline -if --random-pipeline-closure-probability is set
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn maybe_close_random_pipeline(&mut self) {
        match self.random_pipeline_closure {
            Some((ref mut rng, probability)) => {
                if probability <= rng.gen::<f32>() {
                    return;
                }
            },
            _ => return,
        };
        // In order to get repeatability, we sort the pipeline ids.
        let mut pipeline_ids: Vec<&PipelineId> = self.pipelines.keys().collect();
        pipeline_ids.sort();
        if let Some((ref mut rng, probability)) = self.random_pipeline_closure {
            if let Some(pipeline_id) = pipeline_ids.choose(rng) {
                if let Some(pipeline) = self.pipelines.get(pipeline_id) {
                    if self
                        .pending_changes
                        .iter()
                        .any(|change| change.new_pipeline_id == pipeline.id) &&
                        probability <= rng.gen::<f32>()
                    {
                        // We tend not to close pending pipelines, as that almost always
                        // results in pipelines being closed early in their lifecycle,
                        // and not stressing the constellation as much.
                        // https://github.com/servo/servo/issues/18852
                        info!("{}: Not closing pending pipeline", pipeline_id);
                    } else {
                        // Note that we deliberately do not do any of the tidying up
                        // associated with closing a pipeline. The constellation should cope!
                        warn!("{}: Randomly closing pipeline", pipeline_id);
                        pipeline.force_exit(DiscardBrowsingContext::No);
                    }
                }
            }
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn get_joint_session_history(
        &mut self,
        top_level_id: TopLevelBrowsingContextId,
    ) -> &mut JointSessionHistory {
        self.webviews
            .get_mut(top_level_id)
            .map(|webview| &mut webview.session_history)
            .expect("Unknown top-level browsing context")
    }

    // Convert a browsing context to a sendable form to pass to the compositor
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn browsing_context_to_sendable(
        &self,
        browsing_context_id: BrowsingContextId,
    ) -> Option<SendableFrameTree> {
        self.browsing_contexts
            .get(&browsing_context_id)
            .and_then(|browsing_context| {
                self.pipelines
                    .get(&browsing_context.pipeline_id)
                    .map(|pipeline| {
                        let mut frame_tree = SendableFrameTree {
                            pipeline: pipeline.to_sendable(),
                            children: vec![],
                        };

                        for child_browsing_context_id in &pipeline.children {
                            if let Some(child) =
                                self.browsing_context_to_sendable(*child_browsing_context_id)
                            {
                                frame_tree.children.push(child);
                            }
                        }

                        frame_tree
                    })
            })
    }

    /// Send the frame tree for the given webview to the compositor.
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn update_webview_in_compositor(&mut self, webview_id: WebViewId) {
        // Note that this function can panic, due to ipc-channel creation failure.
        // avoiding this panic would require a mechanism for dealing
        // with low-resource scenarios.
        let browsing_context_id = BrowsingContextId::from(webview_id);
        if let Some(frame_tree) = self.browsing_context_to_sendable(browsing_context_id) {
            debug!("{}: Sending frame tree", browsing_context_id);
            self.compositor_proxy
                .send(CompositorMsg::CreateOrUpdateWebView(frame_tree));
        }
    }

    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_media_session_action_msg(&mut self, action: MediaSessionActionType) {
        if let Some(media_session_pipeline_id) = self.active_media_session {
            let result = match self.pipelines.get(&media_session_pipeline_id) {
                None => {
                    return warn!(
                        "{}: Got media session action request after closure",
                        media_session_pipeline_id,
                    )
                },
                Some(pipeline) => {
                    let msg = ConstellationControlMsg::MediaSessionAction(
                        media_session_pipeline_id,
                        action,
                    );
                    pipeline.event_loop.send(msg)
                },
            };
            if let Err(e) = result {
                self.handle_send_error(media_session_pipeline_id, e);
            }
        } else {
            error!("Got a media session action but no active media session is registered");
        }
    }

    /// Handle GamepadEvents from the embedder and forward them to the script thread
    #[tracing::instrument(skip(self), fields(servo_profiling = true))]
    fn handle_gamepad_msg(&mut self, event: GamepadEvent) {
        // Send to the focused browsing contexts' current pipeline.
        let focused_browsing_context_id = self
            .webviews
            .focused_webview()
            .map(|(_, webview)| webview.focused_browsing_context_id);
        match focused_browsing_context_id {
            Some(browsing_context_id) => {
                let event = CompositorEvent::GamepadEvent(event);
                let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
                    Some(ctx) => ctx.pipeline_id,
                    None => {
                        return warn!(
                            "{}: Got gamepad event for nonexistent browsing context",
                            browsing_context_id,
                        );
                    },
                };
                let msg = ConstellationControlMsg::SendEvent(pipeline_id, event);
                let result = match self.pipelines.get(&pipeline_id) {
                    Some(pipeline) => pipeline.event_loop.send(msg),
                    None => {
                        return debug!("{}: Got gamepad event after closure", pipeline_id);
                    },
                };
                if let Err(e) = result {
                    self.handle_send_error(pipeline_id, e);
                }
            },
            None => {
                warn!("No focused webview to handle gamepad event");
            },
        }
    }
}