summaryrefslogtreecommitdiffstats
path: root/browser/components/sessionstore/SessionStore.sys.mjs
blob: f269251f546fcc767ccc1e9a98208f9176b51794 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
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
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
/* 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 http://mozilla.org/MPL/2.0/. */

// Current version of the format used by Session Restore.
const FORMAT_VERSION = 1;

const PERSIST_SESSIONS = Services.prefs.getBoolPref(
  "browser.sessionstore.persist_closed_tabs_between_sessions"
);
const TAB_CUSTOM_VALUES = new WeakMap();
const TAB_LAZY_STATES = new WeakMap();
const TAB_STATE_NEEDS_RESTORE = 1;
const TAB_STATE_RESTORING = 2;
const TAB_STATE_FOR_BROWSER = new WeakMap();
const WINDOW_RESTORE_IDS = new WeakMap();
const WINDOW_RESTORE_ZINDICES = new WeakMap();
const WINDOW_SHOWING_PROMISES = new Map();
const WINDOW_FLUSHING_PROMISES = new Map();

// A new window has just been restored. At this stage, tabs are generally
// not restored.
const NOTIFY_SINGLE_WINDOW_RESTORED = "sessionstore-single-window-restored";
const NOTIFY_WINDOWS_RESTORED = "sessionstore-windows-restored";
const NOTIFY_BROWSER_STATE_RESTORED = "sessionstore-browser-state-restored";
const NOTIFY_LAST_SESSION_CLEARED = "sessionstore-last-session-cleared";
const NOTIFY_RESTORING_ON_STARTUP = "sessionstore-restoring-on-startup";
const NOTIFY_INITIATING_MANUAL_RESTORE =
  "sessionstore-initiating-manual-restore";
const NOTIFY_CLOSED_OBJECTS_CHANGED = "sessionstore-closed-objects-changed";

const NOTIFY_TAB_RESTORED = "sessionstore-debug-tab-restored"; // WARNING: debug-only
const NOTIFY_DOMWINDOWCLOSED_HANDLED =
  "sessionstore-debug-domwindowclosed-handled"; // WARNING: debug-only

const NOTIFY_BROWSER_SHUTDOWN_FLUSH = "sessionstore-browser-shutdown-flush";

// Maximum number of tabs to restore simultaneously. Previously controlled by
// the browser.sessionstore.max_concurrent_tabs pref.
const MAX_CONCURRENT_TAB_RESTORES = 3;

// Minimum amount (in CSS px) by which we allow window edges to be off-screen
// when restoring a window, before we override the saved position to pull the
// window back within the available screen area.
const MIN_SCREEN_EDGE_SLOP = 8;

// global notifications observed
const OBSERVING = [
  "browser-window-before-show",
  "domwindowclosed",
  "quit-application-granted",
  "browser-lastwindow-close-granted",
  "quit-application",
  "browser:purge-session-history",
  "browser:purge-session-history-for-domain",
  "idle-daily",
  "clear-origin-attributes-data",
  "browsing-context-did-set-embedder",
  "browsing-context-discarded",
  "browser-shutdown-tabstate-updated",
];

// XUL Window properties to (re)store
// Restored in restoreDimensions()
const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"];

const CHROME_FLAGS_MAP = [
  [Ci.nsIWebBrowserChrome.CHROME_TITLEBAR, "titlebar"],
  [Ci.nsIWebBrowserChrome.CHROME_WINDOW_CLOSE, "close"],
  [Ci.nsIWebBrowserChrome.CHROME_TOOLBAR, "toolbar"],
  [Ci.nsIWebBrowserChrome.CHROME_LOCATIONBAR, "location"],
  [Ci.nsIWebBrowserChrome.CHROME_PERSONAL_TOOLBAR, "personalbar"],
  [Ci.nsIWebBrowserChrome.CHROME_STATUSBAR, "status"],
  [Ci.nsIWebBrowserChrome.CHROME_MENUBAR, "menubar"],
  [Ci.nsIWebBrowserChrome.CHROME_WINDOW_RESIZE, "resizable"],
  [Ci.nsIWebBrowserChrome.CHROME_WINDOW_MINIMIZE, "minimizable"],
  [Ci.nsIWebBrowserChrome.CHROME_SCROLLBARS, "", "scrollbars=0"],
  [Ci.nsIWebBrowserChrome.CHROME_PRIVATE_WINDOW, "private"],
  [Ci.nsIWebBrowserChrome.CHROME_NON_PRIVATE_WINDOW, "non-private"],
  // Do not inherit remoteness and fissionness from the previous session.
  //[Ci.nsIWebBrowserChrome.CHROME_REMOTE_WINDOW, "remote", "non-remote"],
  //[Ci.nsIWebBrowserChrome.CHROME_FISSION_WINDOW, "fission", "non-fission"],
  [Ci.nsIWebBrowserChrome.CHROME_WINDOW_LOWERED, "alwayslowered"],
  [Ci.nsIWebBrowserChrome.CHROME_WINDOW_RAISED, "alwaysraised"],
  // "chrome" and "suppressanimation" are always set.
  //[Ci.nsIWebBrowserChrome.CHROME_SUPPRESS_ANIMATION, "suppressanimation"],
  [Ci.nsIWebBrowserChrome.CHROME_ALWAYS_ON_TOP, "alwaysontop"],
  //[Ci.nsIWebBrowserChrome.CHROME_OPENAS_CHROME, "chrome", "chrome=0"],
  [Ci.nsIWebBrowserChrome.CHROME_EXTRA, "extrachrome"],
  [Ci.nsIWebBrowserChrome.CHROME_CENTER_SCREEN, "centerscreen"],
  [Ci.nsIWebBrowserChrome.CHROME_DEPENDENT, "dependent"],
  [Ci.nsIWebBrowserChrome.CHROME_MODAL, "modal"],
  [Ci.nsIWebBrowserChrome.CHROME_OPENAS_DIALOG, "dialog", "dialog=0"],
];

// Hideable window features to (re)store
// Restored in restoreWindowFeatures()
const WINDOW_HIDEABLE_FEATURES = [
  "menubar",
  "toolbar",
  "locationbar",
  "personalbar",
  "statusbar",
  "scrollbars",
];

const WINDOW_OPEN_FEATURES_MAP = {
  locationbar: "location",
  statusbar: "status",
};

// Messages that will be received via the Frame Message Manager.
const MESSAGES = [
  // The content script sends us data that has been invalidated and needs to
  // be saved to disk.
  "SessionStore:update",

  // The restoreHistory code has run. This is a good time to run SSTabRestoring.
  "SessionStore:restoreHistoryComplete",

  // The load for the restoring tab has begun. We update the URL bar at this
  // time; if we did it before, the load would overwrite it.
  "SessionStore:restoreTabContentStarted",

  // All network loads for a restoring tab are done, so we should
  // consider restoring another tab in the queue. The document has
  // been restored, and forms have been filled. We trigger
  // SSTabRestored at this time.
  "SessionStore:restoreTabContentComplete",

  // The content script encountered an error.
  "SessionStore:error",
];

// The list of messages we accept from <xul:browser>s that have no tab
// assigned, or whose windows have gone away. Those are for example the
// ones that preload about:newtab pages, or from browsers where the window
// has just been closed.
const NOTAB_MESSAGES = new Set([
  // For a description see above.
  "SessionStore:update",

  // For a description see above.
  "SessionStore:error",
]);

// The list of messages we accept without an "epoch" parameter.
// See getCurrentEpoch() and friends to find out what an "epoch" is.
const NOEPOCH_MESSAGES = new Set([
  // For a description see above.
  "SessionStore:error",
]);

// The list of messages we want to receive even during the short period after a
// frame has been removed from the DOM and before its frame script has finished
// unloading.
const CLOSED_MESSAGES = new Set([
  // For a description see above.
  "SessionStore:update",

  // For a description see above.
  "SessionStore:error",
]);

// These are tab events that we listen to.
const TAB_EVENTS = [
  "TabOpen",
  "TabBrowserInserted",
  "TabClose",
  "TabSelect",
  "TabShow",
  "TabHide",
  "TabPinned",
  "TabUnpinned",
];

const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

/**
 * When calling restoreTabContent, we can supply a reason why
 * the content is being restored. These are those reasons.
 */
const RESTORE_TAB_CONTENT_REASON = {
  /**
   * SET_STATE:
   * We're restoring this tab's content because we're setting
   * state inside this browser tab, probably because the user
   * has asked us to restore a tab (or window, or entire session).
   */
  SET_STATE: 0,
  /**
   * NAVIGATE_AND_RESTORE:
   * We're restoring this tab's content because a navigation caused
   * us to do a remoteness-flip.
   */
  NAVIGATE_AND_RESTORE: 1,
};

// 'browser.startup.page' preference value to resume the previous session.
const BROWSER_STARTUP_RESUME_SESSION = 3;

// Used by SessionHistoryListener.
const kNoIndex = Number.MAX_SAFE_INTEGER;
const kLastIndex = Number.MAX_SAFE_INTEGER - 1;

import { PrivateBrowsingUtils } from "resource://gre/modules/PrivateBrowsingUtils.sys.mjs";

import { TelemetryTimestamps } from "resource://gre/modules/TelemetryTimestamps.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { GlobalState } from "resource:///modules/sessionstore/GlobalState.sys.mjs";

const lazy = {};

XPCOMUtils.defineLazyServiceGetters(lazy, {
  gScreenManager: ["@mozilla.org/gfx/screenmanager;1", "nsIScreenManager"],
});

ChromeUtils.defineESModuleGetters(lazy, {
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.sys.mjs",
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
  DevToolsShim: "chrome://devtools-startup/content/DevToolsShim.sys.mjs",
  E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
  HomePage: "resource:///modules/HomePage.sys.mjs",
  RunState: "resource:///modules/sessionstore/RunState.sys.mjs",
  SessionCookies: "resource:///modules/sessionstore/SessionCookies.sys.mjs",
  SessionFile: "resource:///modules/sessionstore/SessionFile.sys.mjs",
  SessionHistory: "resource://gre/modules/sessionstore/SessionHistory.sys.mjs",
  SessionSaver: "resource:///modules/sessionstore/SessionSaver.sys.mjs",
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
  TabAttributes: "resource:///modules/sessionstore/TabAttributes.sys.mjs",
  TabCrashHandler: "resource:///modules/ContentCrashHandlers.sys.mjs",
  TabState: "resource:///modules/sessionstore/TabState.sys.mjs",
  TabStateCache: "resource:///modules/sessionstore/TabStateCache.sys.mjs",
  TabStateFlusher: "resource:///modules/sessionstore/TabStateFlusher.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

ChromeUtils.defineLazyGetter(lazy, "blankURI", () => {
  return Services.io.newURI("about:blank");
});

/**
 * |true| if we are in debug mode, |false| otherwise.
 * Debug mode is controlled by preference browser.sessionstore.debug
 */
var gDebuggingEnabled = false;

/**
 * A global value to tell that fingerprinting resistance is enabled or not.
 * If it's enabled, the session restore won't restore the window's size and
 * size mode.
 * This value is controlled by preference privacy.resistFingerprinting.
 */
var gResistFingerprintingEnabled = false;

/**
 * @namespace SessionStore
 */
export var SessionStore = {
  get promiseInitialized() {
    return SessionStoreInternal.promiseInitialized;
  },

  get promiseAllWindowsRestored() {
    return SessionStoreInternal.promiseAllWindowsRestored;
  },

  get canRestoreLastSession() {
    return SessionStoreInternal.canRestoreLastSession;
  },

  set canRestoreLastSession(val) {
    SessionStoreInternal.canRestoreLastSession = val;
  },

  get lastClosedObjectType() {
    return SessionStoreInternal.lastClosedObjectType;
  },

  get lastClosedActions() {
    return [...SessionStoreInternal._lastClosedActions];
  },

  get LAST_ACTION_CLOSED_TAB() {
    return SessionStoreInternal._LAST_ACTION_CLOSED_TAB;
  },

  get LAST_ACTION_CLOSED_WINDOW() {
    return SessionStoreInternal._LAST_ACTION_CLOSED_WINDOW;
  },

  get willAutoRestore() {
    return SessionStoreInternal.willAutoRestore;
  },

  init: function ss_init() {
    SessionStoreInternal.init();
  },

  /**
   * Get the collection of all matching windows tracked by SessionStore
   * @param {Window|Object} [aWindowOrOptions] Optionally an options object or a window to used to determine if we're filtering for private or non-private windows
   * @param {boolean} [aWindowOrOptions.private] Determine if we should filter for private or non-private windows
   */
  getWindows(aWindowOrOptions) {
    return SessionStoreInternal.getWindows(aWindowOrOptions);
  },

  /**
   * Get window a given closed tab belongs to
   * @param {integer} aClosedId The closedId of the tab whose window we want to find
   * @param {boolean} [aIncludePrivate] Optionally include private windows when searching for the closed tab
   */
  getWindowForTabClosedId(aClosedId, aIncludePrivate) {
    return SessionStoreInternal.getWindowForTabClosedId(
      aClosedId,
      aIncludePrivate
    );
  },

  getBrowserState: function ss_getBrowserState() {
    return SessionStoreInternal.getBrowserState();
  },

  setBrowserState: function ss_setBrowserState(aState) {
    SessionStoreInternal.setBrowserState(aState);
  },

  getWindowState: function ss_getWindowState(aWindow) {
    return SessionStoreInternal.getWindowState(aWindow);
  },

  setWindowState: function ss_setWindowState(aWindow, aState, aOverwrite) {
    SessionStoreInternal.setWindowState(aWindow, aState, aOverwrite);
  },

  getTabState: function ss_getTabState(aTab) {
    return SessionStoreInternal.getTabState(aTab);
  },

  setTabState: function ss_setTabState(aTab, aState) {
    SessionStoreInternal.setTabState(aTab, aState);
  },

  // Return whether a tab is restoring.
  isTabRestoring(aTab) {
    return TAB_STATE_FOR_BROWSER.has(aTab.linkedBrowser);
  },

  getInternalObjectState(obj) {
    return SessionStoreInternal.getInternalObjectState(obj);
  },

  duplicateTab: function ss_duplicateTab(
    aWindow,
    aTab,
    aDelta = 0,
    aRestoreImmediately = true,
    aOptions = {}
  ) {
    return SessionStoreInternal.duplicateTab(
      aWindow,
      aTab,
      aDelta,
      aRestoreImmediately,
      aOptions
    );
  },

  /**
   * How many tabs were last closed. If multiple tabs were selected and closed together,
   * we'll return that number. Normally the count is 1, or 0 if no tabs have been
   * recently closed in this window.
   * @returns the number of tabs that were last closed.
   */
  getLastClosedTabCount(aWindow) {
    return SessionStoreInternal.getLastClosedTabCount(aWindow);
  },

  resetLastClosedTabCount(aWindow) {
    SessionStoreInternal.resetLastClosedTabCount(aWindow);
  },

  /**
   * Get the number of closed tabs associated with a specific window
   * @param {Window} aWindow
   */
  getClosedTabCountForWindow: function ss_getClosedTabCountForWindow(aWindow) {
    return SessionStoreInternal.getClosedTabCountForWindow(aWindow);
  },

  /**
   * Get the number of closed tabs associated with all matching windows
   * @param {Window|Object} [aOptions]
   *        Either a DOMWindow (see aOptions.sourceWindow) or an object with properties
            to identify which closed tabs to include in the count.
   * @param {Window} aOptions.sourceWindow
            A browser window used to identity privateness.
            When closedTabsFromAllWindows is false, we only count closed tabs assocated with this window.
   * @param {boolean} [aOptions.private = false]
            Explicit indicator to constrain tab count to only private or non-private windows,
   * @param {boolean} [aOptions.closedTabsFromAllWindows]
            Override the value of the closedTabsFromAllWindows preference.
   * @param {boolean} [aOptions.closedTabsFromClosedWindows]
            Override the value of the closedTabsFromClosedWindows preference.
   */
  getClosedTabCount: function ss_getClosedTabCount(aOptions) {
    return SessionStoreInternal.getClosedTabCount(aOptions);
  },

  /**
   * Get the number of closed tabs from recently closed window
   *
   * This is normally only relevant in a non-private window context, as we don't
   * keep data from closed private windows.
   */
  getClosedTabCountFromClosedWindows:
    function ss_getClosedTabCountFromClosedWindows() {
      return SessionStoreInternal.getClosedTabCountFromClosedWindows();
    },

  /**
   * Get the closed tab data associated with this window
   * @param {Window} aWindow
   */
  getClosedTabDataForWindow: function ss_getClosedTabDataForWindow(aWindow) {
    return SessionStoreInternal.getClosedTabDataForWindow(aWindow);
  },

  /**
   * Get the closed tab data associated with all matching windows
   * @param {Window|Object} [aOptions]
   *        Either a DOMWindow (see aOptions.sourceWindow) or an object with properties
            to identify which closed tabs to get data from
   * @param {Window} aOptions.sourceWindow
            A browser window used to identity privateness.
            When closedTabsFromAllWindows is false, we only include closed tabs assocated with this window.
   * @param {boolean} [aOptions.private = false]
            Explicit indicator to constrain tab data to only private or non-private windows,
   * @param {boolean} [aOptions.closedTabsFromAllWindows]
            Override the value of the closedTabsFromAllWindows preference.
   * @param {boolean} [aOptions.closedTabsFromClosedWindows]
            Override the value of the closedTabsFromClosedWindows preference.
   */
  getClosedTabData: function ss_getClosedTabData(aOptions) {
    return SessionStoreInternal.getClosedTabData(aOptions);
  },

  /**
   * Get the closed tab data associated with all closed windows
   * @returns an un-sorted array of tabData for closed tabs from closed windows
   */
  getClosedTabDataFromClosedWindows:
    function ss_getClosedTabDataFromClosedWindows() {
      return SessionStoreInternal.getClosedTabDataFromClosedWindows();
    },

  /**
   * Re-open a closed tab
   * @param {Window|Object} aSource
   *        Either a DOMWindow or an object with properties to resolve to the window
   *        the tab was previously open in.
   * @param {String} aSource.sourceWindowId
            A SessionStore window id used to look up the window where the tab was closed
   * @param {number} aSource.sourceClosedId
            The closedId used to look up the closed window where the tab was closed
   * @param {Integer} [aIndex = 0]
   *        The index of the tab in the closedTabs array (via SessionStore.getClosedTabData), where 0 is most recent.
   * @param {Window} [aTargetWindow = aWindow] Optional window to open the tab into, defaults to current (topWindow).
   * @returns a reference to the reopened tab.
   */
  undoCloseTab: function ss_undoCloseTab(aSource, aIndex, aTargetWindow) {
    return SessionStoreInternal.undoCloseTab(aSource, aIndex, aTargetWindow);
  },

  /**
   * Re-open a tab from a closed window, which corresponds to the closedId
   * @param {Window|Object} aSource
   *        Either a DOMWindow or an object with properties to resolve to the window
   *        the tab was previously open in.
   * @param {String} aSource.sourceWindowId
            A SessionStore window id used to look up the window where the tab was closed
   * @param {number} aSource.sourceClosedId
            The closedId used to look up the closed window where the tab was closed
   * @param {integer} aClosedId
   *        The closedId of the tab or window
   * @param {Window} [aTargetWindow = aWindow] Optional window to open the tab into, defaults to current (topWindow).
   * @returns a reference to the reopened tab.
   */
  undoClosedTabFromClosedWindow: function ss_undoClosedTabFromClosedWindow(
    aSource,
    aClosedId,
    aTargetWindow
  ) {
    return SessionStoreInternal.undoClosedTabFromClosedWindow(
      aSource,
      aClosedId,
      aTargetWindow
    );
  },

  /**
   * Forget a closed tab associated with a given window
   * Removes the record at the given index so it cannot be un-closed or appear
   * in a list of recently-closed tabs
   *
   * @param {Window|Object} aSource
   *        Either a DOMWindow or an object with properties to resolve to the window
   *        the tab was previously open in.
   * @param {String} aSource.sourceWindowId
            A SessionStore window id used to look up the window where the tab was closed
   * @param {number} aSource.sourceClosedId
            The closedId used to look up the closed window where the tab was closed
   * @param {Integer} [aIndex = 0]
   *        The index into the window's list of closed tabs
   * @throws {InvalidArgumentError} if the window is not tracked by SessionStore, or index is out of bounds
   */
  forgetClosedTab: function ss_forgetClosedTab(aSource, aIndex) {
    return SessionStoreInternal.forgetClosedTab(aSource, aIndex);
  },

  /**
   * Forget a closed tab that corresponds to the closedId
   * Removes the record with this closedId so it cannot be un-closed or appear
   * in a list of recently-closed tabs
   *
   * @param {integer} aClosedId
   *        The closedId of the tab
   * @param {Window|Object} aSourceOptions
   *        Either a DOMWindow or an object with properties to resolve to the window
   *        the tab was previously open in.
   * @param {boolean} [aSourceOptions.includePrivate = true]
            If no other means of resolving a source window is given, this flag is used to
            constrain a search across all open window's closed tabs.
   * @param {String} aSourceOptions.sourceWindowId
            A SessionStore window id used to look up the window where the tab was closed
   * @param {number} aSourceOptions.sourceClosedId
            The closedId used to look up the closed window where the tab was closed
   * @throws {InvalidArgumentError} if the closedId doesnt match a closed tab in any window
   */
  forgetClosedTabById: function ss_forgetClosedTabById(
    aClosedId,
    aSourceOptions
  ) {
    SessionStoreInternal.forgetClosedTabById(aClosedId, aSourceOptions);
  },

  /**
   * Forget a closed window.
   * Removes the record with this closedId so it cannot be un-closed or appear
   * in a list of recently-closed windows
   *
   * @param {integer} aClosedId
   *        The closedId of the window
   * @throws {InvalidArgumentError} if the closedId doesnt match a closed window
   */
  forgetClosedWindowById: function ss_forgetClosedWindowById(aClosedId) {
    SessionStoreInternal.forgetClosedWindowById(aClosedId);
  },

  /**
   * Look up the object type ("tab" or "window") for a given closedId
   * @param {integer} aClosedId
   */
  getObjectTypeForClosedId(aClosedId) {
    return SessionStoreInternal.getObjectTypeForClosedId(aClosedId);
  },

  /**
   * Look up a window tracked by SessionStore by its id
   * @param {String} aSessionStoreId
   */
  getWindowById: function ss_getWindowById(aSessionStoreId) {
    return SessionStoreInternal.getWindowById(aSessionStoreId);
  },

  getClosedWindowCount: function ss_getClosedWindowCount() {
    return SessionStoreInternal.getClosedWindowCount();
  },

  // this should only be used by one caller (currently restoreLastClosedTabOrWindowOrSession in browser.js)
  popLastClosedAction: function ss_popLastClosedAction() {
    return SessionStoreInternal._lastClosedActions.pop();
  },

  // for testing purposes
  resetLastClosedActions: function ss_resetLastClosedActions() {
    SessionStoreInternal._lastClosedActions = [];
  },

  getClosedWindowData: function ss_getClosedWindowData() {
    return SessionStoreInternal.getClosedWindowData();
  },

  maybeDontRestoreTabs(aWindow) {
    SessionStoreInternal.maybeDontRestoreTabs(aWindow);
  },

  undoCloseWindow: function ss_undoCloseWindow(aIndex) {
    return SessionStoreInternal.undoCloseWindow(aIndex);
  },

  forgetClosedWindow: function ss_forgetClosedWindow(aIndex) {
    return SessionStoreInternal.forgetClosedWindow(aIndex);
  },

  getCustomWindowValue(aWindow, aKey) {
    return SessionStoreInternal.getCustomWindowValue(aWindow, aKey);
  },

  setCustomWindowValue(aWindow, aKey, aStringValue) {
    SessionStoreInternal.setCustomWindowValue(aWindow, aKey, aStringValue);
  },

  deleteCustomWindowValue(aWindow, aKey) {
    SessionStoreInternal.deleteCustomWindowValue(aWindow, aKey);
  },

  getCustomTabValue(aTab, aKey) {
    return SessionStoreInternal.getCustomTabValue(aTab, aKey);
  },

  setCustomTabValue(aTab, aKey, aStringValue) {
    SessionStoreInternal.setCustomTabValue(aTab, aKey, aStringValue);
  },

  deleteCustomTabValue(aTab, aKey) {
    SessionStoreInternal.deleteCustomTabValue(aTab, aKey);
  },

  getLazyTabValue(aTab, aKey) {
    return SessionStoreInternal.getLazyTabValue(aTab, aKey);
  },

  getCustomGlobalValue(aKey) {
    return SessionStoreInternal.getCustomGlobalValue(aKey);
  },

  setCustomGlobalValue(aKey, aStringValue) {
    SessionStoreInternal.setCustomGlobalValue(aKey, aStringValue);
  },

  deleteCustomGlobalValue(aKey) {
    SessionStoreInternal.deleteCustomGlobalValue(aKey);
  },

  persistTabAttribute: function ss_persistTabAttribute(aName) {
    SessionStoreInternal.persistTabAttribute(aName);
  },

  restoreLastSession: function ss_restoreLastSession() {
    SessionStoreInternal.restoreLastSession();
  },

  speculativeConnectOnTabHover(tab) {
    SessionStoreInternal.speculativeConnectOnTabHover(tab);
  },

  getCurrentState(aUpdateAll) {
    return SessionStoreInternal.getCurrentState(aUpdateAll);
  },

  reviveCrashedTab(aTab) {
    return SessionStoreInternal.reviveCrashedTab(aTab);
  },

  reviveAllCrashedTabs() {
    return SessionStoreInternal.reviveAllCrashedTabs();
  },

  updateSessionStoreFromTablistener(
    aBrowser,
    aBrowsingContext,
    aPermanentKey,
    aData,
    aForStorage
  ) {
    return SessionStoreInternal.updateSessionStoreFromTablistener(
      aBrowser,
      aBrowsingContext,
      aPermanentKey,
      aData,
      aForStorage
    );
  },

  getSessionHistory(tab, updatedCallback) {
    return SessionStoreInternal.getSessionHistory(tab, updatedCallback);
  },

  /**
   * Re-open a tab or window which corresponds to the closedId
   *
   * @param {integer} aClosedId
   *        The closedId of the tab or window
   * @param {boolean} [aIncludePrivate = true]
   *        Whether to match the aClosedId to only closed private tabs/windows or non-private
   * @param {Window} [aTargetWindow]
   *        When aClosedId is for a closed tab, which window to re-open the tab into.
   *        Defaults to current (topWindow).
   *
   * @returns a tab or window object
   */
  undoCloseById(aClosedId, aIncludePrivate, aTargetWindow) {
    return SessionStoreInternal.undoCloseById(
      aClosedId,
      aIncludePrivate,
      aTargetWindow
    );
  },

  resetBrowserToLazyState(tab) {
    return SessionStoreInternal.resetBrowserToLazyState(tab);
  },

  maybeExitCrashedState(browser) {
    SessionStoreInternal.maybeExitCrashedState(browser);
  },

  isBrowserInCrashedSet(browser) {
    return SessionStoreInternal.isBrowserInCrashedSet(browser);
  },

  // this is used for testing purposes
  resetNextClosedId() {
    SessionStoreInternal._nextClosedId = 0;
  },

  /**
   * Ensures that session store has registered and started tracking a given window.
   * @param window
   *        Window reference
   */
  ensureInitialized(window) {
    if (SessionStoreInternal._sessionInitialized && !window.__SSi) {
      /*
        We need to check that __SSi is not defined on the window so that if
        onLoad function is in the middle of executing we don't enter the function
        again and try to redeclare the ContentSessionStore script.
       */
      SessionStoreInternal.onLoad(window);
    }
  },

  getCurrentEpoch(browser) {
    return SessionStoreInternal.getCurrentEpoch(browser.permanentKey);
  },

  /**
   * Determines whether the passed version number is compatible with
   * the current version number of the SessionStore.
   *
   * @param version The format and version of the file, as an array, e.g.
   * ["sessionrestore", 1]
   */
  isFormatVersionCompatible(version) {
    if (!version) {
      return false;
    }
    if (!Array.isArray(version)) {
      // Improper format.
      return false;
    }
    if (version[0] != "sessionrestore") {
      // Not a Session Restore file.
      return false;
    }
    let number = Number.parseFloat(version[1]);
    if (Number.isNaN(number)) {
      return false;
    }
    return number <= FORMAT_VERSION;
  },

  /**
   * Filters out not worth-saving tabs from a given browser state object.
   *
   * @param aState (object)
   *        The browser state for which we remove worth-saving tabs.
   *        The given object will be modified.
   */
  keepOnlyWorthSavingTabs(aState) {
    let closedWindowShouldRestore = null;
    for (let i = aState.windows.length - 1; i >= 0; i--) {
      let win = aState.windows[i];
      for (let j = win.tabs.length - 1; j >= 0; j--) {
        let tab = win.tabs[j];
        if (!SessionStoreInternal._shouldSaveTab(tab)) {
          win.tabs.splice(j, 1);
          if (win.selected > j) {
            win.selected--;
          }
        }
      }

      // If it's the last window (and no closedWindow that will restore), keep the window state with no tabs.
      if (
        !win.tabs.length &&
        (aState.windows.length > 1 ||
          closedWindowShouldRestore ||
          (closedWindowShouldRestore == null &&
            (closedWindowShouldRestore = aState._closedWindows.some(
              w => w._shouldRestore
            ))))
      ) {
        aState.windows.splice(i, 1);
        if (aState.selectedWindow > i) {
          aState.selectedWindow--;
        }
      }
    }
  },

  /**
   * Prepares to change the remoteness of the given browser, by ensuring that
   * the local instance of session history is up-to-date.
   */
  async prepareToChangeRemoteness(aTab) {
    await SessionStoreInternal.prepareToChangeRemoteness(aTab);
  },

  finishTabRemotenessChange(aTab, aSwitchId) {
    SessionStoreInternal.finishTabRemotenessChange(aTab, aSwitchId);
  },

  /**
   * Clear session store data for a given private browsing window.
   * @param {ChromeWindow} win - Open private browsing window to clear data for.
   */
  purgeDataForPrivateWindow(win) {
    return SessionStoreInternal.purgeDataForPrivateWindow(win);
  },
};

// Freeze the SessionStore object. We don't want anyone to modify it.
Object.freeze(SessionStore);

/**
 * @namespace SessionStoreInternal
 *
 * @description Internal implementations and helpers for the public SessionStore methods
 */
var SessionStoreInternal = {
  QueryInterface: ChromeUtils.generateQI([
    "nsIObserver",
    "nsISupportsWeakReference",
  ]),

  _globalState: new GlobalState(),

  // A counter to be used to generate a unique ID for each closed tab or window.
  _nextClosedId: 0,

  // During the initial restore and setBrowserState calls tracks the number of
  // windows yet to be restored
  _restoreCount: -1,

  // For each <browser> element, records the SHistoryListener.
  _browserSHistoryListener: new WeakMap(),

  // Tracks the various listeners that are used throughout the restore.
  _restoreListeners: new WeakMap(),

  // Records the promise created in _restoreHistory, which is used to track
  // the completion of the first phase of the restore.
  _tabStateRestorePromises: new WeakMap(),

  // The history data needed to be restored in the parent.
  _tabStateToRestore: new WeakMap(),

  // For each <browser> element, records the current epoch.
  _browserEpochs: new WeakMap(),

  // Any browsers that fires the oop-browser-crashed event gets stored in
  // here - that way we know which browsers to ignore messages from (until
  // they get restored).
  _crashedBrowsers: new WeakSet(),

  // A map (xul:browser -> FrameLoader) that maps a browser to the last
  // associated frameLoader we heard about.
  _lastKnownFrameLoader: new WeakMap(),

  // A map (xul:browser -> object) that maps a browser associated with a
  // recently closed tab to all its necessary state information we need to
  // properly handle final update message.
  _closingTabMap: new WeakMap(),

  // A map (xul:browser -> object) that maps a browser associated with a
  // recently closed tab due to a window closure to the tab state information
  // that is being stored in _closedWindows for that tab.
  _tabClosingByWindowMap: new WeakMap(),

  // A set of window data that has the potential to be saved in the _closedWindows
  // array for the session. We will remove window data from this set whenever
  // forgetClosedWindow is called for the window, or when session history is
  // purged, so that we don't accidentally save that data after the flush has
  // completed. Closed tabs use a more complicated mechanism for this particular
  // problem. When forgetClosedTab is called, the browser is removed from the
  // _closingTabMap, so its data is not recorded. In the purge history case,
  // the closedTabs array per window is overwritten so that once the flush is
  // complete, the tab would only ever add itself to an array that SessionStore
  // no longer cares about. Bug 1230636 has been filed to make the tab case
  // work more like the window case, which is more explicit, and easier to
  // reason about.
  _saveableClosedWindowData: new WeakSet(),

  // whether a setBrowserState call is in progress
  _browserSetState: false,

  // time in milliseconds when the session was started (saved across sessions),
  // defaults to now if no session was restored or timestamp doesn't exist
  _sessionStartTime: Date.now(),

  // states for all currently opened windows
  _windows: {},

  // counter for creating unique window IDs
  _nextWindowID: 0,

  // states for all recently closed windows
  _closedWindows: [],

  // collection of session states yet to be restored
  _statesToRestore: {},

  // counts the number of crashes since the last clean start
  _recentCrashes: 0,

  // whether the last window was closed and should be restored
  _restoreLastWindow: false,

  // number of tabs currently restoring
  _tabsRestoringCount: 0,

  /**
   * @typedef {Object} CloseAction
   * @property {string} type
   *   What the close action acted upon. One of either _LAST_ACTION_CLOSED_TAB or
   *   _LAST_ACTION_CLOSED_WINDOW
   * @property {number} closedId
   *   The unique ID of the item that closed.
   */

  /**
   * An in-order stack of close actions for tabs and windows.
   * @type {CloseAction[]}
   */
  _lastClosedActions: [],

  /**
   * Removes an object from the _lastClosedActions list
   *
   * @param closedAction
   *        Either _LAST_ACTION_CLOSED_TAB or _LAST_ACTION_CLOSED_WINDOW
   * @param {integer} closedId
   *        The closedId of a tab or window
   */
  _removeClosedAction(closedAction, closedId) {
    let closedActionIndex = this._lastClosedActions.findIndex(
      obj => obj.type == closedAction && obj.closedId == closedId
    );

    if (closedActionIndex > -1) {
      this._lastClosedActions.splice(closedActionIndex, 1);
    }
  },

  /**
   * Add an object to the _lastClosedActions list and truncates the list if needed
   *
   * @param closedAction
   *        Either _LAST_ACTION_CLOSED_TAB or _LAST_ACTION_CLOSED_WINDOW
   * @param {integer} closedId
   *        The closedId of a tab or window
   */
  _addClosedAction(closedAction, closedId) {
    this._lastClosedActions.push({
      type: closedAction,
      closedId,
    });
    let maxLength = this._max_tabs_undo * this._max_windows_undo;

    if (this._lastClosedActions.length > maxLength) {
      this._lastClosedActions = this._lastClosedActions.slice(-maxLength);
    }
  },

  _LAST_ACTION_CLOSED_TAB: "tab",

  _LAST_ACTION_CLOSED_WINDOW: "window",

  _log: null,

  // When starting Firefox with a single private window, this is the place
  // where we keep the session we actually wanted to restore in case the user
  // decides to later open a non-private window as well.
  _deferredInitialState: null,

  // Keeps track of whether a notification needs to be sent that closed objects have changed.
  _closedObjectsChanged: false,

  // A promise resolved once initialization is complete
  _deferredInitialized: (function () {
    let deferred = {};

    deferred.promise = new Promise((resolve, reject) => {
      deferred.resolve = resolve;
      deferred.reject = reject;
    });

    return deferred;
  })(),

  // Whether session has been initialized
  _sessionInitialized: false,

  // A promise resolved once all windows are restored.
  _deferredAllWindowsRestored: (function () {
    let deferred = {};

    deferred.promise = new Promise((resolve, reject) => {
      deferred.resolve = resolve;
      deferred.reject = reject;
    });

    return deferred;
  })(),

  get promiseAllWindowsRestored() {
    return this._deferredAllWindowsRestored.promise;
  },

  // Promise that is resolved when we're ready to initialize
  // and restore the session.
  _promiseReadyForInitialization: null,

  // Keep busy state counters per window.
  _windowBusyStates: new WeakMap(),

  /**
   * A promise fulfilled once initialization is complete.
   */
  get promiseInitialized() {
    return this._deferredInitialized.promise;
  },

  get canRestoreLastSession() {
    return LastSession.canRestore;
  },

  set canRestoreLastSession(val) {
    // Cheat a bit; only allow false.
    if (!val) {
      LastSession.clear();
    }
  },

  /**
   * Returns a string describing the last closed object, either "tab" or "window".
   *
   * This was added to support the sessions.restore WebExtensions API.
   */
  get lastClosedObjectType() {
    if (this._closedWindows.length) {
      // Since there are closed windows, we need to check if there's a closed tab
      // in one of the currently open windows that was closed after the
      // last-closed window.
      let tabTimestamps = [];
      for (let window of Services.wm.getEnumerator("navigator:browser")) {
        let windowState = this._windows[window.__SSi];
        if (windowState && windowState._closedTabs[0]) {
          tabTimestamps.push(windowState._closedTabs[0].closedAt);
        }
      }
      if (
        !tabTimestamps.length ||
        tabTimestamps.sort((a, b) => b - a)[0] < this._closedWindows[0].closedAt
      ) {
        return this._LAST_ACTION_CLOSED_WINDOW;
      }
    }
    return this._LAST_ACTION_CLOSED_TAB;
  },

  /**
   * Returns a boolean that determines whether the session will be automatically
   * restored upon the _next_ startup or a restart.
   */
  get willAutoRestore() {
    return (
      !PrivateBrowsingUtils.permanentPrivateBrowsing &&
      (Services.prefs.getBoolPref("browser.sessionstore.resume_session_once") ||
        Services.prefs.getIntPref("browser.startup.page") ==
          BROWSER_STARTUP_RESUME_SESSION)
    );
  },

  /**
   * Initialize the sessionstore service.
   */
  init() {
    if (this._initialized) {
      throw new Error("SessionStore.init() must only be called once!");
    }

    TelemetryTimestamps.add("sessionRestoreInitialized");
    OBSERVING.forEach(function (aTopic) {
      Services.obs.addObserver(this, aTopic, true);
    }, this);

    this._initPrefs();
    this._initialized = true;

    Services.telemetry
      .getHistogramById("FX_SESSION_RESTORE_PRIVACY_LEVEL")
      .add(Services.prefs.getIntPref("browser.sessionstore.privacy_level"));
  },

  /**
   * Initialize the session using the state provided by SessionStartup
   */
  initSession() {
    TelemetryStopwatch.start("FX_SESSION_RESTORE_STARTUP_INIT_SESSION_MS");
    let state;
    let ss = lazy.SessionStartup;

    if (ss.willRestore() || ss.sessionType == ss.DEFER_SESSION) {
      state = ss.state;
    }

    if (state) {
      try {
        // If we're doing a DEFERRED session, then we want to pull pinned tabs
        // out so they can be restored.
        if (ss.sessionType == ss.DEFER_SESSION) {
          let [iniState, remainingState] =
            this._prepDataForDeferredRestore(state);
          // If we have a iniState with windows, that means that we have windows
          // with pinned tabs to restore.
          if (iniState.windows.length) {
            state = iniState;
          } else {
            state = null;
          }

          if (remainingState.windows.length) {
            LastSession.setState(remainingState);
          }
          Services.telemetry.keyedScalarAdd(
            "browser.engagement.sessionrestore_interstitial",
            "deferred_restore",
            1
          );
        } else {
          // Get the last deferred session in case the user still wants to
          // restore it
          LastSession.setState(state.lastSessionState);

          let restoreAsCrashed = ss.willRestoreAsCrashed();
          if (restoreAsCrashed) {
            this._recentCrashes =
              ((state.session && state.session.recentCrashes) || 0) + 1;

            // _needsRestorePage will record sessionrestore_interstitial,
            // including the specific reason we decided we needed to show
            // about:sessionrestore, if that's what we do.
            if (this._needsRestorePage(state, this._recentCrashes)) {
              // replace the crashed session with a restore-page-only session
              let url = "about:sessionrestore";
              let formdata = { id: { sessionData: state }, url };
              let entry = {
                url,
                triggeringPrincipal_base64:
                  lazy.E10SUtils.SERIALIZED_SYSTEMPRINCIPAL,
              };
              state = { windows: [{ tabs: [{ entries: [entry], formdata }] }] };
            } else if (
              this._hasSingleTabWithURL(state.windows, "about:welcomeback")
            ) {
              Services.telemetry.keyedScalarAdd(
                "browser.engagement.sessionrestore_interstitial",
                "shown_only_about_welcomeback",
                1
              );
              // On a single about:welcomeback URL that crashed, replace about:welcomeback
              // with about:sessionrestore, to make clear to the user that we crashed.
              state.windows[0].tabs[0].entries[0].url = "about:sessionrestore";
              state.windows[0].tabs[0].entries[0].triggeringPrincipal_base64 =
                lazy.E10SUtils.SERIALIZED_SYSTEMPRINCIPAL;
            } else {
              restoreAsCrashed = false;
            }
          }

          // If we didn't use about:sessionrestore, record that:
          if (!restoreAsCrashed) {
            Services.telemetry.keyedScalarAdd(
              "browser.engagement.sessionrestore_interstitial",
              "autorestore",
              1
            );

            this._removeExplicitlyClosedTabs(state);
          }

          // Update the session start time using the restored session state.
          this._updateSessionStartTime(state);

          // Make sure that at least the first window doesn't have anything hidden.
          delete state.windows[0].hidden;
          // Since nothing is hidden in the first window, it cannot be a popup.
          delete state.windows[0].isPopup;
          // We don't want to minimize and then open a window at startup.
          if (state.windows[0].sizemode == "minimized") {
            state.windows[0].sizemode = "normal";
          }

          // clear any lastSessionWindowID attributes since those don't matter
          // during normal restore
          state.windows.forEach(function (aWindow) {
            delete aWindow.__lastSessionWindowID;
          });
        }

        // clear _maybeDontRestoreTabs because we have restored (or not)
        // windows and so they don't matter
        state?.windows?.forEach(win => delete win._maybeDontRestoreTabs);
        state?._closedWindows?.forEach(win => delete win._maybeDontRestoreTabs);
      } catch (ex) {
        this._log.error("The session file is invalid: " + ex);
      }
    }

    // at this point, we've as good as resumed the session, so we can
    // clear the resume_session_once flag, if it's set
    if (
      !lazy.RunState.isQuitting &&
      this._prefBranch.getBoolPref("sessionstore.resume_session_once")
    ) {
      this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
    }

    TelemetryStopwatch.finish("FX_SESSION_RESTORE_STARTUP_INIT_SESSION_MS");
    return state;
  },

  /**
   * When initializing session, if we are restoring the last session at startup,
   * close open tabs or close windows marked _maybeDontRestoreTabs (if they were closed
   * by closing remaining tabs).
   * See bug 490136
   */
  _removeExplicitlyClosedTabs(state) {
    // Don't restore tabs that has been explicitly closed
    for (let i = 0; i < state.windows.length; ) {
      const winData = state.windows[i];
      if (winData._maybeDontRestoreTabs) {
        if (state.windows.length == 1) {
          // it's the last window, we just want to close tabs
          let j = 0;
          // reset close group (we don't want to append tabs to existing group close).
          winData._lastClosedTabGroupCount = -1;
          while (winData.tabs.length) {
            const tabState = winData.tabs.pop();

            // Ensure the index is in bounds.
            let activeIndex = (tabState.index || tabState.entries.length) - 1;
            activeIndex = Math.min(activeIndex, tabState.entries.length - 1);
            activeIndex = Math.max(activeIndex, 0);

            let title = "";
            if (activeIndex in tabState.entries) {
              title =
                tabState.entries[activeIndex].title ||
                tabState.entries[activeIndex].url;
            }

            const tabData = {
              state: tabState,
              title,
              image: tabState.image,
              pos: j++,
              closedAt: Date.now(),
              closedInGroup: true,
            };
            if (this._shouldSaveTabState(tabState)) {
              this.saveClosedTabData(winData, winData._closedTabs, tabData);
            }
          }
        } else {
          // We can remove the window since it doesn't have any
          // tabs that we should restore and it's not the only window
          if (winData.tabs.some(this._shouldSaveTabState)) {
            winData.closedAt = Date.now();
            state._closedWindows.unshift(winData);
          }
          state.windows.splice(i, 1);
          continue; // we don't want to increment the index
        }
      }
      i++;
    }
  },

  _initPrefs() {
    this._prefBranch = Services.prefs.getBranch("browser.");

    gDebuggingEnabled = this._prefBranch.getBoolPref("sessionstore.debug");

    Services.prefs.addObserver("browser.sessionstore.debug", () => {
      gDebuggingEnabled = this._prefBranch.getBoolPref("sessionstore.debug");
    });

    this._log = console.createInstance({
      prefix: "SessionStore",
      maxLogLevel: gDebuggingEnabled ? "Debug" : "Warn",
    });

    this._max_tabs_undo = this._prefBranch.getIntPref(
      "sessionstore.max_tabs_undo"
    );
    this._prefBranch.addObserver("sessionstore.max_tabs_undo", this, true);

    this._closedTabsFromAllWindowsEnabled = this._prefBranch.getBoolPref(
      "sessionstore.closedTabsFromAllWindows"
    );
    this._prefBranch.addObserver(
      "sessionstore.closedTabsFromAllWindows",
      this,
      true
    );

    this._closedTabsFromClosedWindowsEnabled = this._prefBranch.getBoolPref(
      "sessionstore.closedTabsFromClosedWindows"
    );
    this._prefBranch.addObserver(
      "sessionstore.closedTabsFromClosedWindows",
      this,
      true
    );

    this._max_windows_undo = this._prefBranch.getIntPref(
      "sessionstore.max_windows_undo"
    );
    this._prefBranch.addObserver("sessionstore.max_windows_undo", this, true);

    this._restore_on_demand = this._prefBranch.getBoolPref(
      "sessionstore.restore_on_demand"
    );
    this._prefBranch.addObserver("sessionstore.restore_on_demand", this, true);

    gResistFingerprintingEnabled = Services.prefs.getBoolPref(
      "privacy.resistFingerprinting"
    );
    Services.prefs.addObserver("privacy.resistFingerprinting", this);

    this._shistoryInParent = Services.appinfo.sessionHistoryInParent;
  },

  /**
   * Called on application shutdown, after notifications:
   * quit-application-granted, quit-application
   */
  _uninit: function ssi_uninit() {
    if (!this._initialized) {
      throw new Error("SessionStore is not initialized.");
    }

    // Prepare to close the session file and write the last state.
    lazy.RunState.setClosing();

    // save all data for session resuming
    if (this._sessionInitialized) {
      lazy.SessionSaver.run();
    }

    // clear out priority queue in case it's still holding refs
    TabRestoreQueue.reset();

    // Make sure to cancel pending saves.
    lazy.SessionSaver.cancel();
  },

  /**
   * Handle notifications
   */
  observe: function ssi_observe(aSubject, aTopic, aData) {
    switch (aTopic) {
      case "browser-window-before-show": // catch new windows
        this.onBeforeBrowserWindowShown(aSubject);
        break;
      case "domwindowclosed": // catch closed windows
        this.onClose(aSubject).then(() => {
          this._notifyOfClosedObjectsChange();
        });
        if (gDebuggingEnabled) {
          Services.obs.notifyObservers(null, NOTIFY_DOMWINDOWCLOSED_HANDLED);
        }
        break;
      case "quit-application-granted":
        let syncShutdown = aData == "syncShutdown";
        this.onQuitApplicationGranted(syncShutdown);
        break;
      case "browser-lastwindow-close-granted":
        this.onLastWindowCloseGranted();
        break;
      case "quit-application":
        this.onQuitApplication(aData);
        break;
      case "browser:purge-session-history": // catch sanitization
        this.onPurgeSessionHistory();
        this._notifyOfClosedObjectsChange();
        break;
      case "browser:purge-session-history-for-domain":
        this.onPurgeDomainData(aData);
        this._notifyOfClosedObjectsChange();
        break;
      case "nsPref:changed": // catch pref changes
        this.onPrefChange(aData);
        this._notifyOfClosedObjectsChange();
        break;
      case "idle-daily":
        this.onIdleDaily();
        this._notifyOfClosedObjectsChange();
        break;
      case "clear-origin-attributes-data":
        let userContextId = 0;
        try {
          userContextId = JSON.parse(aData).userContextId;
        } catch (e) {}
        if (userContextId) {
          this._forgetTabsWithUserContextId(userContextId);
        }
        break;
      case "browsing-context-did-set-embedder":
        if (Services.appinfo.sessionHistoryInParent) {
          if (
            aSubject &&
            aSubject === aSubject.top &&
            aSubject.isContent &&
            aSubject.embedderElement &&
            aSubject.embedderElement.permanentKey
          ) {
            let permanentKey = aSubject.embedderElement.permanentKey;
            this._browserSHistoryListener.get(permanentKey)?.unregister();
            this.getOrCreateSHistoryListener(permanentKey, aSubject, true);
          }
        }
        break;
      case "browsing-context-discarded":
        if (Services.appinfo.sessionHistoryInParent) {
          let permanentKey = aSubject?.embedderElement?.permanentKey;
          if (permanentKey) {
            this._browserSHistoryListener.get(permanentKey)?.unregister();
          }
        }
        break;
      case "browser-shutdown-tabstate-updated":
        if (Services.appinfo.sessionHistoryInParent) {
          // Non-SHIP code calls this when the frame script is unloaded.
          this.onFinalTabStateUpdateComplete(aSubject);
        }
        this._notifyOfClosedObjectsChange();
        break;
    }
  },

  getOrCreateSHistoryListener(
    permanentKey,
    browsingContext,
    collectImmediately = false
  ) {
    class SHistoryListener {
      constructor() {
        this.QueryInterface = ChromeUtils.generateQI([
          "nsISHistoryListener",
          "nsISupportsWeakReference",
        ]);

        this._browserId = browsingContext.browserId;
        this._fromIndex = kNoIndex;
      }

      unregister() {
        let bc = BrowsingContext.getCurrentTopByBrowserId(this._browserId);
        bc?.sessionHistory?.removeSHistoryListener(this);
        SessionStoreInternal._browserSHistoryListener.delete(permanentKey);
      }

      collect(
        permanentKey, // eslint-disable-line no-shadow
        browsingContext, // eslint-disable-line no-shadow
        { collectFull = true, writeToCache = false }
      ) {
        // Don't bother doing anything if we haven't seen any navigations.
        if (!collectFull && this._fromIndex === kNoIndex) {
          return null;
        }

        TelemetryStopwatch.start(
          "FX_SESSION_RESTORE_COLLECT_SESSION_HISTORY_MS"
        );

        let fromIndex = collectFull ? -1 : this._fromIndex;
        this._fromIndex = kNoIndex;

        let historychange = lazy.SessionHistory.collectFromParent(
          browsingContext.currentURI?.spec,
          true, // Bug 1704574
          browsingContext.sessionHistory,
          fromIndex
        );

        if (writeToCache) {
          let win =
            browsingContext.embedderElement?.ownerGlobal ||
            browsingContext.currentWindowGlobal?.browsingContext?.window;

          SessionStoreInternal.onTabStateUpdate(permanentKey, win, {
            data: { historychange },
          });
        }

        TelemetryStopwatch.finish(
          "FX_SESSION_RESTORE_COLLECT_SESSION_HISTORY_MS"
        );

        return historychange;
      }

      collectFrom(index) {
        if (this._fromIndex <= index) {
          // If we already know that we need to update history from index N we
          // can ignore any changes that happened with an element with index
          // larger than N.
          //
          // Note: initially we use kNoIndex which is MAX_SAFE_INTEGER which
          // means we don't ignore anything here, and in case of navigation in
          // the history back and forth cases we use kLastIndex which ignores
          // only the subsequent navigations, but not any new elements added.
          return;
        }

        let bc = BrowsingContext.getCurrentTopByBrowserId(this._browserId);
        if (bc?.embedderElement?.frameLoader) {
          this._fromIndex = index;

          // Queue a tab state update on the |browser.sessionstore.interval|
          // timer. We'll call this.collect() when we receive the update.
          bc.embedderElement.frameLoader.requestSHistoryUpdate();
        }
      }

      OnHistoryNewEntry(newURI, oldIndex) {
        // We use oldIndex - 1 to collect the current entry as well. This makes
        // sure to collect any changes that were made to the entry while the
        // document was active.
        this.collectFrom(oldIndex == -1 ? oldIndex : oldIndex - 1);
      }
      OnHistoryGotoIndex() {
        this.collectFrom(kLastIndex);
      }
      OnHistoryPurge() {
        this.collectFrom(-1);
      }
      OnHistoryReload() {
        this.collectFrom(-1);
        return true;
      }
      OnHistoryReplaceEntry() {
        this.collectFrom(-1);
      }
    }

    if (!Services.appinfo.sessionHistoryInParent) {
      throw new Error("This function should only be used with SHIP");
    }

    if (!permanentKey || browsingContext !== browsingContext.top) {
      return null;
    }

    let sessionHistory = browsingContext.sessionHistory;
    if (!sessionHistory) {
      return null;
    }

    let listener = this._browserSHistoryListener.get(permanentKey);
    if (listener) {
      return listener;
    }

    listener = new SHistoryListener();
    sessionHistory.addSHistoryListener(listener);
    this._browserSHistoryListener.set(permanentKey, listener);

    let isAboutBlank = browsingContext.currentURI?.spec === "about:blank";

    if (collectImmediately && (!isAboutBlank || sessionHistory.count !== 0)) {
      listener.collect(permanentKey, browsingContext, { writeToCache: true });
    }

    return listener;
  },

  onTabStateUpdate(permanentKey, win, update) {
    // Ignore messages from <browser> elements that have crashed
    // and not yet been revived.
    if (this._crashedBrowsers.has(permanentKey)) {
      return;
    }

    lazy.TabState.update(permanentKey, update);
    this.saveStateDelayed(win);

    // Handle any updates sent by the child after the tab was closed. This
    // might be the final update as sent by the "unload" handler but also
    // any async update message that was sent before the child unloaded.
    let closedTab = this._closingTabMap.get(permanentKey);
    if (closedTab) {
      // Update the closed tab's state. This will be reflected in its
      // window's list of closed tabs as that refers to the same object.
      lazy.TabState.copyFromCache(permanentKey, closedTab.tabData.state);
    }
  },

  onFinalTabStateUpdateComplete(browser) {
    let permanentKey = browser.permanentKey;
    if (
      this._closingTabMap.has(permanentKey) &&
      !this._crashedBrowsers.has(permanentKey)
    ) {
      let { winData, closedTabs, tabData } =
        this._closingTabMap.get(permanentKey);

      // We expect no further updates.
      this._closingTabMap.delete(permanentKey);

      // The tab state no longer needs this reference.
      delete tabData.permanentKey;

      // Determine whether the tab state is worth saving.
      let shouldSave = this._shouldSaveTabState(tabData.state);
      let index = closedTabs.indexOf(tabData);

      if (shouldSave && index == -1) {
        // If the tab state is worth saving and we didn't push it onto
        // the list of closed tabs when it was closed (because we deemed
        // the state not worth saving) then add it to the window's list
        // of closed tabs now.
        this.saveClosedTabData(winData, closedTabs, tabData);
      } else if (!shouldSave && index > -1) {
        // Remove from the list of closed tabs. The update messages sent
        // after the tab was closed changed enough state so that we no
        // longer consider its data interesting enough to keep around.
        this.removeClosedTabData(winData, closedTabs, index);
      }
    }

    // If this the final message we need to resolve all pending flush
    // requests for the given browser as they might have been sent too
    // late and will never respond. If they have been sent shortly after
    // switching a browser's remoteness there isn't too much data to skip.
    lazy.TabStateFlusher.resolveAll(browser);

    this._browserSHistoryListener.get(permanentKey)?.unregister();
    this._restoreListeners.get(permanentKey)?.unregister();

    Services.obs.notifyObservers(browser, NOTIFY_BROWSER_SHUTDOWN_FLUSH);
  },

  updateSessionStoreFromTablistener(
    browser,
    browsingContext,
    permanentKey,
    update,
    forStorage = false
  ) {
    permanentKey = browser?.permanentKey ?? permanentKey;
    if (!permanentKey) {
      return;
    }

    // Ignore sessionStore update from previous epochs
    if (!this.isCurrentEpoch(permanentKey, update.epoch)) {
      return;
    }

    if (browsingContext.isReplaced) {
      return;
    }

    if (Services.appinfo.sessionHistoryInParent) {
      let listener = this.getOrCreateSHistoryListener(
        permanentKey,
        browsingContext
      );

      if (listener) {
        let historychange =
          // If it is not the scheduled update (tab closed, window closed etc),
          // try to store the loading non-web-controlled page opened in _blank
          // first.
          (forStorage &&
            lazy.SessionHistory.collectNonWebControlledBlankLoadingSession(
              browsingContext
            )) ||
          listener.collect(permanentKey, browsingContext, {
            collectFull: !!update.sHistoryNeeded,
            writeToCache: false,
          });

        if (historychange) {
          update.data.historychange = historychange;
        }
      }
    }

    let win =
      browser?.ownerGlobal ??
      browsingContext.currentWindowGlobal?.browsingContext?.window;

    this.onTabStateUpdate(permanentKey, win, update);
  },

  /**
   * This method handles incoming messages sent by the session store content
   * script via the Frame Message Manager or Parent Process Message Manager,
   * and thus enables communication with OOP tabs.
   */
  receiveMessage(aMessage) {
    if (Services.appinfo.sessionHistoryInParent) {
      throw new Error(
        `received unexpected message '${aMessage.name}' with ` +
          `sessionHistoryInParent enabled`
      );
    }

    // If we got here, that means we're dealing with a frame message
    // manager message, so the target will be a <xul:browser>.
    var browser = aMessage.target;
    let win = browser.ownerGlobal;
    let tab = win ? win.gBrowser.getTabForBrowser(browser) : null;

    // Ensure we receive only specific messages from <xul:browser>s that
    // have no tab or window assigned, e.g. the ones that preload
    // about:newtab pages, or windows that have closed.
    if (!tab && !NOTAB_MESSAGES.has(aMessage.name)) {
      throw new Error(
        `received unexpected message '${aMessage.name}' ` +
          `from a browser that has no tab or window`
      );
    }

    let data = aMessage.data || {};
    let hasEpoch = data.hasOwnProperty("epoch");

    // Most messages sent by frame scripts require to pass an epoch.
    if (!hasEpoch && !NOEPOCH_MESSAGES.has(aMessage.name)) {
      throw new Error(`received message '${aMessage.name}' without an epoch`);
    }

    // Ignore messages from previous epochs.
    if (hasEpoch && !this.isCurrentEpoch(browser.permanentKey, data.epoch)) {
      return;
    }

    switch (aMessage.name) {
      case "SessionStore:update":
        // |browser.frameLoader| might be empty if the browser was already
        // destroyed and its tab removed. In that case we still have the last
        // frameLoader we know about to compare.
        let frameLoader =
          browser.frameLoader ||
          this._lastKnownFrameLoader.get(browser.permanentKey);

        // If the message isn't targeting the latest frameLoader discard it.
        if (frameLoader != aMessage.targetFrameLoader) {
          return;
        }

        this.onTabStateUpdate(browser.permanentKey, browser.ownerGlobal, data);

        // SHIP code will call this when it receives "browser-shutdown-tabstate-updated"
        if (data.isFinal) {
          if (!Services.appinfo.sessionHistoryInParent) {
            this.onFinalTabStateUpdateComplete(browser);
          }
        } else if (data.flushID) {
          // This is an update kicked off by an async flush request. Notify the
          // TabStateFlusher so that it can finish the request and notify its
          // consumer that's waiting for the flush to be done.
          lazy.TabStateFlusher.resolve(browser, data.flushID);
        }

        break;
      case "SessionStore:restoreHistoryComplete":
        this._restoreHistoryComplete(browser, data);
        break;
      case "SessionStore:restoreTabContentStarted":
        this._restoreTabContentStarted(browser, data);
        break;
      case "SessionStore:restoreTabContentComplete":
        this._restoreTabContentComplete(browser, data);
        break;
      case "SessionStore:error":
        lazy.TabStateFlusher.resolveAll(
          browser,
          false,
          "Received error from the content process"
        );
        break;
      default:
        throw new Error(`received unknown message '${aMessage.name}'`);
    }
  },

  /* ........ Window Event Handlers .............. */

  /**
   * Implement EventListener for handling various window and tab events
   */
  handleEvent: function ssi_handleEvent(aEvent) {
    let win = aEvent.currentTarget.ownerGlobal;
    let target = aEvent.originalTarget;
    switch (aEvent.type) {
      case "TabOpen":
        this.onTabAdd(win);
        break;
      case "TabBrowserInserted":
        this.onTabBrowserInserted(win, target);
        break;
      case "TabClose":
        // `adoptedBy` will be set if the tab was closed because it is being
        // moved to a new window.
        if (aEvent.detail.adoptedBy) {
          this.onMoveToNewWindow(
            target.linkedBrowser,
            aEvent.detail.adoptedBy.linkedBrowser
          );
        } else if (!aEvent.detail.skipSessionStore) {
          // `skipSessionStore` is set by tab close callers to indicate that we
          // shouldn't record the closed tab.
          this.onTabClose(win, target);
        }
        this.onTabRemove(win, target);
        this._notifyOfClosedObjectsChange();
        break;
      case "TabSelect":
        this.onTabSelect(win);
        break;
      case "TabShow":
        this.onTabShow(win, target);
        break;
      case "TabHide":
        this.onTabHide(win, target);
        break;
      case "TabPinned":
      case "TabUnpinned":
      case "SwapDocShells":
        this.saveStateDelayed(win);
        break;
      case "oop-browser-crashed":
      case "oop-browser-buildid-mismatch":
        if (aEvent.isTopFrame) {
          this.onBrowserCrashed(target);
        }
        break;
      case "XULFrameLoaderCreated":
        if (
          target.namespaceURI == XUL_NS &&
          target.localName == "browser" &&
          target.frameLoader &&
          target.permanentKey
        ) {
          this._lastKnownFrameLoader.set(
            target.permanentKey,
            target.frameLoader
          );
          this.resetEpoch(target.permanentKey, target.frameLoader);
        }
        break;
      default:
        throw new Error(`unhandled event ${aEvent.type}?`);
    }
    this._clearRestoringWindows();
  },

  /**
   * Generate a unique window identifier
   * @return string
   *         A unique string to identify a window
   */
  _generateWindowID: function ssi_generateWindowID() {
    return "window" + this._nextWindowID++;
  },

  /**
   * Registers and tracks a given window.
   *
   * @param aWindow
   *        Window reference
   */
  onLoad(aWindow) {
    // return if window has already been initialized
    if (aWindow && aWindow.__SSi && this._windows[aWindow.__SSi]) {
      return;
    }

    // ignore windows opened while shutting down
    if (lazy.RunState.isQuitting) {
      return;
    }

    // Assign the window a unique identifier we can use to reference
    // internal data about the window.
    aWindow.__SSi = this._generateWindowID();

    if (!Services.appinfo.sessionHistoryInParent) {
      let mm = aWindow.getGroupMessageManager("browsers");
      MESSAGES.forEach(msg => {
        let listenWhenClosed = CLOSED_MESSAGES.has(msg);
        mm.addMessageListener(msg, this, listenWhenClosed);
      });

      // Load the frame script after registering listeners.
      mm.loadFrameScript(
        "chrome://browser/content/content-sessionStore.js",
        true,
        true
      );
    }

    // and create its data object
    this._windows[aWindow.__SSi] = {
      tabs: [],
      selected: 0,
      _closedTabs: [],
      _lastClosedTabGroupCount: -1,
      busy: false,
      chromeFlags: aWindow.docShell.treeOwner
        .QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIAppWindow).chromeFlags,
    };

    if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
      this._windows[aWindow.__SSi].isPrivate = true;
    }
    if (!this._isWindowLoaded(aWindow)) {
      this._windows[aWindow.__SSi]._restoring = true;
    }
    if (!aWindow.toolbar.visible) {
      this._windows[aWindow.__SSi].isPopup = true;
    }

    let tabbrowser = aWindow.gBrowser;

    // add tab change listeners to all already existing tabs
    for (let i = 0; i < tabbrowser.tabs.length; i++) {
      this.onTabBrowserInserted(aWindow, tabbrowser.tabs[i]);
    }
    // notification of tab add/remove/selection/show/hide
    TAB_EVENTS.forEach(function (aEvent) {
      tabbrowser.tabContainer.addEventListener(aEvent, this, true);
    }, this);

    // Keep track of a browser's latest frameLoader.
    aWindow.gBrowser.addEventListener("XULFrameLoaderCreated", this);
  },

  /**
   * Initializes a given window.
   *
   * Windows are registered as soon as they are created but we need to wait for
   * the session file to load, and the initial window's delayed startup to
   * finish before initializing a window, i.e. restoring data into it.
   *
   * @param aWindow
   *        Window reference
   * @param aInitialState
   *        The initial state to be loaded after startup (optional)
   */
  initializeWindow(aWindow, aInitialState = null) {
    let isPrivateWindow = PrivateBrowsingUtils.isWindowPrivate(aWindow);

    // perform additional initialization when the first window is loading
    if (lazy.RunState.isStopped) {
      lazy.RunState.setRunning();

      // restore a crashed session resp. resume the last session if requested
      if (aInitialState) {
        // Don't write to disk right after startup. Set the last time we wrote
        // to disk to NOW() to enforce a full interval before the next write.
        lazy.SessionSaver.updateLastSaveTime();

        if (isPrivateWindow) {
          // We're starting with a single private window. Save the state we
          // actually wanted to restore so that we can do it later in case
          // the user opens another, non-private window.
          this._deferredInitialState = lazy.SessionStartup.state;

          // Nothing to restore now, notify observers things are complete.
          Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED);
          Services.obs.notifyObservers(
            null,
            "sessionstore-one-or-no-tab-restored"
          );
          this._deferredAllWindowsRestored.resolve();
        } else {
          TelemetryTimestamps.add("sessionRestoreRestoring");
          this._restoreCount = aInitialState.windows
            ? aInitialState.windows.length
            : 0;

          // global data must be restored before restoreWindow is called so that
          // it happens before observers are notified
          this._globalState.setFromState(aInitialState);

          // Restore session cookies before loading any tabs.
          lazy.SessionCookies.restore(aInitialState.cookies || []);

          let overwrite = this._isCmdLineEmpty(aWindow, aInitialState);
          let options = { firstWindow: true, overwriteTabs: overwrite };
          this.restoreWindows(aWindow, aInitialState, options);
        }
      } else {
        // Nothing to restore, notify observers things are complete.
        Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED);
        Services.obs.notifyObservers(
          null,
          "sessionstore-one-or-no-tab-restored"
        );
        this._deferredAllWindowsRestored.resolve();
      }
      // this window was opened by _openWindowWithState
    } else if (!this._isWindowLoaded(aWindow)) {
      // We want to restore windows after all windows have opened (since bug
      // 1034036), so bail out here.
      return;
      // The user opened another, non-private window after starting up with
      // a single private one. Let's restore the session we actually wanted to
      // restore at startup.
    } else if (
      this._deferredInitialState &&
      !isPrivateWindow &&
      aWindow.toolbar.visible
    ) {
      // global data must be restored before restoreWindow is called so that
      // it happens before observers are notified
      this._globalState.setFromState(this._deferredInitialState);

      this._restoreCount = this._deferredInitialState.windows
        ? this._deferredInitialState.windows.length
        : 0;
      this.restoreWindows(aWindow, this._deferredInitialState, {
        firstWindow: true,
      });
      this._deferredInitialState = null;
    } else if (
      this._restoreLastWindow &&
      aWindow.toolbar.visible &&
      this._closedWindows.length &&
      !isPrivateWindow
    ) {
      // default to the most-recently closed window
      // don't use popup windows
      let closedWindowState = null;
      let closedWindowIndex;
      for (let i = 0; i < this._closedWindows.length; i++) {
        // Take the first non-popup, point our object at it, and break out.
        if (!this._closedWindows[i].isPopup) {
          closedWindowState = this._closedWindows[i];
          closedWindowIndex = i;
          break;
        }
      }

      if (closedWindowState) {
        let newWindowState;
        if (
          AppConstants.platform == "macosx" ||
          !lazy.SessionStartup.willRestore()
        ) {
          // We want to split the window up into pinned tabs and unpinned tabs.
          // Pinned tabs should be restored. If there are any remaining tabs,
          // they should be added back to _closedWindows.
          // We'll cheat a little bit and reuse _prepDataForDeferredRestore
          // even though it wasn't built exactly for this.
          let [appTabsState, normalTabsState] =
            this._prepDataForDeferredRestore({
              windows: [closedWindowState],
            });

          // These are our pinned tabs, which we should restore
          if (appTabsState.windows.length) {
            newWindowState = appTabsState.windows[0];
            delete newWindowState.__lastSessionWindowID;
          }

          // In case there were no unpinned tabs, remove the window from _closedWindows
          if (!normalTabsState.windows.length) {
            this._removeClosedWindow(closedWindowIndex);
            // Or update _closedWindows with the modified state
          } else {
            delete normalTabsState.windows[0].__lastSessionWindowID;
            this._closedWindows[closedWindowIndex] = normalTabsState.windows[0];
          }
        } else {
          // If we're just restoring the window, make sure it gets removed from
          // _closedWindows.
          this._removeClosedWindow(closedWindowIndex);
          newWindowState = closedWindowState;
          delete newWindowState.hidden;
        }

        if (newWindowState) {
          // Ensure that the window state isn't hidden
          this._restoreCount = 1;
          let state = { windows: [newWindowState] };
          let options = { overwriteTabs: this._isCmdLineEmpty(aWindow, state) };
          this.restoreWindow(aWindow, newWindowState, options);
        }
      }
      // we actually restored the session just now.
      this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
    }
    if (this._restoreLastWindow && aWindow.toolbar.visible) {
      // always reset (if not a popup window)
      // we don't want to restore a window directly after, for example,
      // undoCloseWindow was executed.
      this._restoreLastWindow = false;
    }
  },

  /**
   * Called right before a new browser window is shown.
   * @param aWindow
   *        Window reference
   */
  onBeforeBrowserWindowShown(aWindow) {
    // Register the window.
    this.onLoad(aWindow);

    // Some are waiting for this window to be shown, which is now, so let's resolve
    // the deferred operation.
    let deferred = WINDOW_SHOWING_PROMISES.get(aWindow);
    if (deferred) {
      deferred.resolve(aWindow);
      WINDOW_SHOWING_PROMISES.delete(aWindow);
    }

    // Just call initializeWindow() directly if we're initialized already.
    if (this._sessionInitialized) {
      this.initializeWindow(aWindow);
      return;
    }

    // The very first window that is opened creates a promise that is then
    // re-used by all subsequent windows. The promise will be used to tell
    // when we're ready for initialization.
    if (!this._promiseReadyForInitialization) {
      // Wait for the given window's delayed startup to be finished.
      let promise = new Promise(resolve => {
        Services.obs.addObserver(function obs(subject, topic) {
          if (aWindow == subject) {
            Services.obs.removeObserver(obs, topic);
            resolve();
          }
        }, "browser-delayed-startup-finished");
      });

      // We are ready for initialization as soon as the session file has been
      // read from disk and the initial window's delayed startup has finished.
      this._promiseReadyForInitialization = Promise.all([
        promise,
        lazy.SessionStartup.onceInitialized,
      ]);
    }

    // We can't call this.onLoad since initialization
    // hasn't completed, so we'll wait until it is done.
    // Even if additional windows are opened and wait
    // for initialization as well, the first opened
    // window should execute first, and this.onLoad
    // will be called with the initialState.
    this._promiseReadyForInitialization
      .then(() => {
        if (aWindow.closed) {
          return;
        }

        if (this._sessionInitialized) {
          this.initializeWindow(aWindow);
        } else {
          let initialState = this.initSession();
          this._sessionInitialized = true;

          if (initialState) {
            Services.obs.notifyObservers(null, NOTIFY_RESTORING_ON_STARTUP);
          }
          TelemetryStopwatch.start(
            "FX_SESSION_RESTORE_STARTUP_ONLOAD_INITIAL_WINDOW_MS"
          );
          this.initializeWindow(aWindow, initialState);
          TelemetryStopwatch.finish(
            "FX_SESSION_RESTORE_STARTUP_ONLOAD_INITIAL_WINDOW_MS"
          );

          // Let everyone know we're done.
          this._deferredInitialized.resolve();
        }
      })
      .catch(console.error);
  },

  /**
   * On window close...
   * - remove event listeners from tabs
   * - save all window data
   * @param aWindow
   *        Window reference
   *
   * @returns a Promise
   */
  onClose: function ssi_onClose(aWindow) {
    let completionPromise = Promise.resolve();
    // this window was about to be restored - conserve its original data, if any
    let isFullyLoaded = this._isWindowLoaded(aWindow);
    if (!isFullyLoaded) {
      if (!aWindow.__SSi) {
        aWindow.__SSi = this._generateWindowID();
      }

      let restoreID = WINDOW_RESTORE_IDS.get(aWindow);
      this._windows[aWindow.__SSi] =
        this._statesToRestore[restoreID].windows[0];
      delete this._statesToRestore[restoreID];
      WINDOW_RESTORE_IDS.delete(aWindow);
    }

    // ignore windows not tracked by SessionStore
    if (!aWindow.__SSi || !this._windows[aWindow.__SSi]) {
      return completionPromise;
    }

    // notify that the session store will stop tracking this window so that
    // extensions can store any data about this window in session store before
    // that's not possible anymore
    let event = aWindow.document.createEvent("Events");
    event.initEvent("SSWindowClosing", true, false);
    aWindow.dispatchEvent(event);

    if (this.windowToFocus && this.windowToFocus == aWindow) {
      delete this.windowToFocus;
    }

    var tabbrowser = aWindow.gBrowser;

    let browsers = Array.from(tabbrowser.browsers);

    TAB_EVENTS.forEach(function (aEvent) {
      tabbrowser.tabContainer.removeEventListener(aEvent, this, true);
    }, this);

    aWindow.gBrowser.removeEventListener("XULFrameLoaderCreated", this);

    let winData = this._windows[aWindow.__SSi];

    // Collect window data only when *not* closed during shutdown.
    if (lazy.RunState.isRunning) {
      // Grab the most recent window data. The tab data will be updated
      // once we finish flushing all of the messages from the tabs.
      let tabMap = this._collectWindowData(aWindow);

      for (let [tab, tabData] of tabMap) {
        let permanentKey = tab.linkedBrowser.permanentKey;
        this._tabClosingByWindowMap.set(permanentKey, tabData);
      }

      if (isFullyLoaded && !winData.title) {
        winData.title =
          tabbrowser.selectedBrowser.contentTitle ||
          tabbrowser.selectedTab.label;
      }

      if (AppConstants.platform != "macosx") {
        // Until we decide otherwise elsewhere, this window is part of a series
        // of closing windows to quit.
        winData._shouldRestore = true;
      }

      // Store the window's close date to figure out when each individual tab
      // was closed. This timestamp should allow re-arranging data based on how
      // recently something was closed.
      winData.closedAt = Date.now();

      // we don't want to save the busy state
      delete winData.busy;

      // When closing windows one after the other until Firefox quits, we
      // will move those closed in series back to the "open windows" bucket
      // before writing to disk. If however there is only a single window
      // with tabs we deem not worth saving then we might end up with a
      // random closed or even a pop-up window re-opened. To prevent that
      // we explicitly allow saving an "empty" window state.
      let isLastWindow = this.isLastRestorableWindow();

      // clear this window from the list, since it has definitely been closed.
      delete this._windows[aWindow.__SSi];

      // This window has the potential to be saved in the _closedWindows
      // array (maybeSaveClosedWindows gets the final call on that).
      this._saveableClosedWindowData.add(winData);

      // Now we have to figure out if this window is worth saving in the _closedWindows
      // Object.
      //
      // We're about to flush the tabs from this window, but it's possible that we
      // might never hear back from the content process(es) in time before the user
      // chooses to restore the closed window. So we do the following:
      //
      // 1) Use the tab state cache to determine synchronously if the window is
      //    worth stashing in _closedWindows.
      // 2) Flush the window.
      // 3) When the flush is complete, revisit our decision to store the window
      //    in _closedWindows, and add/remove as necessary.
      if (!winData.isPrivate) {
        this.maybeSaveClosedWindow(winData, isLastWindow);
      }

      completionPromise = lazy.TabStateFlusher.flushWindow(aWindow).then(() => {
        // At this point, aWindow is closed! You should probably not try to
        // access any DOM elements from aWindow within this callback unless
        // you're holding on to them in the closure.

        WINDOW_FLUSHING_PROMISES.delete(aWindow);

        for (let browser of browsers) {
          if (this._tabClosingByWindowMap.has(browser.permanentKey)) {
            let tabData = this._tabClosingByWindowMap.get(browser.permanentKey);
            lazy.TabState.copyFromCache(browser.permanentKey, tabData);
            this._tabClosingByWindowMap.delete(browser.permanentKey);
          }
        }

        // Save non-private windows if they have at
        // least one saveable tab or are the last window.
        if (!winData.isPrivate) {
          this.maybeSaveClosedWindow(winData, isLastWindow, true);

          if (!isLastWindow && winData.closedId > -1) {
            this._addClosedAction(
              this._LAST_ACTION_CLOSED_WINDOW,
              winData.closedId
            );
          }
        }

        // Update the tabs data now that we've got the most
        // recent information.
        this.cleanUpWindow(aWindow, winData, browsers);

        // save the state without this window to disk
        this.saveStateDelayed();
      });

      // Here we might override a flush already in flight, but that's fine
      // because `completionPromise` will always resolve after the old flush
      // resolves.
      WINDOW_FLUSHING_PROMISES.set(aWindow, completionPromise);
    } else {
      this.cleanUpWindow(aWindow, winData, browsers);
    }

    for (let i = 0; i < tabbrowser.tabs.length; i++) {
      this.onTabRemove(aWindow, tabbrowser.tabs[i], true);
    }

    return completionPromise;
  },

  /**
   * Clean up the message listeners on a window that has finally
   * gone away. Call this once you're sure you don't want to hear
   * from any of this windows tabs from here forward.
   *
   * @param aWindow
   *        The browser window we're cleaning up.
   * @param winData
   *        The data for the window that we should hold in the
   *        DyingWindowCache in case anybody is still holding a
   *        reference to it.
   */
  cleanUpWindow(aWindow, winData, browsers) {
    // Any leftover TabStateFlusher Promises need to be resolved now,
    // since we're about to remove the message listeners.
    for (let browser of browsers) {
      lazy.TabStateFlusher.resolveAll(browser);
    }

    // Cache the window state until it is completely gone.
    DyingWindowCache.set(aWindow, winData);

    if (!Services.appinfo.sessionHistoryInParent) {
      let mm = aWindow.getGroupMessageManager("browsers");
      MESSAGES.forEach(msg => mm.removeMessageListener(msg, this));
    }

    this._saveableClosedWindowData.delete(winData);
    delete aWindow.__SSi;
  },

  /**
   * Decides whether or not a closed window should be put into the
   * _closedWindows Object. This might be called multiple times per
   * window, and will do the right thing of moving the window data
   * in or out of _closedWindows if the winData indicates that our
   * need for saving it has changed.
   *
   * @param winData
   *        The data for the closed window that we might save.
   * @param isLastWindow
   *        Whether or not the window being closed is the last
   *        browser window. Callers of this function should pass
   *        in the value of SessionStoreInternal.atLastWindow for
   *        this argument, and pass in the same value if they happen
   *        to call this method again asynchronously (for example, after
   *        a window flush).
   */
  maybeSaveClosedWindow(winData, isLastWindow, recordTelemetry = false) {
    // Make sure SessionStore is still running, and make sure that we
    // haven't chosen to forget this window.
    if (
      lazy.RunState.isRunning &&
      this._saveableClosedWindowData.has(winData)
    ) {
      // Determine whether the window has any tabs worth saving.
      // Note: We currently ignore the possibility of useful _closedTabs here.
      // A window with 0 worth-keeping open tabs will not have its state saved, and
      // any _closedTabs will be lost.
      let hasSaveableTabs = winData.tabs.some(this._shouldSaveTabState);

      // Note that we might already have this window stored in
      // _closedWindows from a previous call to this function.
      let winIndex = this._closedWindows.indexOf(winData);
      let alreadyStored = winIndex != -1;
      let shouldStore = hasSaveableTabs || isLastWindow;

      if (shouldStore && !alreadyStored) {
        let index = this._closedWindows.findIndex(win => {
          return win.closedAt < winData.closedAt;
        });

        // If we found no window closed before our
        // window then just append it to the list.
        if (index == -1) {
          index = this._closedWindows.length;
        }

        // About to save the closed window, add a unique ID.
        winData.closedId = this._nextClosedId++;

        // Insert winData at the right position.
        this._closedWindows.splice(index, 0, winData);
        this._capClosedWindows();
        this._closedObjectsChanged = true;
        // The first time we close a window, ensure it can be restored from the
        // hidden window.
        if (
          AppConstants.platform == "macosx" &&
          this._closedWindows.length == 1
        ) {
          // Fake a popupshowing event so shortcuts work:
          let window = Services.appShell.hiddenDOMWindow;
          let historyMenu = window.document.getElementById("history-menu");
          let evt = new window.CustomEvent("popupshowing", { bubbles: true });
          historyMenu.menupopup.dispatchEvent(evt);
        }
      } else if (!shouldStore) {
        if (
          winData._closedTabs.length &&
          this._closedTabsFromAllWindowsEnabled
        ) {
          // we are going to lose closed tabs, so any observers should be notified
          this._closedObjectsChanged = true;
        }
        if (alreadyStored) {
          this._removeClosedWindow(winIndex);
          return;
        }
        // we only do this after the TabStateFlusher promise resolves in ssi_onClose
        if (recordTelemetry) {
          let closedTabsHistogram = Services.telemetry.getHistogramById(
            "FX_SESSION_RESTORE_CLOSED_TABS_NOT_SAVED"
          );
          closedTabsHistogram.add(winData._closedTabs.length);
        }
      }
    }
  },

  /**
   * On quit application granted
   */
  onQuitApplicationGranted: function ssi_onQuitApplicationGranted(
    syncShutdown = false
  ) {
    // Collect an initial snapshot of window data before we do the flush.
    let index = 0;
    for (let window of this._orderedBrowserWindows) {
      this._collectWindowData(window);
      this._windows[window.__SSi].zIndex = ++index;
    }

    // Now add an AsyncShutdown blocker that'll spin the event loop
    // until the windows have all been flushed.

    // This progress object will track the state of async window flushing
    // and will help us debug things that go wrong with our AsyncShutdown
    // blocker.
    let progress = { total: -1, current: -1 };

    // We're going down! Switch state so that we treat closing windows and
    // tabs correctly.
    lazy.RunState.setQuitting();

    if (!syncShutdown) {
      // We've got some time to shut down, so let's do this properly that there
      // will be a complete session available upon next startup.
      // To prevent a blocker from taking longer than the DELAY_CRASH_MS limit
      // (which will cause a crash) of AsyncShutdown whilst flushing all windows,
      // we resolve the Promise blocker once:
      // 1. the flush duration exceeds 10 seconds before DELAY_CRASH_MS, or
      // 2. 'oop-frameloader-crashed', or
      // 3. 'ipc:content-shutdown' is observed.
      lazy.AsyncShutdown.quitApplicationGranted.addBlocker(
        "SessionStore: flushing all windows",
        () => {
          // Set up the list of promises that will signal a complete sessionstore
          // shutdown: either all data is saved, or we crashed or the message IPC
          // channel went away in the meantime.
          let promises = [this.flushAllWindowsAsync(progress)];

          const observeTopic = topic => {
            let deferred = Promise.withResolvers();
            const observer = subject => {
              // Skip abort on ipc:content-shutdown if not abnormal/crashed
              subject.QueryInterface(Ci.nsIPropertyBag2);
              if (
                !(topic == "ipc:content-shutdown" && !subject.get("abnormal"))
              ) {
                deferred.resolve();
              }
            };
            const cleanup = () => {
              try {
                Services.obs.removeObserver(observer, topic);
              } catch (ex) {
                console.error(
                  "SessionStore: exception whilst flushing all windows: ",
                  ex
                );
              }
            };
            Services.obs.addObserver(observer, topic);
            deferred.promise.then(cleanup, cleanup);
            return deferred;
          };

          // Build a list of deferred executions that require cleanup once the
          // Promise race is won.
          // Ensure that the timer fires earlier than the AsyncShutdown crash timer.
          let waitTimeMaxMs = Math.max(
            0,
            lazy.AsyncShutdown.DELAY_CRASH_MS - 10000
          );
          let defers = [
            this.looseTimer(waitTimeMaxMs),

            // FIXME: We should not be aborting *all* flushes when a single
            // content process crashes here.
            observeTopic("oop-frameloader-crashed"),
            observeTopic("ipc:content-shutdown"),
          ];
          // Add these monitors to the list of Promises to start the race.
          promises.push(...defers.map(deferred => deferred.promise));

          return Promise.race(promises).then(() => {
            // When a Promise won the race, make sure we clean up the running
            // monitors.
            defers.forEach(deferred => deferred.reject());
          });
        },
        () => progress
      );
    } else {
      // We have to shut down NOW, which means we only get to save whatever
      // we already had cached.
    }
  },

  /**
   * An async Task that iterates all open browser windows and flushes
   * any outstanding messages from their tabs. This will also close
   * all of the currently open windows while we wait for the flushes
   * to complete.
   *
   * @param progress (Object)
   *        Optional progress object that will be updated as async
   *        window flushing progresses. flushAllWindowsSync will
   *        write to the following properties:
   *
   *        total (int):
   *          The total number of windows to be flushed.
   *        current (int):
   *          The current window that we're waiting for a flush on.
   *
   * @return Promise
   */
  async flushAllWindowsAsync(progress = {}) {
    let windowPromises = new Map(WINDOW_FLUSHING_PROMISES);
    WINDOW_FLUSHING_PROMISES.clear();

    // We collect flush promises and close each window immediately so that
    // the user can't start changing any window state while we're waiting
    // for the flushes to finish.
    for (let window of this._browserWindows) {
      windowPromises.set(window, lazy.TabStateFlusher.flushWindow(window));

      // We have to wait for these messages to come up from
      // each window and each browser. In the meantime, hide
      // the windows to improve perceived shutdown speed.
      let baseWin = window.docShell.treeOwner.QueryInterface(Ci.nsIBaseWindow);
      baseWin.visibility = false;
    }

    progress.total = windowPromises.size;
    progress.current = 0;

    // We'll iterate through the Promise array, yielding each one, so as to
    // provide useful progress information to AsyncShutdown.
    for (let [win, promise] of windowPromises) {
      await promise;

      // We may have already stopped tracking this window in onClose, which is
      // fine as we would've collected window data there as well.
      if (win.__SSi && this._windows[win.__SSi]) {
        this._collectWindowData(win);
      }

      progress.current++;
    }

    // We must cache this because _getTopWindow will always
    // return null by the time quit-application occurs.
    var activeWindow = this._getTopWindow();
    if (activeWindow) {
      this.activeWindowSSiCache = activeWindow.__SSi || "";
    }
    DirtyWindows.clear();
  },

  /**
   * On last browser window close
   */
  onLastWindowCloseGranted: function ssi_onLastWindowCloseGranted() {
    // last browser window is quitting.
    // remember to restore the last window when another browser window is opened
    // do not account for pref(resume_session_once) at this point, as it might be
    // set by another observer getting this notice after us
    this._restoreLastWindow = true;
  },

  /**
   * On quitting application
   * @param aData
   *        String type of quitting
   */
  onQuitApplication: function ssi_onQuitApplication(aData) {
    if (aData == "restart" || aData == "os-restart") {
      if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
        if (
          aData == "os-restart" &&
          !this._prefBranch.getBoolPref("sessionstore.resume_session_once")
        ) {
          this._prefBranch.setBoolPref(
            "sessionstore.resuming_after_os_restart",
            true
          );
        }
        this._prefBranch.setBoolPref("sessionstore.resume_session_once", true);
      }

      // The browser:purge-session-history notification fires after the
      // quit-application notification so unregister the
      // browser:purge-session-history notification to prevent clearing
      // session data on disk on a restart.  It is also unnecessary to
      // perform any other sanitization processing on a restart as the
      // browser is about to exit anyway.
      Services.obs.removeObserver(this, "browser:purge-session-history");
    }

    if (aData != "restart") {
      // Throw away the previous session on shutdown without notification
      LastSession.clear(true);
    }

    this._uninit();
  },

  /**
   * Clear session store data for a given private browsing window.
   * @param {ChromeWindow} win - Open private browsing window to clear data for.
   */
  purgeDataForPrivateWindow(win) {
    // No need to clear data if already shutting down.
    if (lazy.RunState.isQuitting) {
      return;
    }

    // Check if we have data for the given window.
    let windowData = this._windows[win.__SSi];
    if (!windowData) {
      return;
    }

    // Clear closed tab data.
    if (windowData._closedTabs.length) {
      // Remove all of the closed tabs data.
      // This also clears out the permenentKey-mapped data for pending state updates
      // and removes the tabs from from the _lastClosedActions list
      while (windowData._closedTabs.length) {
        this.removeClosedTabData(windowData, windowData._closedTabs, 0);
      }
      // Reset the closed tab list.
      windowData._closedTabs = [];
      windowData._lastClosedTabGroupCount = -1;
      this._closedObjectsChanged = true;
    }
  },

  /**
   * On purge of session history
   */
  onPurgeSessionHistory: function ssi_onPurgeSessionHistory() {
    lazy.SessionFile.wipe();
    // If the browser is shutting down, simply return after clearing the
    // session data on disk as this notification fires after the
    // quit-application notification so the browser is about to exit.
    if (lazy.RunState.isQuitting) {
      return;
    }
    LastSession.clear();

    let openWindows = {};
    // Collect open windows.
    for (let window of this._browserWindows) {
      openWindows[window.__SSi] = true;
    }

    // also clear all data about closed tabs and windows
    for (let ix in this._windows) {
      if (ix in openWindows) {
        if (this._windows[ix]._closedTabs.length) {
          this._windows[ix]._closedTabs = [];
          this._closedObjectsChanged = true;
        }
      } else {
        delete this._windows[ix];
      }
    }
    // also clear all data about closed windows
    if (this._closedWindows.length) {
      this._closedWindows = [];
      this._closedObjectsChanged = true;
    }
    // give the tabbrowsers a chance to clear their histories first
    var win = this._getTopWindow();
    if (win) {
      win.setTimeout(() => lazy.SessionSaver.run(), 0);
    } else if (lazy.RunState.isRunning) {
      lazy.SessionSaver.run();
    }

    this._clearRestoringWindows();
    this._saveableClosedWindowData = new WeakSet();
    this._lastClosedActions = [];
  },

  /**
   * On purge of domain data
   * @param {string} aDomain
   *        The domain we want to purge data for
   */
  onPurgeDomainData: function ssi_onPurgeDomainData(aDomain) {
    // does a session history entry contain a url for the given domain?
    function containsDomain(aEntry) {
      let host;
      try {
        host = Services.io.newURI(aEntry.url).host;
      } catch (e) {
        // The given URL probably doesn't have a host.
      }
      if (host && Services.eTLD.hasRootDomain(host, aDomain)) {
        return true;
      }
      return aEntry.children && aEntry.children.some(containsDomain, this);
    }
    // remove all closed tabs containing a reference to the given domain
    for (let ix in this._windows) {
      let closedTabs = this._windows[ix]._closedTabs;
      for (let i = closedTabs.length - 1; i >= 0; i--) {
        if (closedTabs[i].state.entries.some(containsDomain, this)) {
          closedTabs.splice(i, 1);
          this._closedObjectsChanged = true;
        }
      }
    }
    // remove all open & closed tabs containing a reference to the given
    // domain in closed windows
    for (let ix = this._closedWindows.length - 1; ix >= 0; ix--) {
      let closedTabs = this._closedWindows[ix]._closedTabs;
      let openTabs = this._closedWindows[ix].tabs;
      let openTabCount = openTabs.length;
      for (let i = closedTabs.length - 1; i >= 0; i--) {
        if (closedTabs[i].state.entries.some(containsDomain, this)) {
          closedTabs.splice(i, 1);
        }
      }
      for (let j = openTabs.length - 1; j >= 0; j--) {
        if (openTabs[j].entries.some(containsDomain, this)) {
          openTabs.splice(j, 1);
          if (this._closedWindows[ix].selected > j) {
            this._closedWindows[ix].selected--;
          }
        }
      }
      if (!openTabs.length) {
        this._closedWindows.splice(ix, 1);
      } else if (openTabs.length != openTabCount) {
        // Adjust the window's title if we removed an open tab
        let selectedTab = openTabs[this._closedWindows[ix].selected - 1];
        // some duplication from restoreHistory - make sure we get the correct title
        let activeIndex = (selectedTab.index || selectedTab.entries.length) - 1;
        if (activeIndex >= selectedTab.entries.length) {
          activeIndex = selectedTab.entries.length - 1;
        }
        this._closedWindows[ix].title = selectedTab.entries[activeIndex].title;
      }
    }

    if (lazy.RunState.isRunning) {
      lazy.SessionSaver.run();
    }

    this._clearRestoringWindows();
  },

  /**
   * On preference change
   * @param aData
   *        String preference changed
   */
  onPrefChange: function ssi_onPrefChange(aData) {
    switch (aData) {
      // if the user decreases the max number of closed tabs they want
      // preserved update our internal states to match that max
      case "sessionstore.max_tabs_undo":
        this._max_tabs_undo = this._prefBranch.getIntPref(
          "sessionstore.max_tabs_undo"
        );
        for (let ix in this._windows) {
          if (this._windows[ix]._closedTabs.length > this._max_tabs_undo) {
            this._windows[ix]._closedTabs.splice(
              this._max_tabs_undo,
              this._windows[ix]._closedTabs.length
            );
            this._closedObjectsChanged = true;
          }
        }
        break;
      case "sessionstore.max_windows_undo":
        this._max_windows_undo = this._prefBranch.getIntPref(
          "sessionstore.max_windows_undo"
        );
        this._capClosedWindows();
        break;
      case "privacy.resistFingerprinting":
        gResistFingerprintingEnabled = Services.prefs.getBoolPref(
          "privacy.resistFingerprinting"
        );
        break;
      case "sessionstore.restore_on_demand":
        this._restore_on_demand = this._prefBranch.getBoolPref(
          "sessionstore.restore_on_demand"
        );
        break;
      case "sessionstore.closedTabsFromAllWindows":
        this._closedTabsFromAllWindowsEnabled = this._prefBranch.getBoolPref(
          "sessionstore.closedTabsFromAllWindows"
        );
        this._closedObjectsChanged = true;
        break;
      case "sessionstore.closedTabsFromClosedWindows":
        this._closedTabsFromClosedWindowsEnabled = this._prefBranch.getBoolPref(
          "sessionstore.closedTabsFromClosedWindows"
        );
        this._closedObjectsChanged = true;
        break;
    }
  },

  /**
   * save state when new tab is added
   * @param aWindow
   *        Window reference
   */
  onTabAdd: function ssi_onTabAdd(aWindow) {
    this.saveStateDelayed(aWindow);
  },

  /**
   * set up listeners for a new tab
   * @param aWindow
   *        Window reference
   * @param aTab
   *        Tab reference
   */
  onTabBrowserInserted: function ssi_onTabBrowserInserted(aWindow, aTab) {
    let browser = aTab.linkedBrowser;
    browser.addEventListener("SwapDocShells", this);
    browser.addEventListener("oop-browser-crashed", this);
    browser.addEventListener("oop-browser-buildid-mismatch", this);

    if (browser.frameLoader) {
      this._lastKnownFrameLoader.set(browser.permanentKey, browser.frameLoader);
    }

    // Only restore if browser has been lazy.
    if (
      TAB_LAZY_STATES.has(aTab) &&
      !TAB_STATE_FOR_BROWSER.has(browser) &&
      lazy.TabStateCache.get(browser.permanentKey)
    ) {
      let tabState = lazy.TabState.clone(aTab, TAB_CUSTOM_VALUES.get(aTab));
      this.restoreTab(aTab, tabState);
    }

    // The browser has been inserted now, so lazy data is no longer relevant.
    TAB_LAZY_STATES.delete(aTab);
  },

  /**
   * remove listeners for a tab
   * @param aWindow
   *        Window reference
   * @param aTab
   *        Tab reference
   * @param aNoNotification
   *        bool Do not save state if we're updating an existing tab
   */
  onTabRemove: function ssi_onTabRemove(aWindow, aTab, aNoNotification) {
    this.cleanUpRemovedBrowser(aTab);

    if (!aNoNotification) {
      this.saveStateDelayed(aWindow);
    }
  },

  /**
   * When a tab closes, collect its properties
   * @param aWindow
   *        Window reference
   * @param aTab
   *        Tab reference
   */
  onTabClose: function ssi_onTabClose(aWindow, aTab) {
    // don't update our internal state if we don't have to
    if (this._max_tabs_undo == 0) {
      return;
    }

    // Get the latest data for this tab (generally, from the cache)
    let tabState = lazy.TabState.collect(aTab, TAB_CUSTOM_VALUES.get(aTab));

    // Store closed-tab data for undo.
    this.maybeSaveClosedTab(aWindow, aTab, tabState);
  },

  /**
   * Flush and copy tab state when moving a tab to a new window.
   * @param aFromBrowser
   *        Browser reference.
   * @param aToBrowser
   *        Browser reference.
   */
  onMoveToNewWindow(aFromBrowser, aToBrowser) {
    lazy.TabStateFlusher.flush(aFromBrowser).then(() => {
      let tabState = lazy.TabStateCache.get(aFromBrowser.permanentKey);
      lazy.TabStateCache.update(aToBrowser.permanentKey, tabState);
    });
  },

  /**
   * Save a closed tab if needed.
   * @param aWindow
   *        Window reference.
   * @param aTab
   *        Tab reference.
   * @param tabState
   *        Tab state.
   */
  maybeSaveClosedTab(aWindow, aTab, tabState) {
    // Don't save private tabs
    let isPrivateWindow = PrivateBrowsingUtils.isWindowPrivate(aWindow);
    if (!isPrivateWindow && tabState.isPrivate) {
      return;
    }
    if (aTab == aWindow.FirefoxViewHandler.tab) {
      return;
    }

    let permanentKey = aTab.linkedBrowser.permanentKey;

    let tabData = {
      permanentKey,
      state: tabState,
      title: aTab.label,
      image: aWindow.gBrowser.getIcon(aTab),
      pos: aTab._tPos,
      closedAt: Date.now(),
      closedInGroup: aTab._closedInGroup,
      sourceWindowId: aWindow.__SSi,
    };

    let winData = this._windows[aWindow.__SSi];
    let closedTabs = winData._closedTabs;

    // Determine whether the tab contains any information worth saving. Note
    // that there might be pending state changes queued in the child that
    // didn't reach the parent yet. If a tab is emptied before closing then we
    // might still remove it from the list of closed tabs later.
    if (this._shouldSaveTabState(tabState)) {
      // Save the tab state, for now. We might push a valid tab out
      // of the list but those cases should be extremely rare and
      // do probably never occur when using the browser normally.
      // (Tests or add-ons might do weird things though.)
      this.saveClosedTabData(winData, closedTabs, tabData);
    }

    // Remember the closed tab to properly handle any last updates included in
    // the final "update" message sent by the frame script's unload handler.
    this._closingTabMap.set(permanentKey, {
      winData,
      closedTabs,
      tabData,
    });
  },

  /**
   * Remove listeners which were added when browser was inserted and reset restoring state.
   * Also re-instate lazy data and basically revert tab to its lazy browser state.
   * @param aTab
   *        Tab reference
   */
  resetBrowserToLazyState(aTab) {
    const gBrowser = aTab.ownerGlobal.gBrowser;
    let browser = aTab.linkedBrowser;
    // Browser is already lazy so don't do anything.
    if (!browser.isConnected) {
      return;
    }

    this.cleanUpRemovedBrowser(aTab);

    aTab.setAttribute("pending", "true");

    this._lastKnownFrameLoader.delete(browser.permanentKey);
    this._crashedBrowsers.delete(browser.permanentKey);
    aTab.removeAttribute("crashed");
    gBrowser.tabContainer.updateTabIndicatorAttr(aTab);

    let { userTypedValue = null, userTypedClear = 0 } = browser;
    let hasStartedLoad = browser.didStartLoadSinceLastUserTyping();

    let cacheState = lazy.TabStateCache.get(browser.permanentKey);

    // Cache the browser userTypedValue either if there is no cache state
    // at all (e.g. if it was already discarded before we got to cache its state)
    // or it may have been created but not including a userTypedValue (e.g.
    // for a private tab we will cache `isPrivate: true` as soon as the tab
    // is opened).
    //
    // But only if:
    //
    // - if there is no cache state yet (which is unfortunately required
    //   for tabs discarded immediately after creation by extensions, see
    //   Bug 1422588).
    //
    // - or the user typed value was already being loaded (otherwise the lazy
    //   tab will not be restored with the expected url once activated again,
    //   see Bug 1724205).
    let shouldUpdateCacheState =
      userTypedValue &&
      (!cacheState || (hasStartedLoad && !cacheState.userTypedValue));

    if (shouldUpdateCacheState) {
      // Discard was likely called before state can be cached.  Update
      // the persistent tab state cache with browser information so a
      // restore will be successful.  This information is necessary for
      // restoreTabContent in ContentRestore.sys.mjs to work properly.
      lazy.TabStateCache.update(browser.permanentKey, {
        userTypedValue,
        userTypedClear: 1,
      });
    }

    TAB_LAZY_STATES.set(aTab, {
      url: browser.currentURI.spec,
      title: aTab.label,
      userTypedValue,
      userTypedClear,
    });
  },

  /**
   * Check if we are dealing with a crashed browser. If so, then the corresponding
   * crashed tab was revived by navigating to a different page. Remove the browser
   * from the list of crashed browsers to stop ignoring its messages.
   * @param aBrowser
   *        Browser reference
   */
  maybeExitCrashedState(aBrowser) {
    let uri = aBrowser.documentURI;
    if (uri?.spec?.startsWith("about:tabcrashed")) {
      this._crashedBrowsers.delete(aBrowser.permanentKey);
    }
  },

  /**
   * A debugging-only function to check if a browser is in _crashedBrowsers.
   * @param aBrowser
   *        Browser reference
   */
  isBrowserInCrashedSet(aBrowser) {
    if (gDebuggingEnabled) {
      return this._crashedBrowsers.has(aBrowser.permanentKey);
    }
    throw new Error(
      "SessionStore.isBrowserInCrashedSet() should only be called in debug mode!"
    );
  },

  /**
   * When a tab is removed or suspended, remove listeners and reset restoring state.
   * @param aBrowser
   *        Browser reference
   */
  cleanUpRemovedBrowser(aTab) {
    let browser = aTab.linkedBrowser;

    browser.removeEventListener("SwapDocShells", this);
    browser.removeEventListener("oop-browser-crashed", this);
    browser.removeEventListener("oop-browser-buildid-mismatch", this);

    // If this tab was in the middle of restoring or still needs to be restored,
    // we need to reset that state. If the tab was restoring, we will attempt to
    // restore the next tab.
    let previousState = TAB_STATE_FOR_BROWSER.get(browser);
    if (previousState) {
      this._resetTabRestoringState(aTab);
      if (previousState == TAB_STATE_RESTORING) {
        this.restoreNextTab();
      }
    }
  },

  /**
   * Insert a given |tabData| object into the list of |closedTabs|. We will
   * determine the right insertion point based on the .closedAt properties of
   * all tabs already in the list. The list will be truncated to contain a
   * maximum of |this._max_tabs_undo| entries.
   *
   * @param winData (object)
   *        The data of the window.
   * @param tabData (object)
   *        The tabData to be inserted.
   * @param closedTabs (array)
   *        The list of closed tabs for a window.
   */
  saveClosedTabData(winData, closedTabs, tabData, saveAction = true) {
    // Find the index of the first tab in the list
    // of closed tabs that was closed before our tab.
    let index = closedTabs.findIndex(tab => {
      return tab.closedAt < tabData.closedAt;
    });

    // If we found no tab closed before our
    // tab then just append it to the list.
    if (index == -1) {
      index = closedTabs.length;
    }

    // About to save the closed tab, add a unique ID.
    tabData.closedId = this._nextClosedId++;

    // Insert tabData at the right position.
    closedTabs.splice(index, 0, tabData);
    this._closedObjectsChanged = true;

    if (tabData.closedInGroup) {
      if (winData._lastClosedTabGroupCount < this._max_tabs_undo) {
        if (winData._lastClosedTabGroupCount < 0) {
          winData._lastClosedTabGroupCount = 1;
        } else {
          winData._lastClosedTabGroupCount++;
        }
      }
    } else {
      winData._lastClosedTabGroupCount = -1;
    }

    if (saveAction) {
      this._addClosedAction(this._LAST_ACTION_CLOSED_TAB, tabData.closedId);
    }

    // Truncate the list of closed tabs, if needed.
    if (closedTabs.length > this._max_tabs_undo) {
      closedTabs.splice(this._max_tabs_undo, closedTabs.length);
    }
  },

  /**
   * Remove the closed tab data at |index| from the list of |closedTabs|. If
   * the tab's final message is still pending we will simply discard it when
   * it arrives so that the tab doesn't reappear in the list.
   *
   * @param winData (object)
   *        The data of the window.
   * @param index (uint)
   *        The index of the tab to remove.
   * @param closedTabs (array)
   *        The list of closed tabs for a window.
   */
  removeClosedTabData(winData, closedTabs, index) {
    // Remove the given index from the list.
    let [closedTab] = closedTabs.splice(index, 1);
    this._closedObjectsChanged = true;

    // If the tab is part of the last closed group,
    // we need to deduct the tab from the count.
    if (index < winData._lastClosedTabGroupCount) {
      winData._lastClosedTabGroupCount--;
    }

    // If the closed tab's state still has a .permanentKey property then we
    // haven't seen its final update message yet. Remove it from the map of
    // closed tabs so that we will simply discard its last messages and will
    // not add it back to the list of closed tabs again.
    if (closedTab.permanentKey) {
      this._closingTabMap.delete(closedTab.permanentKey);
      this._tabClosingByWindowMap.delete(closedTab.permanentKey);
      delete closedTab.permanentKey;
    }

    this._removeClosedAction(this._LAST_ACTION_CLOSED_TAB, closedTab.closedId);

    return closedTab;
  },

  /**
   * When a tab is selected, save session data
   * @param aWindow
   *        Window reference
   */
  onTabSelect: function ssi_onTabSelect(aWindow) {
    if (lazy.RunState.isRunning) {
      this._windows[aWindow.__SSi].selected =
        aWindow.gBrowser.tabContainer.selectedIndex;

      let tab = aWindow.gBrowser.selectedTab;
      let browser = tab.linkedBrowser;

      if (TAB_STATE_FOR_BROWSER.get(browser) == TAB_STATE_NEEDS_RESTORE) {
        // If BROWSER_STATE is still available for the browser and it is
        // If __SS_restoreState is still on the browser and it is
        // TAB_STATE_NEEDS_RESTORE, then we haven't restored this tab yet.
        //
        // It's possible that this tab was recently revived, and that
        // we've deferred showing the tab crashed page for it (if the
        // tab crashed in the background). If so, we need to re-enter
        // the crashed state, since we'll be showing the tab crashed
        // page.
        if (lazy.TabCrashHandler.willShowCrashedTab(browser)) {
          this.enterCrashedState(browser);
        } else {
          this.restoreTabContent(tab);
        }
      }
    }
  },

  onTabShow: function ssi_onTabShow(aWindow, aTab) {
    // If the tab hasn't been restored yet, move it into the right bucket
    if (
      TAB_STATE_FOR_BROWSER.get(aTab.linkedBrowser) == TAB_STATE_NEEDS_RESTORE
    ) {
      TabRestoreQueue.hiddenToVisible(aTab);

      // let's kick off tab restoration again to ensure this tab gets restored
      // with "restore_hidden_tabs" == false (now that it has become visible)
      this.restoreNextTab();
    }

    // Default delay of 2 seconds gives enough time to catch multiple TabShow
    // events. This used to be due to changing groups in 'tab groups'. We
    // might be able to get rid of this now?
    this.saveStateDelayed(aWindow);
  },

  onTabHide: function ssi_onTabHide(aWindow, aTab) {
    // If the tab hasn't been restored yet, move it into the right bucket
    if (
      TAB_STATE_FOR_BROWSER.get(aTab.linkedBrowser) == TAB_STATE_NEEDS_RESTORE
    ) {
      TabRestoreQueue.visibleToHidden(aTab);
    }

    // Default delay of 2 seconds gives enough time to catch multiple TabHide
    // events. This used to be due to changing groups in 'tab groups'. We
    // might be able to get rid of this now?
    this.saveStateDelayed(aWindow);
  },

  /**
   * Handler for the event that is fired when a <xul:browser> crashes.
   *
   * @param aWindow
   *        The window that the crashed browser belongs to.
   * @param aBrowser
   *        The <xul:browser> that is now in the crashed state.
   */
  onBrowserCrashed(aBrowser) {
    this.enterCrashedState(aBrowser);
    // The browser crashed so we might never receive flush responses.
    // Resolve all pending flush requests for the crashed browser.
    lazy.TabStateFlusher.resolveAll(aBrowser);
  },

  /**
   * Called when a browser is showing or is about to show the tab
   * crashed page. This method causes SessionStore to ignore the
   * tab until it's restored.
   *
   * @param browser
   *        The <xul:browser> that is about to show the crashed page.
   */
  enterCrashedState(browser) {
    this._crashedBrowsers.add(browser.permanentKey);

    let win = browser.ownerGlobal;

    // If we hadn't yet restored, or were still in the midst of
    // restoring this browser at the time of the crash, we need
    // to reset its state so that we can try to restore it again
    // when the user revives the tab from the crash.
    if (TAB_STATE_FOR_BROWSER.has(browser)) {
      let tab = win.gBrowser.getTabForBrowser(browser);
      if (tab) {
        this._resetLocalTabRestoringState(tab);
      }
    }
  },

  // Clean up data that has been closed a long time ago.
  // Do not reschedule a save. This will wait for the next regular
  // save.
  onIdleDaily() {
    // Remove old closed windows
    this._cleanupOldData([this._closedWindows]);

    // Remove closed tabs of closed windows
    this._cleanupOldData(
      this._closedWindows.map(winData => winData._closedTabs)
    );

    // Remove closed tabs of open windows
    this._cleanupOldData(
      Object.keys(this._windows).map(key => this._windows[key]._closedTabs)
    );

    this._notifyOfClosedObjectsChange();
  },

  // Remove "old" data from an array
  _cleanupOldData(targets) {
    const TIME_TO_LIVE = this._prefBranch.getIntPref(
      "sessionstore.cleanup.forget_closed_after"
    );
    const now = Date.now();

    for (let array of targets) {
      for (let i = array.length - 1; i >= 0; --i) {
        let data = array[i];
        // Make sure that we have a timestamp to tell us when the target
        // has been closed. If we don't have a timestamp, default to a
        // safe timestamp: just now.
        data.closedAt = data.closedAt || now;
        if (now - data.closedAt > TIME_TO_LIVE) {
          array.splice(i, 1);
          this._closedObjectsChanged = true;
        }
      }
    }
  },

  /* ........ nsISessionStore API .............. */

  getBrowserState: function ssi_getBrowserState() {
    let state = this.getCurrentState();

    // Don't include the last session state in getBrowserState().
    delete state.lastSessionState;

    // Don't include any deferred initial state.
    delete state.deferredInitialState;

    return JSON.stringify(state);
  },

  setBrowserState: function ssi_setBrowserState(aState) {
    this._handleClosedWindows();

    try {
      var state = JSON.parse(aState);
    } catch (ex) {
      /* invalid state object - don't restore anything */
    }
    if (!state) {
      throw Components.Exception(
        "Invalid state string: not JSON",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    if (!state.windows) {
      throw Components.Exception("No windows", Cr.NS_ERROR_INVALID_ARG);
    }

    this._browserSetState = true;

    // Make sure the priority queue is emptied out
    this._resetRestoringState();

    var window = this._getTopWindow();
    if (!window) {
      this._restoreCount = 1;
      this._openWindowWithState(state);
      return;
    }

    // close all other browser windows
    for (let otherWin of this._browserWindows) {
      if (otherWin != window) {
        otherWin.close();
        this.onClose(otherWin);
      }
    }

    // make sure closed window data isn't kept
    if (this._closedWindows.length) {
      this._closedWindows = [];
      this._closedObjectsChanged = true;
    }

    // determine how many windows are meant to be restored
    this._restoreCount = state.windows ? state.windows.length : 0;

    // global data must be restored before restoreWindow is called so that
    // it happens before observers are notified
    this._globalState.setFromState(state);

    // Restore session cookies.
    lazy.SessionCookies.restore(state.cookies || []);

    // restore to the given state
    this.restoreWindows(window, state, { overwriteTabs: true });

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  getWindowState: function ssi_getWindowState(aWindow) {
    if ("__SSi" in aWindow) {
      return Cu.cloneInto(this._getWindowState(aWindow), {});
    }

    if (DyingWindowCache.has(aWindow)) {
      let data = DyingWindowCache.get(aWindow);
      return Cu.cloneInto({ windows: [data] }, {});
    }

    throw Components.Exception(
      "Window is not tracked",
      Cr.NS_ERROR_INVALID_ARG
    );
  },

  setWindowState: function ssi_setWindowState(aWindow, aState, aOverwrite) {
    if (!aWindow.__SSi) {
      throw Components.Exception(
        "Window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    this.restoreWindows(aWindow, aState, { overwriteTabs: aOverwrite });

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  getTabState: function ssi_getTabState(aTab) {
    if (!aTab || !aTab.ownerGlobal) {
      throw Components.Exception("Need a valid tab", Cr.NS_ERROR_INVALID_ARG);
    }
    if (!aTab.ownerGlobal.__SSi) {
      throw Components.Exception(
        "Default view is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    let tabState = lazy.TabState.collect(aTab, TAB_CUSTOM_VALUES.get(aTab));

    return JSON.stringify(tabState);
  },

  setTabState(aTab, aState) {
    // Remove the tab state from the cache.
    // Note that we cannot simply replace the contents of the cache
    // as |aState| can be an incomplete state that will be completed
    // by |restoreTabs|.
    let tabState = aState;
    if (typeof tabState == "string") {
      tabState = JSON.parse(aState);
    }
    if (!tabState) {
      throw Components.Exception(
        "Invalid state string: not JSON",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    if (typeof tabState != "object") {
      throw Components.Exception("Not an object", Cr.NS_ERROR_INVALID_ARG);
    }
    if (!("entries" in tabState)) {
      throw Components.Exception(
        "Invalid state object: no entries",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    let window = aTab.ownerGlobal;
    if (!window || !("__SSi" in window)) {
      throw Components.Exception(
        "Window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    if (TAB_STATE_FOR_BROWSER.has(aTab.linkedBrowser)) {
      this._resetTabRestoringState(aTab);
    }

    this._ensureNoNullsInTabDataList(
      window.gBrowser.tabs,
      this._windows[window.__SSi].tabs,
      aTab._tPos
    );
    this.restoreTab(aTab, tabState);

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  getInternalObjectState(obj) {
    if (obj.__SSi) {
      return this._windows[obj.__SSi];
    }
    return obj.loadURI
      ? TAB_STATE_FOR_BROWSER.get(obj)
      : TAB_CUSTOM_VALUES.get(obj);
  },

  getObjectTypeForClosedId(aClosedId) {
    // check if matches a window first
    if (this.getClosedWindowDataByClosedId(aClosedId)) {
      return this._LAST_ACTION_CLOSED_WINDOW;
    }
    return this._LAST_ACTION_CLOSED_TAB;
  },

  getClosedWindowDataByClosedId: function ssi_getClosedWindowDataByClosedId(
    aClosedId
  ) {
    return this._closedWindows.find(
      closedData => closedData.closedId == aClosedId
    );
  },

  getWindowById: function ssi_getWindowById(aSessionStoreId) {
    let resultWindow;
    for (let window of this._browserWindows) {
      if (window.__SSi === aSessionStoreId) {
        resultWindow = window;
        break;
      }
    }
    return resultWindow;
  },

  duplicateTab: function ssi_duplicateTab(
    aWindow,
    aTab,
    aDelta = 0,
    aRestoreImmediately = true,
    { inBackground, index } = {}
  ) {
    if (!aTab || !aTab.ownerGlobal) {
      throw Components.Exception("Need a valid tab", Cr.NS_ERROR_INVALID_ARG);
    }
    if (!aTab.ownerGlobal.__SSi) {
      throw Components.Exception(
        "Default view is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    if (!aWindow.gBrowser) {
      throw Components.Exception(
        "Invalid window object: no gBrowser",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    // Create a new tab.
    let userContextId = aTab.getAttribute("usercontextid");

    let tabOptions = {
      userContextId,
      index,
      ...(aTab == aWindow.gBrowser.selectedTab
        ? { relatedToCurrent: true, ownerTab: aTab }
        : {}),
      skipLoad: true,
      preferredRemoteType: aTab.linkedBrowser.remoteType,
    };
    let newTab = aWindow.gBrowser.addTrustedTab(null, tabOptions);

    // Start the throbber to pretend we're doing something while actually
    // waiting for data from the frame script. This throbber is disabled
    // if the URI is a local about: URI.
    let uriObj = aTab.linkedBrowser.currentURI;
    if (!uriObj || (uriObj && !uriObj.schemeIs("about"))) {
      newTab.setAttribute("busy", "true");
    }

    // Hack to ensure that the about:home, about:newtab, and about:welcome
    // favicon is loaded instantaneously, to avoid flickering and improve
    // perceived performance.
    aWindow.gBrowser.setDefaultIcon(newTab, uriObj);

    // Collect state before flushing.
    let tabState = lazy.TabState.collect(aTab, TAB_CUSTOM_VALUES.get(aTab));

    // Flush to get the latest tab state to duplicate.
    let browser = aTab.linkedBrowser;
    lazy.TabStateFlusher.flush(browser).then(() => {
      // The new tab might have been closed in the meantime.
      if (newTab.closing || !newTab.linkedBrowser) {
        return;
      }

      let window = newTab.ownerGlobal;

      // The tab or its window might be gone.
      if (!window || !window.__SSi) {
        return;
      }

      // Update state with flushed data. We can't use TabState.clone() here as
      // the tab to duplicate may have already been closed. In that case we
      // only have access to the <xul:browser>.
      let options = { includePrivateData: true };
      lazy.TabState.copyFromCache(browser.permanentKey, tabState, options);

      tabState.index += aDelta;
      tabState.index = Math.max(
        1,
        Math.min(tabState.index, tabState.entries.length)
      );
      tabState.pinned = false;

      if (inBackground === false) {
        aWindow.gBrowser.selectedTab = newTab;
      }

      // Restore the state into the new tab.
      this.restoreTab(newTab, tabState, {
        restoreImmediately: aRestoreImmediately,
      });
    });

    return newTab;
  },

  getWindows(aWindowOrOptions) {
    let isPrivate;
    if (!aWindowOrOptions) {
      aWindowOrOptions = this._getTopWindow();
    }
    if (aWindowOrOptions instanceof Ci.nsIDOMWindow) {
      isPrivate = PrivateBrowsingUtils.isBrowserPrivate(aWindowOrOptions);
    } else {
      isPrivate = Boolean(aWindowOrOptions.private);
    }

    const browserWindows = Array.from(this._browserWindows).filter(win => {
      return PrivateBrowsingUtils.isBrowserPrivate(win) === isPrivate;
    });
    return browserWindows;
  },

  getWindowForTabClosedId(aClosedId, aIncludePrivate) {
    // check non-private windows first, and then only check private windows if
    // aIncludePrivate was true
    const privateValues = aIncludePrivate ? [false, true] : [false];
    for (let privateness of privateValues) {
      for (let window of this.getWindows({ private: privateness })) {
        const windowState = this._windows[window.__SSi];
        if (!windowState._closedTabs?.length) {
          continue;
        }
        if (windowState._closedTabs.find(tab => tab.closedId === aClosedId)) {
          return window;
        }
      }
    }
    return undefined;
  },

  getLastClosedTabCount(aWindow) {
    if ("__SSi" in aWindow) {
      return Math.min(
        Math.max(this._windows[aWindow.__SSi]._lastClosedTabGroupCount, 1),
        this.getClosedTabCountForWindow(aWindow)
      );
    }

    throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
  },

  resetLastClosedTabCount(aWindow) {
    if ("__SSi" in aWindow) {
      this._windows[aWindow.__SSi]._lastClosedTabGroupCount = -1;
    } else {
      throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
    }
  },

  getClosedTabCountForWindow: function ssi_getClosedTabCountForWindow(aWindow) {
    if ("__SSi" in aWindow) {
      return this._windows[aWindow.__SSi]._closedTabs.length;
    }

    if (!DyingWindowCache.has(aWindow)) {
      throw Components.Exception(
        "Window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    return DyingWindowCache.get(aWindow)._closedTabs.length;
  },

  _prepareClosedTabOptions(aOptions = {}) {
    const sourceOptions = Object.assign(
      {
        closedTabsFromAllWindows: this._closedTabsFromAllWindowsEnabled,
        closedTabsFromClosedWindows: this._closedTabsFromClosedWindowsEnabled,
        sourceWindow: null,
      },
      aOptions instanceof Ci.nsIDOMWindow
        ? { sourceWindow: aOptions }
        : aOptions
    );
    if (!sourceOptions.sourceWindow) {
      sourceOptions.sourceWindow = this._getTopWindow(sourceOptions.private);
    }
    if (!sourceOptions.hasOwnProperty("private")) {
      sourceOptions.private = PrivateBrowsingUtils.isWindowPrivate(
        sourceOptions.sourceWindow
      );
    }
    return sourceOptions;
  },

  getClosedTabCount(aOptions) {
    const sourceOptions = this._prepareClosedTabOptions(aOptions);
    let tabCount = 0;

    if (sourceOptions.closedTabsFromAllWindows) {
      tabCount += this.getWindows({ private: sourceOptions.private })
        .map(win => this.getClosedTabCountForWindow(win))
        .reduce((total, count) => total + count, 0);
    } else {
      tabCount += this.getClosedTabCountForWindow(sourceOptions.sourceWindow);
    }

    if (!sourceOptions.private && sourceOptions.closedTabsFromClosedWindows) {
      tabCount += this.getClosedTabCountFromClosedWindows();
    }
    return tabCount;
  },

  getClosedTabCountFromClosedWindows:
    function ssi_getClosedTabCountFromClosedWindows() {
      const tabCount = this._closedWindows
        .map(winData => winData._closedTabs.length)
        .reduce((total, count) => total + count, 0);
      return tabCount;
    },

  getClosedTabDataForWindow: function ssi_getClosedTabDataForWindow(aWindow) {
    // We need to enable wrapping reflectors in order to allow the cloning of
    // objects containing FormDatas, which could be stored by
    // form-associated custom elements.
    let options = { wrapReflectors: true };
    if ("__SSi" in aWindow) {
      return Cu.cloneInto(
        this._windows[aWindow.__SSi]._closedTabs,
        {},
        options
      );
    }

    if (!DyingWindowCache.has(aWindow)) {
      throw Components.Exception(
        "Window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    let data = DyingWindowCache.get(aWindow);
    return Cu.cloneInto(data._closedTabs, {}, options);
  },

  getClosedTabData: function ssi_getClosedTabData(aOptions) {
    const sourceOptions = this._prepareClosedTabOptions(aOptions);
    const closedTabData = [];
    if (sourceOptions.closedTabsFromAllWindows) {
      for (let win of this.getWindows({ private: sourceOptions.private })) {
        closedTabData.push(...this.getClosedTabDataForWindow(win));
      }
    } else {
      closedTabData.push(
        ...this.getClosedTabDataForWindow(sourceOptions.sourceWindow)
      );
    }
    return closedTabData;
  },

  getClosedTabDataFromClosedWindows:
    function ssi_getClosedTabDataFromClosedWindows() {
      const closedTabData = [];
      for (let winData of this._closedWindows) {
        const sourceClosedId = winData.closedId;
        const closedTabs = Cu.cloneInto(winData._closedTabs, {});
        // Add a property pointing back to the closed window source
        for (let tabData of closedTabs) {
          tabData.sourceClosedId = sourceClosedId;
        }
        closedTabData.push(...closedTabs);
      }
      // sorting is left to the caller
      return closedTabData;
    },

  undoCloseTab: function ssi_undoCloseTab(aSource, aIndex, aTargetWindow) {
    const sourceWinData = this._resolveClosedDataSource(aSource);
    const isPrivateSource = Boolean(sourceWinData.isPrivate);
    if (aTargetWindow && !aTargetWindow.__SSi) {
      throw Components.Exception(
        "Target window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    } else if (!aTargetWindow) {
      aTargetWindow = this._getTopWindow(isPrivateSource);
    }
    if (
      isPrivateSource !== PrivateBrowsingUtils.isWindowPrivate(aTargetWindow)
    ) {
      throw Components.Exception(
        "Target window doesn't have the same privateness as the source window",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    // default to the most-recently closed tab
    aIndex = aIndex || 0;
    if (!(aIndex in sourceWinData._closedTabs)) {
      throw Components.Exception(
        "Invalid index: not in the closed tabs",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    // fetch the data of closed tab, while removing it from the array
    let { state, pos } = this.removeClosedTabData(
      sourceWinData,
      sourceWinData._closedTabs,
      aIndex
    );

    // Predict the remote type to use for the load to avoid unnecessary process
    // switches.
    let preferredRemoteType = lazy.E10SUtils.DEFAULT_REMOTE_TYPE;
    let url;
    if (state.entries?.length) {
      let activeIndex = (state.index || state.entries.length) - 1;
      activeIndex = Math.min(activeIndex, state.entries.length - 1);
      activeIndex = Math.max(activeIndex, 0);
      url = state.entries[activeIndex].url;
    }
    if (url) {
      preferredRemoteType = this.getPreferredRemoteType(
        url,
        aTargetWindow,
        state.userContextId
      );
    }

    // create a new tab
    let tabbrowser = aTargetWindow.gBrowser;
    let tab = (tabbrowser.selectedTab = tabbrowser.addTrustedTab(null, {
      // Append the tab if we're opening into a different window,
      index: aSource == aTargetWindow ? pos : Infinity,
      pinned: state.pinned,
      userContextId: state.userContextId,
      skipLoad: true,
      preferredRemoteType,
    }));

    // restore tab content
    this.restoreTab(tab, state);

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();

    return tab;
  },

  undoClosedTabFromClosedWindow: function ssi_undoClosedTabFromClosedWindow(
    aSource,
    aClosedId,
    aTargetWindow
  ) {
    const sourceWinData = this._resolveClosedDataSource(aSource);
    const closedIndex = sourceWinData._closedTabs.findIndex(
      tabData => tabData.closedId == aClosedId
    );
    if (closedIndex >= 0) {
      return this.undoCloseTab(aSource, closedIndex, aTargetWindow);
    }
    throw Components.Exception(
      "Invalid closedId: not in the closed tabs",
      Cr.NS_ERROR_INVALID_ARG
    );
  },

  getPreferredRemoteType(url, aWindow, userContextId) {
    return lazy.E10SUtils.getRemoteTypeForURI(
      url,
      aWindow.gMultiProcessBrowser,
      aWindow.gFissionBrowser,
      lazy.E10SUtils.DEFAULT_REMOTE_TYPE,
      null,
      lazy.E10SUtils.predictOriginAttributes({
        window: aWindow,
        userContextId,
      })
    );
  },

  _resolveClosedDataSource(aSource) {
    let winData;
    if (aSource instanceof Ci.nsIDOMWindow) {
      if (!aSource.__SSi) {
        throw Components.Exception(
          "Window is not tracked",
          Cr.NS_ERROR_INVALID_ARG
        );
      }
      winData = this._windows[aSource.__SSi];
    } else if (typeof aSource.sourceClosedId == "number") {
      /* eslint-disable-next-line no-shadow */
      winData = this._closedWindows.find(
        closedData => closedData.closedId == aSource.sourceClosedId
      );
      if (!winData) {
        throw Components.Exception(
          "No such closed window",
          Cr.NS_ERROR_INVALID_ARG
        );
      }
    } else if (typeof aSource.sourceWindowId == "string") {
      winData = this._windows[aSource.sourceWindowId];
      if (!winData) {
        throw Components.Exception(
          "No such source window",
          Cr.NS_ERROR_INVALID_ARG
        );
      }
    } else {
      throw Components.Exception(
        "Invalid source object",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    return winData;
  },

  forgetClosedTab: function ssi_forgetClosedTab(aSource, aIndex) {
    const winData = this._resolveClosedDataSource(aSource);
    // default to the most-recently closed tab
    aIndex = aIndex || 0;
    if (!(aIndex in winData._closedTabs)) {
      throw Components.Exception(
        "Invalid index: not in the closed tabs",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    // remove closed tab from the array
    this.removeClosedTabData(winData, winData._closedTabs, aIndex);

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  forgetClosedWindowById(aClosedId) {
    // We don't keep any record for closed private windows so privateness is not relevant here
    let closedIndex = this._closedWindows.findIndex(
      windowState => windowState.closedId == aClosedId
    );
    if (closedIndex < 0) {
      throw Components.Exception(
        "Invalid closedId: not in the closed windows",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    this.forgetClosedWindow(closedIndex);
  },

  forgetClosedTabById(aClosedId, aSourceOptions = {}) {
    let sourceWindowsData;
    let searchPrivateWindows = aSourceOptions.includePrivate ?? true;
    if (
      aSourceOptions instanceof Ci.nsIDOMWindow ||
      "sourceWindowId" in aSourceOptions ||
      "sourceClosedId" in aSourceOptions
    ) {
      sourceWindowsData = [this._resolveClosedDataSource(aSourceOptions)];
    } else {
      // Get the windows we'll look for the closed tab in, filtering out private
      // windows if necessary
      let browserWindows = Array.from(this._browserWindows);
      sourceWindowsData = [];
      for (let win of browserWindows) {
        if (
          !searchPrivateWindows &&
          PrivateBrowsingUtils.isBrowserPrivate(win)
        ) {
          continue;
        }
        sourceWindowsData.push(this._windows[win.__SSi]);
      }
    }

    // See if the aCloseId matches a closed tab in any window data
    for (let winData of sourceWindowsData) {
      let closedIndex = winData._closedTabs.findIndex(
        tabData => tabData.closedId == aClosedId
      );
      if (closedIndex >= 0) {
        // remove closed tab from the array
        this.removeClosedTabData(winData, winData._closedTabs, closedIndex);
        // Notify of changes to closed objects.
        this._notifyOfClosedObjectsChange();
        return;
      }
    }
    throw Components.Exception(
      "Invalid closedId: not found in the closed tabs of any window",
      Cr.NS_ERROR_INVALID_ARG
    );
  },

  getClosedWindowCount: function ssi_getClosedWindowCount() {
    return this._closedWindows.length;
  },

  getClosedWindowData: function ssi_getClosedWindowData() {
    return Cu.cloneInto(this._closedWindows, {});
  },

  maybeDontRestoreTabs(aWindow) {
    // Don't restore the tabs if we restore the session at startup
    this._windows[aWindow.__SSi]._maybeDontRestoreTabs = true;
  },

  isLastRestorableWindow() {
    return (
      Object.values(this._windows).filter(winData => !winData.isPrivate)
        .length == 1 &&
      !this._closedWindows.some(win => win._shouldRestore || false)
    );
  },

  undoCloseWindow: function ssi_undoCloseWindow(aIndex) {
    if (!(aIndex in this._closedWindows)) {
      throw Components.Exception(
        "Invalid index: not in the closed windows",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    // reopen the window
    let state = { windows: this._removeClosedWindow(aIndex) };
    delete state.windows[0].closedAt; // Window is now open.

    let window = this._openWindowWithState(state);
    this.windowToFocus = window;
    WINDOW_SHOWING_PROMISES.get(window).promise.then(win =>
      this.restoreWindows(win, state, { overwriteTabs: true })
    );

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();

    return window;
  },

  forgetClosedWindow: function ssi_forgetClosedWindow(aIndex) {
    // default to the most-recently closed window
    aIndex = aIndex || 0;
    if (!(aIndex in this._closedWindows)) {
      throw Components.Exception(
        "Invalid index: not in the closed windows",
        Cr.NS_ERROR_INVALID_ARG
      );
    }

    // remove closed window from the array
    let winData = this._closedWindows[aIndex];
    this._removeClosedWindow(aIndex);
    this._saveableClosedWindowData.delete(winData);

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  getCustomWindowValue(aWindow, aKey) {
    if ("__SSi" in aWindow) {
      let data = this._windows[aWindow.__SSi].extData || {};
      return data[aKey] || "";
    }

    if (DyingWindowCache.has(aWindow)) {
      let data = DyingWindowCache.get(aWindow).extData || {};
      return data[aKey] || "";
    }

    throw Components.Exception(
      "Window is not tracked",
      Cr.NS_ERROR_INVALID_ARG
    );
  },

  setCustomWindowValue(aWindow, aKey, aStringValue) {
    if (typeof aStringValue != "string") {
      throw new TypeError("setCustomWindowValue only accepts string values");
    }

    if (!("__SSi" in aWindow)) {
      throw Components.Exception(
        "Window is not tracked",
        Cr.NS_ERROR_INVALID_ARG
      );
    }
    if (!this._windows[aWindow.__SSi].extData) {
      this._windows[aWindow.__SSi].extData = {};
    }
    this._windows[aWindow.__SSi].extData[aKey] = aStringValue;
    this.saveStateDelayed(aWindow);
  },

  deleteCustomWindowValue(aWindow, aKey) {
    if (
      aWindow.__SSi &&
      this._windows[aWindow.__SSi].extData &&
      this._windows[aWindow.__SSi].extData[aKey]
    ) {
      delete this._windows[aWindow.__SSi].extData[aKey];
    }
    this.saveStateDelayed(aWindow);
  },

  getCustomTabValue(aTab, aKey) {
    return (TAB_CUSTOM_VALUES.get(aTab) || {})[aKey] || "";
  },

  setCustomTabValue(aTab, aKey, aStringValue) {
    if (typeof aStringValue != "string") {
      throw new TypeError("setCustomTabValue only accepts string values");
    }

    // If the tab hasn't been restored, then set the data there, otherwise we
    // could lose newly added data.
    if (!TAB_CUSTOM_VALUES.has(aTab)) {
      TAB_CUSTOM_VALUES.set(aTab, {});
    }

    TAB_CUSTOM_VALUES.get(aTab)[aKey] = aStringValue;
    this.saveStateDelayed(aTab.ownerGlobal);
  },

  deleteCustomTabValue(aTab, aKey) {
    let state = TAB_CUSTOM_VALUES.get(aTab);
    if (state && aKey in state) {
      delete state[aKey];
      this.saveStateDelayed(aTab.ownerGlobal);
    }
  },

  /**
   * Retrieves data specific to lazy-browser tabs.  If tab is not lazy,
   * will return undefined.
   *
   * @param aTab (xul:tab)
   *        The tabbrowser-tab the data is for.
   * @param aKey (string)
   *        The key which maps to the desired data.
   */
  getLazyTabValue(aTab, aKey) {
    return (TAB_LAZY_STATES.get(aTab) || {})[aKey];
  },

  getCustomGlobalValue(aKey) {
    return this._globalState.get(aKey);
  },

  setCustomGlobalValue(aKey, aStringValue) {
    if (typeof aStringValue != "string") {
      throw new TypeError("setCustomGlobalValue only accepts string values");
    }

    this._globalState.set(aKey, aStringValue);
    this.saveStateDelayed();
  },

  deleteCustomGlobalValue(aKey) {
    this._globalState.delete(aKey);
    this.saveStateDelayed();
  },

  persistTabAttribute: function ssi_persistTabAttribute(aName) {
    if (lazy.TabAttributes.persist(aName)) {
      this.saveStateDelayed();
    }
  },

  /**
   * Undoes the closing of a tab or window which corresponds
   * to the closedId passed in.
   *
   * @param {integer} aClosedId
   *        The closedId of the tab or window
   * @param {boolean} [aIncludePrivate = true]
   *        Whether to restore private tabs or windows. Defaults to true
   * @param {Window} [aTargetWindow]
   *        When aClosedId is for a closed tab, which window to re-open the tab into.
   *        Defaults to current (topWindow).
   *
   * @returns a tab or window object
   */
  undoCloseById(aClosedId, aIncludePrivate = true, aTargetWindow) {
    // Check if we are re-opening a window first.
    for (let i = 0, l = this._closedWindows.length; i < l; i++) {
      if (this._closedWindows[i].closedId == aClosedId) {
        return this.undoCloseWindow(i);
      }
    }

    // See if the aCloseId matches a tab in an open window
    // Check for a tab.
    for (let sourceWindow of Services.wm.getEnumerator("navigator:browser")) {
      if (
        !aIncludePrivate &&
        PrivateBrowsingUtils.isWindowPrivate(sourceWindow)
      ) {
        continue;
      }
      let windowState = this._windows[sourceWindow.__SSi];
      if (windowState) {
        for (let j = 0, l = windowState._closedTabs.length; j < l; j++) {
          if (windowState._closedTabs[j].closedId == aClosedId) {
            return this.undoCloseTab(sourceWindow, j, aTargetWindow);
          }
        }
      }
    }

    // Neither a tab nor a window was found, return undefined and let the caller decide what to do about it.
    return undefined;
  },

  /**
   * Updates the label and icon for a <xul:tab> using the data from
   * tabData.
   *
   * @param tab
   *        The <xul:tab> to update.
   * @param tabData (optional)
   *        The tabData to use to update the tab. If the argument is
   *        not supplied, the data will be retrieved from the cache.
   */
  updateTabLabelAndIcon(tab, tabData = null) {
    if (tab.hasAttribute("customizemode")) {
      return;
    }

    let browser = tab.linkedBrowser;
    let win = browser.ownerGlobal;

    if (!tabData) {
      tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab));
      if (!tabData) {
        throw new Error("tabData not found for given tab");
      }
    }

    let activePageData = tabData.entries[tabData.index - 1] || null;

    // If the page has a title, set it.
    if (activePageData) {
      if (activePageData.title && activePageData.title != activePageData.url) {
        win.gBrowser.setInitialTabTitle(tab, activePageData.title, {
          isContentTitle: true,
        });
      } else {
        win.gBrowser.setInitialTabTitle(tab, activePageData.url);
      }
    }

    // Restore the tab icon.
    if ("image" in tabData) {
      // We know that about:blank is safe to load in any remote type. Since
      // SessionStore is triggered with about:blank, there must be a process
      // flip. We will ignore the first about:blank load to prevent resetting the
      // favicon that we have set earlier to avoid flickering and improve
      // perceived performance.
      if (
        !activePageData ||
        (activePageData && activePageData.url != "about:blank")
      ) {
        win.gBrowser.setIcon(
          tab,
          tabData.image,
          undefined,
          tabData.iconLoadingPrincipal
        );
      }
      lazy.TabStateCache.update(browser.permanentKey, {
        image: null,
        iconLoadingPrincipal: null,
      });
    }
  },

  // This method deletes all the closedTabs matching userContextId.
  _forgetTabsWithUserContextId(userContextId) {
    for (let window of Services.wm.getEnumerator("navigator:browser")) {
      let windowState = this._windows[window.__SSi];
      if (windowState) {
        // In order to remove the tabs in the correct order, we store the
        // indexes, into an array, then we revert the array and remove closed
        // data from the last one going backward.
        let indexes = [];
        windowState._closedTabs.forEach((closedTab, index) => {
          if (closedTab.state.userContextId == userContextId) {
            indexes.push(index);
          }
        });

        for (let index of indexes.reverse()) {
          this.removeClosedTabData(windowState, windowState._closedTabs, index);
        }
      }
    }

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  /**
   * Restores the session state stored in LastSession. This will attempt
   * to merge data into the current session. If a window was opened at startup
   * with pinned tab(s), then the remaining data from the previous session for
   * that window will be opened into that window. Otherwise new windows will
   * be opened.
   */
  restoreLastSession: function ssi_restoreLastSession() {
    // Use the public getter since it also checks PB mode
    if (!this.canRestoreLastSession) {
      throw Components.Exception("Last session can not be restored");
    }

    Services.obs.notifyObservers(null, NOTIFY_INITIATING_MANUAL_RESTORE);

    // First collect each window with its id...
    let windows = {};
    for (let window of this._browserWindows) {
      if (window.__SS_lastSessionWindowID) {
        windows[window.__SS_lastSessionWindowID] = window;
      }
    }

    let lastSessionState = LastSession.getState();

    // This shouldn't ever be the case...
    if (!lastSessionState.windows.length) {
      throw Components.Exception(
        "lastSessionState has no windows",
        Cr.NS_ERROR_UNEXPECTED
      );
    }

    // We're technically doing a restore, so set things up so we send the
    // notification when we're done. We want to send "sessionstore-browser-state-restored".
    this._restoreCount = lastSessionState.windows.length;
    this._browserSetState = true;

    // We want to re-use the last opened window instead of opening a new one in
    // the case where it's "empty" and not associated with a window in the session.
    // We will do more processing via _prepWindowToRestoreInto if we need to use
    // the lastWindow.
    let lastWindow = this._getTopWindow();
    let canUseLastWindow = lastWindow && !lastWindow.__SS_lastSessionWindowID;

    // global data must be restored before restoreWindow is called so that
    // it happens before observers are notified
    this._globalState.setFromState(lastSessionState);

    let openWindows = [];
    let windowsToOpen = [];

    // Restore session cookies.
    lazy.SessionCookies.restore(lastSessionState.cookies || []);

    // Restore into windows or open new ones as needed.
    for (let i = 0; i < lastSessionState.windows.length; i++) {
      let winState = lastSessionState.windows[i];
      let lastSessionWindowID = winState.__lastSessionWindowID;
      // delete lastSessionWindowID so we don't add that to the window again
      delete winState.__lastSessionWindowID;

      // See if we can use an open window. First try one that is associated with
      // the state we're trying to restore and then fallback to the last selected
      // window.
      let windowToUse = windows[lastSessionWindowID];
      if (!windowToUse && canUseLastWindow) {
        windowToUse = lastWindow;
        canUseLastWindow = false;
      }

      let [canUseWindow, canOverwriteTabs] =
        this._prepWindowToRestoreInto(windowToUse);

      // If there's a window already open that we can restore into, use that
      if (canUseWindow) {
        if (!PERSIST_SESSIONS) {
          // Since we're not overwriting existing tabs, we want to merge _closedTabs,
          // putting existing ones first. Then make sure we're respecting the max pref.
          if (winState._closedTabs && winState._closedTabs.length) {
            let curWinState = this._windows[windowToUse.__SSi];
            curWinState._closedTabs = curWinState._closedTabs.concat(
              winState._closedTabs
            );
            curWinState._closedTabs.splice(
              this._max_tabs_undo,
              curWinState._closedTabs.length
            );
          }
        }
        // We don't restore window right away, just store its data.
        // Later, these windows will be restored with newly opened windows.
        this._updateWindowRestoreState(windowToUse, {
          windows: [winState],
          options: { overwriteTabs: canOverwriteTabs },
        });
        openWindows.push(windowToUse);
      } else {
        windowsToOpen.push(winState);
      }
    }

    // Actually restore windows in reversed z-order.
    this._openWindows({ windows: windowsToOpen }).then(openedWindows =>
      this._restoreWindowsInReversedZOrder(openWindows.concat(openedWindows))
    );

    // Merge closed windows from this session with ones from last session
    if (lastSessionState._closedWindows) {
      // reset window closedIds and any references to them from closed tabs
      for (let closedWindow of lastSessionState._closedWindows) {
        closedWindow.closedId = this._nextClosedId++;
        if (closedWindow._closedTabs?.length) {
          this._resetClosedTabIds(
            closedWindow._closedTabs,
            closedWindow.closedId
          );
        }
      }
      this._closedWindows = this._closedWindows.concat(
        lastSessionState._closedWindows
      );
      this._capClosedWindows();
      this._closedObjectsChanged = true;
    }

    lazy.DevToolsShim.restoreDevToolsSession(lastSessionState);

    // Set data that persists between sessions
    this._recentCrashes =
      (lastSessionState.session && lastSessionState.session.recentCrashes) || 0;

    // Update the session start time using the restored session state.
    this._updateSessionStartTime(lastSessionState);

    LastSession.clear();

    // Notify of changes to closed objects.
    this._notifyOfClosedObjectsChange();
  },

  /**
   * Revive a crashed tab and restore its state from before it crashed.
   *
   * @param aTab
   *        A <xul:tab> linked to a crashed browser. This is a no-op if the
   *        browser hasn't actually crashed, or is not associated with a tab.
   *        This function will also throw if the browser happens to be remote.
   */
  reviveCrashedTab(aTab) {
    if (!aTab) {
      throw new Error(
        "SessionStore.reviveCrashedTab expected a tab, but got null."
      );
    }

    const gBrowser = aTab.ownerGlobal.gBrowser;
    let browser = aTab.linkedBrowser;
    if (!this._crashedBrowsers.has(browser.permanentKey)) {
      return;
    }

    // Sanity check - the browser to be revived should not be remote
    // at this point.
    if (browser.isRemoteBrowser) {
      throw new Error(
        "SessionStore.reviveCrashedTab: " +
          "Somehow a crashed browser is still remote."
      );
    }

    // We put the browser at about:blank in case the user is
    // restoring tabs on demand. This way, the user won't see
    // a flash of the about:tabcrashed page after selecting
    // the revived tab.
    aTab.removeAttribute("crashed");
    gBrowser.tabContainer.updateTabIndicatorAttr(aTab);

    browser.loadURI(lazy.blankURI, {
      triggeringPrincipal: Services.scriptSecurityManager.createNullPrincipal({
        userContextId: aTab.userContextId,
      }),
      remoteTypeOverride: lazy.E10SUtils.NOT_REMOTE,
    });

    let data = lazy.TabState.collect(aTab, TAB_CUSTOM_VALUES.get(aTab));
    this.restoreTab(aTab, data, {
      forceOnDemand: true,
    });
  },

  /**
   * Revive all crashed tabs and reset the crashed tabs count to 0.
   */
  reviveAllCrashedTabs() {
    for (let window of Services.wm.getEnumerator("navigator:browser")) {
      for (let tab of window.gBrowser.tabs) {
        this.reviveCrashedTab(tab);
      }
    }
  },

  /**
   * Retrieves the latest session history information for a tab. The cached data
   * is returned immediately, but a callback may be provided that supplies
   * up-to-date data when or if it is available. The callback is passed a single
   * argument with data in the same format as the return value.
   *
   * @param tab tab to retrieve the session history for
   * @param updatedCallback function to call with updated data as the single argument
   * @returns a object containing 'index' specifying the current index, and an
   * array 'entries' containing an object for each history item.
   */
  getSessionHistory(tab, updatedCallback) {
    if (updatedCallback) {
      lazy.TabStateFlusher.flush(tab.linkedBrowser).then(() => {
        let sessionHistory = this.getSessionHistory(tab);
        if (sessionHistory) {
          updatedCallback(sessionHistory);
        }
      });
    }

    // Don't continue if the tab was closed before TabStateFlusher.flush resolves.
    if (tab.linkedBrowser) {
      let tabState = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab));
      return { index: tabState.index - 1, entries: tabState.entries };
    }
    return null;
  },

  /**
   * See if aWindow is usable for use when restoring a previous session via
   * restoreLastSession. If usable, prepare it for use.
   *
   * @param aWindow
   *        the window to inspect & prepare
   * @returns [canUseWindow, canOverwriteTabs]
   *          canUseWindow: can the window be used to restore into
   *          canOverwriteTabs: all of the current tabs are home pages and we
   *                            can overwrite them
   */
  _prepWindowToRestoreInto: function ssi_prepWindowToRestoreInto(aWindow) {
    if (!aWindow) {
      return [false, false];
    }

    // We might be able to overwrite the existing tabs instead of just adding
    // the previous session's tabs to the end. This will be set if possible.
    let canOverwriteTabs = false;

    // Look at the open tabs in comparison to home pages. If all the tabs are
    // home pages then we'll end up overwriting all of them. Otherwise we'll
    // just close the tabs that match home pages. Tabs with the about:blank
    // URI will always be overwritten.
    let homePages = ["about:blank"];
    let removableTabs = [];
    let tabbrowser = aWindow.gBrowser;
    let startupPref = this._prefBranch.getIntPref("startup.page");
    if (startupPref == 1) {
      homePages = homePages.concat(lazy.HomePage.get(aWindow).split("|"));
    }

    for (let i = tabbrowser._numPinnedTabs; i < tabbrowser.tabs.length; i++) {
      let tab = tabbrowser.tabs[i];
      if (homePages.includes(tab.linkedBrowser.currentURI.spec)) {
        removableTabs.push(tab);
      }
    }

    if (
      tabbrowser.tabs.length > tabbrowser.visibleTabs.length &&
      tabbrowser.visibleTabs.length === removableTabs.length
    ) {
      // If all the visible tabs are also removable and the selected tab is hidden or removeable, we will later remove
      // all "removable" tabs causing the browser to automatically close because the only tab left is hidden.
      // To prevent the browser from automatically closing, we will leave one other visible tab open.
      removableTabs.shift();
    }

    if (tabbrowser.tabs.length == removableTabs.length) {
      canOverwriteTabs = true;
    } else {
      // If we're not overwriting all of the tabs, then close the home tabs.
      for (let i = removableTabs.length - 1; i >= 0; i--) {
        tabbrowser.removeTab(removableTabs.pop(), { animate: false });
      }
    }

    return [true, canOverwriteTabs];
  },

  /* ........ Saving Functionality .............. */

  /**
   * Store window dimensions, visibility, sidebar
   * @param aWindow
   *        Window reference
   */
  _updateWindowFeatures: function ssi_updateWindowFeatures(aWindow) {
    var winData = this._windows[aWindow.__SSi];

    WINDOW_ATTRIBUTES.forEach(function (aAttr) {
      winData[aAttr] = this._getWindowDimension(aWindow, aAttr);
    }, this);

    if (winData.sizemode != "minimized") {
      winData.sizemodeBeforeMinimized = winData.sizemode;
    }

    var hidden = WINDOW_HIDEABLE_FEATURES.filter(function (aItem) {
      return aWindow[aItem] && !aWindow[aItem].visible;
    });
    if (hidden.length) {
      winData.hidden = hidden.join(",");
    } else if (winData.hidden) {
      delete winData.hidden;
    }

    let sidebarBox = aWindow.document.getElementById("sidebar-box");
    let sidebar = sidebarBox.getAttribute("sidebarcommand");
    if (sidebar && sidebarBox.getAttribute("checked") == "true") {
      winData.sidebar = sidebar;
    } else if (winData.sidebar) {
      delete winData.sidebar;
    }
    let workspaceID = aWindow.getWorkspaceID();
    if (workspaceID) {
      winData.workspaceID = workspaceID;
    }
  },

  /**
   * gather session data as object
   * @param aUpdateAll
   *        Bool update all windows
   * @returns object
   */
  getCurrentState(aUpdateAll) {
    this._handleClosedWindows().then(() => {
      this._notifyOfClosedObjectsChange();
    });

    var activeWindow = this._getTopWindow();

    TelemetryStopwatch.start("FX_SESSION_RESTORE_COLLECT_ALL_WINDOWS_DATA_MS");
    if (lazy.RunState.isRunning) {
      // update the data for all windows with activities since the last save operation.
      let index = 0;
      for (let window of this._orderedBrowserWindows) {
        if (!this._isWindowLoaded(window)) {
          // window data is still in _statesToRestore
          continue;
        }
        if (aUpdateAll || DirtyWindows.has(window) || window == activeWindow) {
          this._collectWindowData(window);
        } else {
          // always update the window features (whose change alone never triggers a save operation)
          this._updateWindowFeatures(window);
        }
        this._windows[window.__SSi].zIndex = ++index;
      }
      DirtyWindows.clear();
    }
    TelemetryStopwatch.finish("FX_SESSION_RESTORE_COLLECT_ALL_WINDOWS_DATA_MS");

    // An array that at the end will hold all current window data.
    var total = [];
    // The ids of all windows contained in 'total' in the same order.
    var ids = [];
    // The number of window that are _not_ popups.
    var nonPopupCount = 0;
    var ix;

    // collect the data for all windows
    for (ix in this._windows) {
      if (this._windows[ix]._restoring) {
        // window data is still in _statesToRestore
        continue;
      }
      total.push(this._windows[ix]);
      ids.push(ix);
      if (!this._windows[ix].isPopup) {
        nonPopupCount++;
      }
    }

    // collect the data for all windows yet to be restored
    for (ix in this._statesToRestore) {
      for (let winData of this._statesToRestore[ix].windows) {
        total.push(winData);
        if (!winData.isPopup) {
          nonPopupCount++;
        }
      }
    }

    // shallow copy this._closedWindows to preserve current state
    let lastClosedWindowsCopy = this._closedWindows.slice();

    if (AppConstants.platform != "macosx") {
      // If no non-popup browser window remains open, return the state of the last
      // closed window(s). We only want to do this when we're actually "ending"
      // the session.
      // XXXzpao We should do this for _restoreLastWindow == true, but that has
      //        its own check for popups. c.f. bug 597619
      if (
        nonPopupCount == 0 &&
        !!lastClosedWindowsCopy.length &&
        lazy.RunState.isQuitting
      ) {
        // prepend the last non-popup browser window, so that if the user loads more tabs
        // at startup we don't accidentally add them to a popup window
        do {
          total.unshift(lastClosedWindowsCopy.shift());
        } while (total[0].isPopup && lastClosedWindowsCopy.length);
      }
    }

    if (activeWindow) {
      this.activeWindowSSiCache = activeWindow.__SSi || "";
    }
    ix = ids.indexOf(this.activeWindowSSiCache);
    // We don't want to restore focus to a minimized window or a window which had all its
    // tabs stripped out (doesn't exist).
    if (ix != -1 && total[ix] && total[ix].sizemode == "minimized") {
      ix = -1;
    }

    let session = {
      lastUpdate: Date.now(),
      startTime: this._sessionStartTime,
      recentCrashes: this._recentCrashes,
    };

    let state = {
      version: ["sessionrestore", FORMAT_VERSION],
      windows: total,
      selectedWindow: ix + 1,
      _closedWindows: lastClosedWindowsCopy,
      session,
      global: this._globalState.getState(),
    };

    // Collect and store session cookies.
    state.cookies = lazy.SessionCookies.collect();

    lazy.DevToolsShim.saveDevToolsSession(state);

    // Persist the last session if we deferred restoring it
    if (LastSession.canRestore) {
      state.lastSessionState = LastSession.getState();
    }

    // If we were called by the SessionSaver and started with only a private
    // window we want to pass the deferred initial state to not lose the
    // previous session.
    if (this._deferredInitialState) {
      state.deferredInitialState = this._deferredInitialState;
    }

    return state;
  },

  /**
   * serialize session data for a window
   * @param aWindow
   *        Window reference
   * @returns string
   */
  _getWindowState: function ssi_getWindowState(aWindow) {
    if (!this._isWindowLoaded(aWindow)) {
      return this._statesToRestore[WINDOW_RESTORE_IDS.get(aWindow)];
    }

    if (lazy.RunState.isRunning) {
      this._collectWindowData(aWindow);
    }

    return { windows: [this._windows[aWindow.__SSi]] };
  },

  /**
   * Gathers data about a window and its tabs, and updates its
   * entry in this._windows.
   *
   * @param aWindow
   *        Window references.
   * @returns a Map mapping the browser tabs from aWindow to the tab
   *          entry that was put into the window data in this._windows.
   */
  _collectWindowData: function ssi_collectWindowData(aWindow) {
    let tabMap = new Map();

    if (!this._isWindowLoaded(aWindow)) {
      return tabMap;
    }

    let tabbrowser = aWindow.gBrowser;
    let tabs = tabbrowser.tabs;
    let winData = this._windows[aWindow.__SSi];
    let tabsData = (winData.tabs = []);

    // update the internal state data for this window
    for (let tab of tabs) {
      if (tab == aWindow.FirefoxViewHandler.tab) {
        continue;
      }
      let tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab));
      tabMap.set(tab, tabData);
      tabsData.push(tabData);
    }

    let selectedIndex = tabbrowser.tabbox.selectedIndex + 1;
    // We don't store the Firefox View tab in Session Store, so if it was the last selected "tab" when
    // a window is closed, point to the first item in the tab strip instead (it will never be the Firefox View tab,
    // since it's only inserted into the tab strip after it's selected).
    if (aWindow.FirefoxViewHandler.tab?.selected) {
      selectedIndex = 1;
      winData.title = tabbrowser.tabs[0].label;
    }
    winData.selected = selectedIndex;

    this._updateWindowFeatures(aWindow);

    // Make sure we keep __SS_lastSessionWindowID around for cases like entering
    // or leaving PB mode.
    if (aWindow.__SS_lastSessionWindowID) {
      this._windows[aWindow.__SSi].__lastSessionWindowID =
        aWindow.__SS_lastSessionWindowID;
    }

    DirtyWindows.remove(aWindow);
    return tabMap;
  },

  /* ........ Restoring Functionality .............. */

  /**
   * Open windows with data
   *
   * @param root
   *        Windows data
   * @returns a promise resolved when all windows have been opened
   */
  _openWindows(root) {
    let windowsOpened = [];
    for (let winData of root.windows) {
      if (!winData || !winData.tabs || !winData.tabs[0]) {
        this._restoreCount--;
        continue;
      }
      windowsOpened.push(this._openWindowWithState({ windows: [winData] }));
    }
    let windowOpenedPromises = [];
    for (const openedWindow of windowsOpened) {
      let deferred = WINDOW_SHOWING_PROMISES.get(openedWindow);
      windowOpenedPromises.push(deferred.promise);
    }
    return Promise.all(windowOpenedPromises);
  },

  /** reset closedId's from previous sessions to ensure these IDs are unique
   * @param tabData
   *        an array of data to be restored
   * @param {String} windowId
   *        The SessionStore id for the window these tabs should be associated with
   * @returns the updated tabData array
   */
  _resetClosedTabIds(tabData, windowId) {
    for (let entry of tabData) {
      entry.closedId = this._nextClosedId++;
      entry.sourceWindowId = windowId;
    }
    return tabData;
  },
  /**
   * restore features to a single window
   * @param aWindow
   *        Window reference to the window to use for restoration
   * @param winData
   *        JS object
   * @param aOptions.overwriteTabs
   *        to overwrite existing tabs w/ new ones
   * @param aOptions.firstWindow
   *        if this is the first non-private window we're
   *        restoring in this session, that might open an
   *        external link as well
   */
  restoreWindow: function ssi_restoreWindow(aWindow, winData, aOptions = {}) {
    let overwriteTabs = aOptions && aOptions.overwriteTabs;
    let firstWindow = aOptions && aOptions.firstWindow;

    // initialize window if necessary
    if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi])) {
      this.onLoad(aWindow);
    }

    TelemetryStopwatch.start("FX_SESSION_RESTORE_RESTORE_WINDOW_MS");

    // We're not returning from this before we end up calling restoreTabs
    // for this window, so make sure we send the SSWindowStateBusy event.
    this._sendWindowRestoringNotification(aWindow);
    this._setWindowStateBusy(aWindow);

    if (winData.workspaceID) {
      aWindow.moveToWorkspace(winData.workspaceID);
    }

    if (!winData.tabs) {
      winData.tabs = [];
      // don't restore a single blank tab when we've had an external
      // URL passed in for loading at startup (cf. bug 357419)
    } else if (
      firstWindow &&
      !overwriteTabs &&
      winData.tabs.length == 1 &&
      (!winData.tabs[0].entries || !winData.tabs[0].entries.length)
    ) {
      winData.tabs = [];
    }

    // See SessionStoreInternal.restoreTabs for a description of what
    // selectTab represents.
    let selectTab = 0;
    if (overwriteTabs) {
      selectTab = parseInt(winData.selected || 1, 10);
      selectTab = Math.max(selectTab, 1);
      selectTab = Math.min(selectTab, winData.tabs.length);
    }

    let tabbrowser = aWindow.gBrowser;

    // disable smooth scrolling while adding, moving, removing and selecting tabs
    let arrowScrollbox = tabbrowser.tabContainer.arrowScrollbox;
    let smoothScroll = arrowScrollbox.smoothScroll;
    arrowScrollbox.smoothScroll = false;

    // We need to keep track of the initially open tabs so that they
    // can be moved to the end of the restored tabs.
    let initialTabs;
    if (!overwriteTabs && firstWindow) {
      initialTabs = Array.from(tabbrowser.tabs);
    }

    // Get rid of tabs that aren't needed anymore.
    if (overwriteTabs) {
      for (let i = tabbrowser.browsers.length - 1; i >= 0; i--) {
        if (!tabbrowser.tabs[i].selected) {
          tabbrowser.removeTab(tabbrowser.tabs[i]);
        }
      }
    }

    let restoreTabsLazily =
      this._prefBranch.getBoolPref("sessionstore.restore_tabs_lazily") &&
      this._restore_on_demand;

    if (winData.tabs.length) {
      var tabs = tabbrowser.createTabsForSessionRestore(
        restoreTabsLazily,
        selectTab,
        winData.tabs
      );
    }

    // Move the originally open tabs to the end.
    if (initialTabs) {
      let endPosition = tabbrowser.tabs.length - 1;
      for (let i = 0; i < initialTabs.length; i++) {
        tabbrowser.unpinTab(initialTabs[i]);
        tabbrowser.moveTabTo(initialTabs[i], endPosition);
      }
    }

    // We want to correlate the window with data from the last session, so
    // assign another id if we have one. Otherwise clear so we don't do
    // anything with it.
    delete aWindow.__SS_lastSessionWindowID;
    if (winData.__lastSessionWindowID) {
      aWindow.__SS_lastSessionWindowID = winData.__lastSessionWindowID;
    }

    if (overwriteTabs) {
      delete this._windows[aWindow.__SSi].extData;
    }

    // Restore cookies from legacy sessions, i.e. before bug 912717.
    lazy.SessionCookies.restore(winData.cookies || []);

    if (winData.extData) {
      if (!this._windows[aWindow.__SSi].extData) {
        this._windows[aWindow.__SSi].extData = {};
      }
      for (var key in winData.extData) {
        this._windows[aWindow.__SSi].extData[key] = winData.extData[key];
      }
    }

    let newClosedTabsData;
    if (winData._closedTabs) {
      newClosedTabsData = winData._closedTabs;
      this._resetClosedTabIds(newClosedTabsData, aWindow.__SSi);
    } else {
      newClosedTabsData = [];
    }

    let newLastClosedTabGroupCount = winData._lastClosedTabGroupCount || -1;

    if (overwriteTabs || firstWindow) {
      // Overwrite existing closed tabs data when overwriteTabs=true
      // or we're the first window to be restored.
      this._windows[aWindow.__SSi]._closedTabs = newClosedTabsData;
    } else if (this._max_tabs_undo > 0) {
      // We preserve tabs between sessions so we just want to filter out any previously open tabs that
      // were added to the _closedTabs list prior to restoreLastSession
      if (PERSIST_SESSIONS) {
        newClosedTabsData = this._windows[aWindow.__SSi]._closedTabs.filter(
          tab => !tab.removeAfterRestore
        );
      } else {
        newClosedTabsData = newClosedTabsData.concat(
          this._windows[aWindow.__SSi]._closedTabs
        );
      }

      // ... and make sure that we don't exceed the max number of closed tabs
      // we can restore.
      this._windows[aWindow.__SSi]._closedTabs = newClosedTabsData.slice(
        0,
        this._max_tabs_undo
      );
    }
    // Because newClosedTabsData are put in first, we need to
    // copy also the _lastClosedTabGroupCount.
    this._windows[aWindow.__SSi]._lastClosedTabGroupCount =
      newLastClosedTabGroupCount;

    if (!this._isWindowLoaded(aWindow)) {
      // from now on, the data will come from the actual window
      delete this._statesToRestore[WINDOW_RESTORE_IDS.get(aWindow)];
      WINDOW_RESTORE_IDS.delete(aWindow);
      delete this._windows[aWindow.__SSi]._restoring;
    }

    // Restore tabs, if any.
    if (winData.tabs.length) {
      this.restoreTabs(aWindow, tabs, winData.tabs, selectTab);
    }

    // set smoothScroll back to the original value
    arrowScrollbox.smoothScroll = smoothScroll;

    TelemetryStopwatch.finish("FX_SESSION_RESTORE_RESTORE_WINDOW_MS");

    this._setWindowStateReady(aWindow);

    this._sendWindowRestoredNotification(aWindow);

    Services.obs.notifyObservers(aWindow, NOTIFY_SINGLE_WINDOW_RESTORED);

    this._sendRestoreCompletedNotifications();
  },

  /**
   * Prepare connection to host beforehand.
   *
   * @param tab
   *        Tab we are loading from.
   * @param url
   *        URL of a host.
   * @returns a flag indicates whether a connection has been made
   */
  prepareConnectionToHost(tab, url) {
    if (url && !url.startsWith("about:")) {
      let principal = Services.scriptSecurityManager.createNullPrincipal({
        userContextId: tab.userContextId,
      });
      let sc = Services.io.QueryInterface(Ci.nsISpeculativeConnect);
      let uri = Services.io.newURI(url);
      try {
        sc.speculativeConnect(uri, principal, null, false);
        return true;
      } catch (error) {
        // Can't setup speculative connection for this url.
        console.error(error);
        return false;
      }
    }
    return false;
  },

  /**
   * Make a connection to a host when users hover mouse on a tab.
   * This will also set a flag in the tab to prevent us from speculatively
   * connecting a second time.
   *
   * @param tab
   *        a tab to speculatively connect on mouse hover.
   */
  speculativeConnectOnTabHover(tab) {
    let tabState = TAB_LAZY_STATES.get(tab);
    if (tabState && !tabState.connectionPrepared) {
      let url = this.getLazyTabValue(tab, "url");
      let prepared = this.prepareConnectionToHost(tab, url);
      // This is used to test if a connection has been made beforehand.
      if (gDebuggingEnabled) {
        tab.__test_connection_prepared = prepared;
        tab.__test_connection_url = url;
      }
      // A flag indicate that we've prepared a connection for this tab and
      // if is called again, we shouldn't prepare another connection.
      tabState.connectionPrepared = true;
    }
  },

  /**
   * This function will restore window features and then retore window data.
   *
   * @param windows
   *        ordered array of windows to restore
   */
  _restoreWindowsFeaturesAndTabs(windows) {
    // First, we restore window features, so that when users start interacting
    // with a window, we don't steal the window focus.
    for (let window of windows) {
      let state = this._statesToRestore[WINDOW_RESTORE_IDS.get(window)];
      this.restoreWindowFeatures(window, state.windows[0]);
    }

    // Then we restore data into windows.
    for (let window of windows) {
      let state = this._statesToRestore[WINDOW_RESTORE_IDS.get(window)];
      this.restoreWindow(
        window,
        state.windows[0],
        state.options || { overwriteTabs: true }
      );
      WINDOW_RESTORE_ZINDICES.delete(window);
    }
  },

  /**
   * This function will restore window in reversed z-index, so that users will
   * be presented with most recently used window first.
   *
   * @param windows
   *        unordered array of windows to restore
   */
  _restoreWindowsInReversedZOrder(windows) {
    windows.sort(
      (a, b) =>
        (WINDOW_RESTORE_ZINDICES.get(a) || 0) -
        (WINDOW_RESTORE_ZINDICES.get(b) || 0)
    );

    this.windowToFocus = windows[0];
    this._restoreWindowsFeaturesAndTabs(windows);
  },

  /**
   * Restore multiple windows using the provided state.
   * @param aWindow
   *        Window reference to the first window to use for restoration.
   *        Additionally required windows will be opened.
   * @param aState
   *        JS object or JSON string
   * @param aOptions.overwriteTabs
   *        to overwrite existing tabs w/ new ones
   * @param aOptions.firstWindow
   *        if this is the first non-private window we're
   *        restoring in this session, that might open an
   *        external link as well
   */
  restoreWindows: function ssi_restoreWindows(aWindow, aState, aOptions = {}) {
    // initialize window if necessary
    if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi])) {
      this.onLoad(aWindow);
    }

    let root;
    try {
      root = typeof aState == "string" ? JSON.parse(aState) : aState;
    } catch (ex) {
      // invalid state object - don't restore anything
      this._log.error(ex);
      this._sendRestoreCompletedNotifications();
      return;
    }

    // Restore closed windows if any.
    if (root._closedWindows) {
      this._closedWindows = root._closedWindows;
      // reset window closedIds and any references to them from closed tabs
      for (let closedWindow of this._closedWindows) {
        closedWindow.closedId = this._nextClosedId++;
        if (closedWindow._closedTabs?.length) {
          this._resetClosedTabIds(
            closedWindow._closedTabs,
            closedWindow.closedId
          );
        }
      }
      this._closedObjectsChanged = true;
    }

    // We're done here if there are no windows.
    if (!root.windows || !root.windows.length) {
      this._sendRestoreCompletedNotifications();
      return;
    }

    let firstWindowData = root.windows.splice(0, 1);
    // Store the restore state and restore option of the current window,
    // so that the window can be restored in reversed z-order.
    this._updateWindowRestoreState(aWindow, {
      windows: firstWindowData,
      options: aOptions,
    });

    // Begin the restoration: First open all windows in creation order. After all
    // windows have opened, we restore states to windows in reversed z-order.
    this._openWindows(root).then(windows => {
      // We want to add current window to opened window, so that this window will be
      // restored in reversed z-order. (We add the window to first position, in case
      // no z-indices are found, that window will be restored first.)
      windows.unshift(aWindow);

      this._restoreWindowsInReversedZOrder(windows);
    });

    lazy.DevToolsShim.restoreDevToolsSession(aState);
  },

  /**
   * Manage history restoration for a window
   * @param aWindow
   *        Window to restore the tabs into
   * @param aTabs
   *        Array of tab references
   * @param aTabData
   *        Array of tab data
   * @param aSelectTab
   *        Index of the tab to select. This is a 1-based index where "1"
   *        indicates the first tab should be selected, and "0" indicates that
   *        the currently selected tab will not be changed.
   */
  restoreTabs(aWindow, aTabs, aTabData, aSelectTab) {
    var tabbrowser = aWindow.gBrowser;

    let numTabsToRestore = aTabs.length;
    let numTabsInWindow = tabbrowser.tabs.length;
    let tabsDataArray = this._windows[aWindow.__SSi].tabs;

    // Update the window state in case we shut down without being notified.
    // Individual tab states will be taken care of by restoreTab() below.
    if (numTabsInWindow == numTabsToRestore) {
      // Remove all previous tab data.
      tabsDataArray.length = 0;
    } else {
      // Remove all previous tab data except tabs that should not be overriden.
      tabsDataArray.splice(numTabsInWindow - numTabsToRestore);
    }

    // Remove items from aTabData if there is no corresponding tab:
    if (numTabsInWindow < tabsDataArray.length) {
      tabsDataArray.length = numTabsInWindow;
    }

    // Ensure the tab data array has items for each of the tabs
    this._ensureNoNullsInTabDataList(
      tabbrowser.tabs,
      tabsDataArray,
      numTabsInWindow - 1
    );

    if (aSelectTab > 0 && aSelectTab <= aTabs.length) {
      // Update the window state in case we shut down without being notified.
      this._windows[aWindow.__SSi].selected = aSelectTab;
    }

    // If we restore the selected tab, make sure it goes first.
    let selectedIndex = aTabs.indexOf(tabbrowser.selectedTab);
    if (selectedIndex > -1) {
      this.restoreTab(tabbrowser.selectedTab, aTabData[selectedIndex]);
    }

    // Restore all tabs.
    for (let t = 0; t < aTabs.length; t++) {
      if (t != selectedIndex) {
        this.restoreTab(aTabs[t], aTabData[t]);
      }
    }
  },

  // In case we didn't collect/receive data for any tabs yet we'll have to
  // fill the array with at least empty tabData objects until |_tPos| or
  // we'll end up with |null| entries.
  _ensureNoNullsInTabDataList(tabElements, tabDataList, changedTabPos) {
    let initialDataListLength = tabDataList.length;
    if (changedTabPos < initialDataListLength) {
      return;
    }
    // Add items to the end.
    while (tabDataList.length < changedTabPos) {
      let existingTabEl = tabElements[tabDataList.length];
      tabDataList.push({
        entries: [],
        lastAccessed: existingTabEl.lastAccessed,
      });
    }
    // Ensure the pre-existing items are non-null.
    for (let i = 0; i < initialDataListLength; i++) {
      if (!tabDataList[i]) {
        let existingTabEl = tabElements[i];
        tabDataList[i] = {
          entries: [],
          lastAccessed: existingTabEl.lastAccessed,
        };
      }
    }
  },

  // Restores the given tab state for a given tab.
  restoreTab(tab, tabData, options = {}) {
    let browser = tab.linkedBrowser;

    if (TAB_STATE_FOR_BROWSER.has(browser)) {
      console.error("Must reset tab before calling restoreTab.");
      return;
    }

    let loadArguments = options.loadArguments;
    let window = tab.ownerGlobal;
    let tabbrowser = window.gBrowser;
    let forceOnDemand = options.forceOnDemand;
    let isRemotenessUpdate = options.isRemotenessUpdate;

    let willRestoreImmediately =
      options.restoreImmediately || tabbrowser.selectedBrowser == browser;

    let isBrowserInserted = browser.isConnected;

    // Increase the busy state counter before modifying the tab.
    this._setWindowStateBusy(window);

    // It's important to set the window state to dirty so that
    // we collect their data for the first time when saving state.
    DirtyWindows.add(window);

    if (!tab.hasOwnProperty("_tPos")) {
      throw new Error(
        "Shouldn't be trying to restore a tab that has no position"
      );
    }
    // Update the tab state in case we shut down without being notified.
    this._windows[window.__SSi].tabs[tab._tPos] = tabData;

    // Prepare the tab so that it can be properly restored.  We'll also attach
    // a copy of the tab's data in case we close it before it's been restored.
    // Anything that dispatches an event to external consumers must happen at
    // the end of this method, to make sure that the tab/browser object is in a
    // reliable and consistent state.

    if (tabData.lastAccessed) {
      tab.updateLastAccessed(tabData.lastAccessed);
    }

    if ("attributes" in tabData) {
      // Ensure that we persist tab attributes restored from previous sessions.
      Object.keys(tabData.attributes).forEach(a =>
        lazy.TabAttributes.persist(a)
      );
    }

    if (!tabData.entries) {
      tabData.entries = [];
    }
    if (tabData.extData) {
      TAB_CUSTOM_VALUES.set(tab, Cu.cloneInto(tabData.extData, {}));
    } else {
      TAB_CUSTOM_VALUES.delete(tab);
    }

    // Tab is now open.
    delete tabData.closedAt;

    // Ensure the index is in bounds.
    let activeIndex = (tabData.index || tabData.entries.length) - 1;
    activeIndex = Math.min(activeIndex, tabData.entries.length - 1);
    activeIndex = Math.max(activeIndex, 0);

    // Save the index in case we updated it above.
    tabData.index = activeIndex + 1;

    tab.setAttribute("pending", "true");

    // If we're restoring this tab, it certainly shouldn't be in
    // the ignored set anymore.
    this._crashedBrowsers.delete(browser.permanentKey);

    // If we're in the midst of performing a process flip, then we must
    // have initiated a navigation. This means that these userTyped*
    // values are now out of date.
    if (
      options.restoreContentReason ==
      RESTORE_TAB_CONTENT_REASON.NAVIGATE_AND_RESTORE
    ) {
      delete tabData.userTypedValue;
      delete tabData.userTypedClear;
    }

    // Update the persistent tab state cache with |tabData| information.
    lazy.TabStateCache.update(browser.permanentKey, {
      // NOTE: Copy the entries array shallowly, so as to not screw with the
      // original tabData's history when getting history updates.
      history: { entries: [...tabData.entries], index: tabData.index },
      scroll: tabData.scroll || null,
      storage: tabData.storage || null,
      formdata: tabData.formdata || null,
      disallow: tabData.disallow || null,
      userContextId: tabData.userContextId || 0,

      // This information is only needed until the tab has finished restoring.
      // When that's done it will be removed from the cache and we always
      // collect it in TabState._collectBaseTabData().
      image: tabData.image || "",
      iconLoadingPrincipal: tabData.iconLoadingPrincipal || null,
      searchMode: tabData.searchMode || null,
      userTypedValue: tabData.userTypedValue || "",
      userTypedClear: tabData.userTypedClear || 0,
    });

    // Restore tab attributes.
    if ("attributes" in tabData) {
      lazy.TabAttributes.set(tab, tabData.attributes);
    }

    if (isBrowserInserted) {
      // Start a new epoch to discard all frame script messages relating to a
      // previous epoch. All async messages that are still on their way to chrome
      // will be ignored and don't override any tab data set when restoring.
      let epoch = this.startNextEpoch(browser.permanentKey);

      // Ensure that the tab will get properly restored in the event the tab
      // crashes while restoring.  But don't set this on lazy browsers as
      // restoreTab will get called again when the browser is instantiated.
      TAB_STATE_FOR_BROWSER.set(browser, TAB_STATE_NEEDS_RESTORE);

      this._sendRestoreHistory(browser, {
        tabData,
        epoch,
        loadArguments,
        isRemotenessUpdate,
      });

      // This could cause us to ignore MAX_CONCURRENT_TAB_RESTORES a bit, but
      // it ensures each window will have its selected tab loaded.
      if (willRestoreImmediately) {
        this.restoreTabContent(tab, options);
      } else if (!forceOnDemand) {
        TabRestoreQueue.add(tab);
        // Check if a tab is in queue and will be restored
        // after the currently loading tabs. If so, prepare
        // a connection to host to speed up page loading.
        if (TabRestoreQueue.willRestoreSoon(tab)) {
          if (activeIndex in tabData.entries) {
            let url = tabData.entries[activeIndex].url;
            let prepared = this.prepareConnectionToHost(tab, url);
            if (gDebuggingEnabled) {
              tab.__test_connection_prepared = prepared;
              tab.__test_connection_url = url;
            }
          }
        }
        this.restoreNextTab();
      }
    } else {
      // TAB_LAZY_STATES holds data for lazy-browser tabs to proxy for
      // data unobtainable from the unbound browser.  This only applies to lazy
      // browsers and will be removed once the browser is inserted in the document.
      // This must preceed `updateTabLabelAndIcon` call for required data to be present.
      let url = "about:blank";
      let title = "";

      if (activeIndex in tabData.entries) {
        url = tabData.entries[activeIndex].url;
        title = tabData.entries[activeIndex].title || url;
      }
      TAB_LAZY_STATES.set(tab, {
        url,
        title,
        userTypedValue: tabData.userTypedValue || "",
        userTypedClear: tabData.userTypedClear || 0,
      });
    }

    // Most of tabData has been restored, now continue with restoring
    // attributes that may trigger external events.

    if (tabData.pinned) {
      tabbrowser.pinTab(tab);
    } else {
      tabbrowser.unpinTab(tab);
    }

    if (tabData.hidden) {
      tabbrowser.hideTab(tab);
    } else {
      tabbrowser.showTab(tab);
    }

    if (!!tabData.muted != browser.audioMuted) {
      tab.toggleMuteAudio(tabData.muteReason);
    }

    if (tab.hasAttribute("customizemode")) {
      window.gCustomizeMode.setTab(tab);
    }

    // Update tab label and icon to show something
    // while we wait for the messages to be processed.
    this.updateTabLabelAndIcon(tab, tabData);

    // Decrease the busy state counter after we're done.
    this._setWindowStateReady(window);
  },

  /**
   * Kicks off restoring the given tab.
   *
   * @param aTab
   *        the tab to restore
   * @param aOptions
   *        optional arguments used when performing process switch during load
   */
  restoreTabContent(aTab, aOptions = {}) {
    let loadArguments = aOptions.loadArguments;
    if (aTab.hasAttribute("customizemode") && !loadArguments) {
      return;
    }

    let browser = aTab.linkedBrowser;
    let window = aTab.ownerGlobal;
    let tabbrowser = window.gBrowser;
    let tabData = lazy.TabState.clone(aTab, TAB_CUSTOM_VALUES.get(aTab));
    let activeIndex = tabData.index - 1;
    let activePageData = tabData.entries[activeIndex] || null;
    let uri = activePageData ? activePageData.url || null : null;

    this.markTabAsRestoring(aTab);

    let isRemotenessUpdate = aOptions.isRemotenessUpdate;
    let explicitlyUpdateRemoteness = !Services.appinfo.sessionHistoryInParent;
    // If we aren't already updating the browser's remoteness, check if it's
    // necessary.
    if (explicitlyUpdateRemoteness && !isRemotenessUpdate) {
      isRemotenessUpdate = tabbrowser.updateBrowserRemotenessByURL(
        browser,
        uri
      );

      if (isRemotenessUpdate) {
        // We updated the remoteness, so we need to send the history down again.
        //
        // Start a new epoch to discard all frame script messages relating to a
        // previous epoch. All async messages that are still on their way to chrome
        // will be ignored and don't override any tab data set when restoring.
        let epoch = this.startNextEpoch(browser.permanentKey);

        this._sendRestoreHistory(browser, {
          tabData,
          epoch,
          loadArguments,
          isRemotenessUpdate,
        });
      }
    }

    this._sendRestoreTabContent(browser, {
      loadArguments,
      isRemotenessUpdate,
      reason:
        aOptions.restoreContentReason || RESTORE_TAB_CONTENT_REASON.SET_STATE,
    });

    // Focus the tab's content area, unless the restore is for a new tab URL or
    // was triggered by a DocumentChannel process switch.
    if (
      aTab.selected &&
      !window.isBlankPageURL(uri) &&
      !aOptions.isRemotenessUpdate
    ) {
      browser.focus();
    }
  },

  /**
   * Marks a given pending tab as restoring.
   *
   * @param aTab
   *        the pending tab to mark as restoring
   */
  markTabAsRestoring(aTab) {
    let browser = aTab.linkedBrowser;
    if (TAB_STATE_FOR_BROWSER.get(browser) != TAB_STATE_NEEDS_RESTORE) {
      throw new Error("Given tab is not pending.");
    }

    // Make sure that this tab is removed from the priority queue.
    TabRestoreQueue.remove(aTab);

    // Increase our internal count.
    this._tabsRestoringCount++;

    // Set this tab's state to restoring
    TAB_STATE_FOR_BROWSER.set(browser, TAB_STATE_RESTORING);
    aTab.removeAttribute("pending");
  },

  /**
   * This _attempts_ to restore the next available tab. If the restore fails,
   * then we will attempt the next one.
   * There are conditions where this won't do anything:
   *   if we're in the process of quitting
   *   if there are no tabs to restore
   *   if we have already reached the limit for number of tabs to restore
   */
  restoreNextTab: function ssi_restoreNextTab() {
    // If we call in here while quitting, we don't actually want to do anything
    if (lazy.RunState.isQuitting) {
      return;
    }

    // Don't exceed the maximum number of concurrent tab restores.
    if (this._tabsRestoringCount >= MAX_CONCURRENT_TAB_RESTORES) {
      return;
    }

    let tab = TabRestoreQueue.shift();
    if (tab) {
      this.restoreTabContent(tab);
    }
  },

  /**
   * Restore visibility and dimension features to a window
   * @param aWindow
   *        Window reference
   * @param aWinData
   *        Object containing session data for the window
   */
  restoreWindowFeatures: function ssi_restoreWindowFeatures(aWindow, aWinData) {
    var hidden = aWinData.hidden ? aWinData.hidden.split(",") : [];
    WINDOW_HIDEABLE_FEATURES.forEach(function (aItem) {
      aWindow[aItem].visible = !hidden.includes(aItem);
    });

    if (aWinData.isPopup) {
      this._windows[aWindow.__SSi].isPopup = true;
      if (aWindow.gURLBar) {
        aWindow.gURLBar.readOnly = true;
      }
    } else {
      delete this._windows[aWindow.__SSi].isPopup;
      if (aWindow.gURLBar) {
        aWindow.gURLBar.readOnly = false;
      }
    }

    aWindow.setTimeout(() => {
      this.restoreDimensions(
        aWindow,
        +(aWinData.width || 0),
        +(aWinData.height || 0),
        "screenX" in aWinData ? +aWinData.screenX : NaN,
        "screenY" in aWinData ? +aWinData.screenY : NaN,
        aWinData.sizemode || "",
        aWinData.sizemodeBeforeMinimized || "",
        aWinData.sidebar || ""
      );
    }, 0);
  },

  /**
   * Restore a window's dimensions
   * @param aWidth
   *        Window width in desktop pixels
   * @param aHeight
   *        Window height in desktop pixels
   * @param aLeft
   *        Window left in desktop pixels
   * @param aTop
   *        Window top in desktop pixels
   * @param aSizeMode
   *        Window size mode (eg: maximized)
   * @param aSizeModeBeforeMinimized
   *        Window size mode before window got minimized (eg: maximized)
   * @param aSidebar
   *        Sidebar command
   */
  restoreDimensions: function ssi_restoreDimensions(
    aWindow,
    aWidth,
    aHeight,
    aLeft,
    aTop,
    aSizeMode,
    aSizeModeBeforeMinimized,
    aSidebar
  ) {
    var win = aWindow;
    var _this = this;
    function win_(aName) {
      return _this._getWindowDimension(win, aName);
    }

    const dwu = win.windowUtils;
    // find available space on the screen where this window is being placed
    let screen = lazy.gScreenManager.screenForRect(
      aLeft,
      aTop,
      aWidth,
      aHeight
    );
    if (screen) {
      let screenLeft = {},
        screenTop = {},
        screenWidth = {},
        screenHeight = {};
      screen.GetAvailRectDisplayPix(
        screenLeft,
        screenTop,
        screenWidth,
        screenHeight
      );

      // We store aLeft / aTop (screenX/Y) in desktop pixels, see
      // _getWindowDimension.
      screenLeft = screenLeft.value;
      screenTop = screenTop.value;
      screenWidth = screenWidth.value;
      screenHeight = screenHeight.value;

      let screenBottom = screenTop + screenHeight;
      let screenRight = screenLeft + screenWidth;

      // NOTE: contentsScaleFactor is the desktopToDeviceScale of the screen.
      // Naming could be more consistent here.
      let cssToDesktopScale =
        screen.defaultCSSScaleFactor / screen.contentsScaleFactor;

      let winSlopX = win.screenEdgeSlopX * cssToDesktopScale;
      let winSlopY = win.screenEdgeSlopY * cssToDesktopScale;

      let minSlop = MIN_SCREEN_EDGE_SLOP * cssToDesktopScale;
      let slopX = Math.max(minSlop, winSlopX);
      let slopY = Math.max(minSlop, winSlopY);

      // Pull the window within the screen's bounds (allowing a little slop
      // for windows that may be deliberately placed with their border off-screen
      // as when Win10 "snaps" a window to the left/right edge -- bug 1276516).
      // First, ensure the left edge is large enough...
      if (aLeft < screenLeft - slopX) {
        aLeft = screenLeft - winSlopX;
      }
      // Then check the resulting right edge, and reduce it if necessary.
      let right = aLeft + aWidth * cssToDesktopScale;
      if (right > screenRight + slopX) {
        right = screenRight + winSlopX;
        // See if we can move the left edge leftwards to maintain width.
        if (aLeft > screenLeft) {
          aLeft = Math.max(
            right - aWidth * cssToDesktopScale,
            screenLeft - winSlopX
          );
        }
      }
      // Finally, update aWidth to account for the adjusted left and right
      // edges, and convert it back to CSS pixels on the target screen.
      aWidth = (right - aLeft) / cssToDesktopScale;

      // And do the same in the vertical dimension.
      if (aTop < screenTop - slopY) {
        aTop = screenTop - winSlopY;
      }
      let bottom = aTop + aHeight * cssToDesktopScale;
      if (bottom > screenBottom + slopY) {
        bottom = screenBottom + winSlopY;
        if (aTop > screenTop) {
          aTop = Math.max(
            bottom - aHeight * cssToDesktopScale,
            screenTop - winSlopY
          );
        }
      }
      aHeight = (bottom - aTop) / cssToDesktopScale;
    }

    // Suppress animations.
    dwu.suppressAnimation(true);

    // We want to make sure users will get their animations back in case an exception is thrown.
    try {
      // only modify those aspects which aren't correct yet
      if (
        !isNaN(aLeft) &&
        !isNaN(aTop) &&
        (aLeft != win_("screenX") || aTop != win_("screenY"))
      ) {
        // moveTo uses CSS pixels relative to aWindow, while aLeft and aRight
        // are on desktop pixels, undo the conversion we do in
        // _getWindowDimension.
        let desktopToCssScale =
          aWindow.desktopToDeviceScale / aWindow.devicePixelRatio;
        aWindow.moveTo(aLeft * desktopToCssScale, aTop * desktopToCssScale);
      }
      if (
        aWidth &&
        aHeight &&
        (aWidth != win_("width") || aHeight != win_("height")) &&
        !gResistFingerprintingEnabled
      ) {
        // Don't resize the window if it's currently maximized and we would
        // maximize it again shortly after.
        if (aSizeMode != "maximized" || win_("sizemode") != "maximized") {
          aWindow.resizeTo(aWidth, aHeight);
        }
      }
      this._windows[aWindow.__SSi].sizemodeBeforeMinimized =
        aSizeModeBeforeMinimized;
      if (
        aSizeMode &&
        win_("sizemode") != aSizeMode &&
        !gResistFingerprintingEnabled
      ) {
        switch (aSizeMode) {
          case "maximized":
            aWindow.maximize();
            break;
          case "minimized":
            if (aSizeModeBeforeMinimized == "maximized") {
              aWindow.maximize();
            }
            aWindow.minimize();
            break;
          case "normal":
            aWindow.restore();
            break;
        }
      }
      let sidebarBox = aWindow.document.getElementById("sidebar-box");
      if (
        aSidebar &&
        (sidebarBox.getAttribute("sidebarcommand") != aSidebar ||
          !sidebarBox.getAttribute("checked"))
      ) {
        aWindow.SidebarUI.showInitially(aSidebar);
      }
      // since resizing/moving a window brings it to the foreground,
      // we might want to re-focus the last focused window
      if (this.windowToFocus) {
        this.windowToFocus.focus();
      }
    } finally {
      // Enable animations.
      dwu.suppressAnimation(false);
    }
  },

  /* ........ Disk Access .............. */

  /**
   * Save the current session state to disk, after a delay.
   *
   * @param aWindow (optional)
   *        Will mark the given window as dirty so that we will recollect its
   *        data before we start writing.
   */
  saveStateDelayed(aWindow = null) {
    if (aWindow) {
      DirtyWindows.add(aWindow);
    }

    lazy.SessionSaver.runDelayed();
  },

  /* ........ Auxiliary Functions .............. */

  /**
   * Remove a closed window from the list of closed windows and indicate that
   * the change should be notified.
   *
   * @param index
   *        The index of the window in this._closedWindows.
   *
   * @returns Array of closed windows.
   */
  _removeClosedWindow(index) {
    // remove all of the closed tabs from the _lastClosedActions list
    // before removing the window from it
    for (let closedTab of this._closedWindows[index]._closedTabs) {
      this._removeClosedAction(
        this._LAST_ACTION_CLOSED_TAB,
        closedTab.closedId
      );
    }
    this._removeClosedAction(
      this._LAST_ACTION_CLOSED_WINDOW,
      this._closedWindows[index].closedId
    );
    let windows = this._closedWindows.splice(index, 1);
    this._closedObjectsChanged = true;
    return windows;
  },

  /**
   * Notifies observers that the list of closed tabs and/or windows has changed.
   * Waits a tick to allow SessionStorage a chance to register the change.
   */
  _notifyOfClosedObjectsChange() {
    if (!this._closedObjectsChanged) {
      return;
    }
    this._closedObjectsChanged = false;
    lazy.setTimeout(() => {
      Services.obs.notifyObservers(null, NOTIFY_CLOSED_OBJECTS_CHANGED);
    }, 0);
  },

  /**
   * Update the session start time and send a telemetry measurement
   * for the number of days elapsed since the session was started.
   *
   * @param state
   *        The session state.
   */
  _updateSessionStartTime: function ssi_updateSessionStartTime(state) {
    // Attempt to load the session start time from the session state
    if (state.session && state.session.startTime) {
      this._sessionStartTime = state.session.startTime;
    }
  },

  /**
   * Iterator that yields all currently opened browser windows.
   * (Might miss the most recent one.)
   * This list is in focus order, but may include minimized windows
   * before non-minimized windows.
   */
  _browserWindows: {
    *[Symbol.iterator]() {
      for (let window of lazy.BrowserWindowTracker.orderedWindows) {
        if (window.__SSi && !window.closed) {
          yield window;
        }
      }
    },
  },

  /**
   * Iterator that yields all currently opened browser windows,
   * with minimized windows last.
   * (Might miss the most recent window.)
   */
  _orderedBrowserWindows: {
    *[Symbol.iterator]() {
      let windows = lazy.BrowserWindowTracker.orderedWindows;
      windows.sort((a, b) => {
        if (
          a.windowState == a.STATE_MINIMIZED &&
          b.windowState != b.STATE_MINIMIZED
        ) {
          return 1;
        }
        if (
          a.windowState != a.STATE_MINIMIZED &&
          b.windowState == b.STATE_MINIMIZED
        ) {
          return -1;
        }
        return 0;
      });
      for (let window of windows) {
        if (window.__SSi && !window.closed) {
          yield window;
        }
      }
    },
  },

  /**
   * Returns most recent window
   * @param {boolean} [isPrivate]
   *        Optional boolean to get only non-private or private windows
   *        When omitted, we'll return whatever the top-most window is regardless of privateness
   * @returns Window reference
   */
  _getTopWindow: function ssi_getTopWindow(isPrivate) {
    const options = { allowPopups: true };
    if (typeof isPrivate !== "undefined") {
      options.private = isPrivate;
    }
    return lazy.BrowserWindowTracker.getTopWindow(options);
  },

  /**
   * Calls onClose for windows that are determined to be closed but aren't
   * destroyed yet, which would otherwise cause getBrowserState and
   * setBrowserState to treat them as open windows.
   */
  _handleClosedWindows: function ssi_handleClosedWindows() {
    let promises = [];
    for (let window of Services.wm.getEnumerator("navigator:browser")) {
      if (window.closed) {
        promises.push(this.onClose(window));
      }
    }
    return Promise.all(promises);
  },

  /**
   * Store a restore state of a window to this._statesToRestore. The window
   * will be given an id that can be used to get the restore state from
   * this._statesToRestore.
   *
   * @param window
   *        a reference to a window that has a state to restore
   * @param state
   *        an object containing session data
   */
  _updateWindowRestoreState(window, state) {
    // Store z-index, so that windows can be restored in reversed z-order.
    if ("zIndex" in state.windows[0]) {
      WINDOW_RESTORE_ZINDICES.set(window, state.windows[0].zIndex);
    }
    do {
      var ID = "window" + Math.random();
    } while (ID in this._statesToRestore);
    WINDOW_RESTORE_IDS.set(window, ID);
    this._statesToRestore[ID] = state;
  },

  /**
   * open a new browser window for a given session state
   * called when restoring a multi-window session
   * @param aState
   *        Object containing session data
   */
  _openWindowWithState: function ssi_openWindowWithState(aState) {
    var argString = Cc["@mozilla.org/supports-string;1"].createInstance(
      Ci.nsISupportsString
    );
    argString.data = "";

    // Build feature string
    let features;
    let winState = aState.windows[0];
    if (winState.chromeFlags) {
      features = ["chrome", "suppressanimation"];
      let chromeFlags = winState.chromeFlags;
      const allFlags = Ci.nsIWebBrowserChrome.CHROME_ALL;
      const hasAll = (chromeFlags & allFlags) == allFlags;
      if (hasAll) {
        features.push("all");
      }
      for (let [flag, onValue, offValue] of CHROME_FLAGS_MAP) {
        if (hasAll && allFlags & flag) {
          continue;
        }
        let value = chromeFlags & flag ? onValue : offValue;
        if (value) {
          features.push(value);
        }
      }
    } else {
      // |chromeFlags| is not found. Fallbacks to the old method.
      features = ["chrome", "dialog=no", "suppressanimation"];
      let hidden = winState.hidden?.split(",") || [];
      if (!hidden.length) {
        features.push("all");
      } else {
        features.push("resizable");
        WINDOW_HIDEABLE_FEATURES.forEach(aFeature => {
          if (!hidden.includes(aFeature)) {
            features.push(WINDOW_OPEN_FEATURES_MAP[aFeature] || aFeature);
          }
        });
      }
    }
    WINDOW_ATTRIBUTES.forEach(aFeature => {
      // Use !isNaN as an easy way to ignore sizemode and check for numbers
      if (aFeature in winState && !isNaN(winState[aFeature])) {
        features.push(aFeature + "=" + winState[aFeature]);
      }
    });

    if (winState.isPrivate) {
      features.push("private");
    }

    var window = Services.ww.openWindow(
      null,
      AppConstants.BROWSER_CHROME_URL,
      "_blank",
      features.join(","),
      argString
    );

    this._updateWindowRestoreState(window, aState);
    WINDOW_SHOWING_PROMISES.set(window, Promise.withResolvers());

    return window;
  },

  /**
   * whether the user wants to load any other page at startup
   * (except the homepage) - needed for determining whether to overwrite the current tabs
   * C.f.: nsBrowserContentHandler's defaultArgs implementation.
   * @returns bool
   */
  _isCmdLineEmpty: function ssi_isCmdLineEmpty(aWindow, aState) {
    var pinnedOnly =
      aState.windows &&
      aState.windows.every(win => win.tabs.every(tab => tab.pinned));

    let hasFirstArgument = aWindow.arguments && aWindow.arguments[0];
    if (!pinnedOnly) {
      let defaultArgs = Cc["@mozilla.org/browser/clh;1"].getService(
        Ci.nsIBrowserHandler
      ).defaultArgs;
      if (
        aWindow.arguments &&
        aWindow.arguments[0] &&
        aWindow.arguments[0] == defaultArgs
      ) {
        hasFirstArgument = false;
      }
    }

    return !hasFirstArgument;
  },

  /**
   * on popup windows, the AppWindow's attributes seem not to be set correctly
   * we use thus JSDOMWindow attributes for sizemode and normal window attributes
   * (and hope for reasonable values when maximized/minimized - since then
   * outerWidth/outerHeight aren't the dimensions of the restored window)
   * @param aWindow
   *        Window reference
   * @param aAttribute
   *        String sizemode | width | height | other window attribute
   * @returns string
   */
  _getWindowDimension: function ssi_getWindowDimension(aWindow, aAttribute) {
    if (aAttribute == "sizemode") {
      switch (aWindow.windowState) {
        case aWindow.STATE_FULLSCREEN:
        case aWindow.STATE_MAXIMIZED:
          return "maximized";
        case aWindow.STATE_MINIMIZED:
          return "minimized";
        default:
          return "normal";
      }
    }

    // We want to persist the size / position in normal state, so that
    // we can restore to them even if the window is currently maximized
    // or minimized. However, attributes on window object only reflect
    // the current state of the window, so when it isn't in the normal
    // sizemode, their values aren't what we want the window to restore
    // to. In that case, try to read from the attributes of the root
    // element first instead.
    if (aWindow.windowState != aWindow.STATE_NORMAL) {
      let docElem = aWindow.document.documentElement;
      let attr = parseInt(docElem.getAttribute(aAttribute), 10);
      if (attr) {
        if (aAttribute != "width" && aAttribute != "height") {
          return attr;
        }
        // Width and height attribute report the inner size, but we want
        // to store the outer size, so add the difference.
        let appWin = aWindow.docShell.treeOwner
          .QueryInterface(Ci.nsIInterfaceRequestor)
          .getInterface(Ci.nsIAppWindow);
        let diff =
          aAttribute == "width"
            ? appWin.outerToInnerWidthDifferenceInCSSPixels
            : appWin.outerToInnerHeightDifferenceInCSSPixels;
        return attr + diff;
      }
    }

    switch (aAttribute) {
      case "width":
        return aWindow.outerWidth;
      case "height":
        return aWindow.outerHeight;
      case "screenX":
      case "screenY":
        // We use desktop pixels rather than CSS pixels to store window
        // positions, see bug 1247335.  This allows proper multi-monitor
        // positioning in mixed-DPI situations.
        // screenX/Y are in CSS pixels for the current window, so, convert them
        // to desktop pixels.
        return (
          (aWindow[aAttribute] * aWindow.devicePixelRatio) /
          aWindow.desktopToDeviceScale
        );
      default:
        return aAttribute in aWindow ? aWindow[aAttribute] : "";
    }
  },

  /**
   * @param aState is a session state
   * @param aRecentCrashes is the number of consecutive crashes
   * @returns whether a restore page will be needed for the session state
   */
  _needsRestorePage: function ssi_needsRestorePage(aState, aRecentCrashes) {
    const SIX_HOURS_IN_MS = 6 * 60 * 60 * 1000;

    // don't display the page when there's nothing to restore
    let winData = aState.windows || null;
    if (!winData || !winData.length) {
      return false;
    }

    // don't wrap a single about:sessionrestore page
    if (
      this._hasSingleTabWithURL(winData, "about:sessionrestore") ||
      this._hasSingleTabWithURL(winData, "about:welcomeback")
    ) {
      return false;
    }

    // don't automatically restore in Safe Mode
    if (Services.appinfo.inSafeMode) {
      return true;
    }

    let max_resumed_crashes = this._prefBranch.getIntPref(
      "sessionstore.max_resumed_crashes"
    );
    let sessionAge =
      aState.session &&
      aState.session.lastUpdate &&
      Date.now() - aState.session.lastUpdate;

    let decision =
      max_resumed_crashes != -1 &&
      (aRecentCrashes > max_resumed_crashes ||
        (sessionAge && sessionAge >= SIX_HOURS_IN_MS));
    if (decision) {
      let key;
      if (aRecentCrashes > max_resumed_crashes) {
        if (sessionAge && sessionAge >= SIX_HOURS_IN_MS) {
          key = "shown_many_crashes_old_session";
        } else {
          key = "shown_many_crashes";
        }
      } else {
        key = "shown_old_session";
      }
      Services.telemetry.keyedScalarAdd(
        "browser.engagement.sessionrestore_interstitial",
        key,
        1
      );
    }
    return decision;
  },

  /**
   * @param aWinData is the set of windows in session state
   * @param aURL is the single URL we're looking for
   * @returns whether the window data contains only the single URL passed
   */
  _hasSingleTabWithURL(aWinData, aURL) {
    if (
      aWinData &&
      aWinData.length == 1 &&
      aWinData[0].tabs &&
      aWinData[0].tabs.length == 1 &&
      aWinData[0].tabs[0].entries &&
      aWinData[0].tabs[0].entries.length == 1
    ) {
      return aURL == aWinData[0].tabs[0].entries[0].url;
    }
    return false;
  },

  /**
   * Determine if the tab state we're passed is something we should save. This
   * is used when closing a tab or closing a window with a single tab
   *
   * @param aTabState
   *        The current tab state
   * @returns boolean
   */
  _shouldSaveTabState: function ssi_shouldSaveTabState(aTabState) {
    // If the tab has only a transient about: history entry, no other
    // session history, and no userTypedValue, then we don't actually want to
    // store this tab's data.
    const entryUrl = aTabState.entries[0]?.url;
    return (
      entryUrl &&
      !(
        aTabState.entries.length == 1 &&
        (entryUrl == "about:blank" ||
          entryUrl == "about:home" ||
          entryUrl == "about:newtab" ||
          entryUrl == "about:privatebrowsing") &&
        !aTabState.userTypedValue
      )
    );
  },

  /**
   * Determine if the tab state we're passed is something we should keep to be
   * reopened at session restore. This is used when we are saving the current
   * session state to disk. This method is very similar to _shouldSaveTabState,
   * however, "about:blank" and "about:newtab" tabs will still be saved to disk.
   *
   * @param aTabState
   *        The current tab state
   * @returns boolean
   */
  _shouldSaveTab: function ssi_shouldSaveTab(aTabState) {
    // If the tab has one of the following transient about: history entry, no
    // userTypedValue, and no customizemode attribute, then we don't actually
    // want to write this tab's data to disk.
    return (
      aTabState.userTypedValue ||
      (aTabState.attributes && aTabState.attributes.customizemode == "true") ||
      (aTabState.entries.length &&
        aTabState.entries[0].url != "about:privatebrowsing")
    );
  },

  /**
   * This is going to take a state as provided at startup (via
   * SessionStartup.state) and split it into 2 parts. The first part
   * (defaultState) will be a state that should still be restored at startup,
   * while the second part (state) is a state that should be saved for later.
   * defaultState will be comprised of windows with only pinned tabs, extracted
   * from a clone of startupState. It will also contain window position information.
   *
   * defaultState will be restored at startup. state will be passed into
   * LastSession and will be kept in case the user explicitly wants
   * to restore the previous session (publicly exposed as restoreLastSession).
   *
   * @param state
   *        The startupState, presumably from SessionStartup.state
   * @returns [defaultState, state]
   */
  _prepDataForDeferredRestore: function ssi_prepDataForDeferredRestore(
    startupState
  ) {
    // Make sure that we don't modify the global state as provided by
    // SessionStartup.state.
    let state = Cu.cloneInto(startupState, {});
    let hasPinnedTabs = false;
    let defaultState = { windows: [], selectedWindow: 1 };
    state.selectedWindow = state.selectedWindow || 1;

    // Look at each window, remove pinned tabs, adjust selectedindex,
    // remove window if necessary.
    for (let wIndex = 0; wIndex < state.windows.length; ) {
      let window = state.windows[wIndex];
      window.selected = window.selected || 1;
      // We're going to put the state of the window into this object, but for closedTabs
      // we want to preserve the original closedTabs since that will be saved as the lastSessionState
      let newWindowState = {
        tabs: [],
      };
      if (PERSIST_SESSIONS) {
        newWindowState._closedTabs = Cu.cloneInto(window._closedTabs, {});
      }
      for (let tIndex = 0; tIndex < window.tabs.length; ) {
        if (window.tabs[tIndex].pinned) {
          // Adjust window.selected
          if (tIndex + 1 < window.selected) {
            window.selected -= 1;
          } else if (tIndex + 1 == window.selected) {
            newWindowState.selected = newWindowState.tabs.length + 1;
          }
          // + 1 because the tab isn't actually in the array yet

          // Now add the pinned tab to our window
          newWindowState.tabs = newWindowState.tabs.concat(
            window.tabs.splice(tIndex, 1)
          );
          // We don't want to increment tIndex here.
          continue;
        } else if (!window.tabs[tIndex].hidden && PERSIST_SESSIONS) {
          // Add any previously open tabs that aren't pinned or hidden to the recently closed tabs list
          // which we want to persist between sessions; if the session is manually restored, they will
          // be filtered out of the closed tabs list (due to removeAfterRestore property) and reopened
          // per expected session restore behavior.

          let tabState = window.tabs[tIndex];

          // Ensure the index is in bounds.
          let activeIndex = tabState.index;
          activeIndex = Math.min(activeIndex, tabState.entries.length - 1);
          activeIndex = Math.max(activeIndex, 0);

          if (activeIndex in tabState.entries) {
            let title =
              tabState.entries[activeIndex].title ||
              tabState.entries[activeIndex].url;

            let tabData = {
              state: tabState,
              title,
              image: tabState.image,
              pos: tIndex,
              closedAt: Date.now(),
              closedInGroup: false,
              removeAfterRestore: true,
            };

            if (this._shouldSaveTabState(tabState)) {
              this.saveClosedTabData(
                window,
                newWindowState._closedTabs,
                tabData,
                false
              );
            }
          }
        }
        tIndex++;
      }

      hasPinnedTabs ||= !!newWindowState.tabs.length;

      // Only transfer over window attributes for pinned tabs, which has
      // already been extracted into newWindowState.tabs.
      if (newWindowState.tabs.length) {
        WINDOW_ATTRIBUTES.forEach(function (attr) {
          if (attr in window) {
            newWindowState[attr] = window[attr];
            delete window[attr];
          }
        });
        // We're just copying position data into the window for pinned tabs.
        // Not copying over:
        // - extData
        // - isPopup
        // - hidden

        // Assign a unique ID to correlate the window to be opened with the
        // remaining data
        window.__lastSessionWindowID = newWindowState.__lastSessionWindowID =
          "" + Date.now() + Math.random();
      }

      // If this newWindowState contains pinned tabs (stored in tabs) or
      // closed tabs, add it to the defaultState so they're available immediately.
      if (
        newWindowState.tabs.length ||
        (PERSIST_SESSIONS && newWindowState._closedTabs.length)
      ) {
        defaultState.windows.push(newWindowState);
        // Remove the window from the state if it doesn't have any tabs
        if (!window.tabs.length) {
          if (wIndex + 1 <= state.selectedWindow) {
            state.selectedWindow -= 1;
          } else if (wIndex + 1 == state.selectedWindow) {
            defaultState.selectedIndex = defaultState.windows.length + 1;
          }

          state.windows.splice(wIndex, 1);
          // We don't want to increment wIndex here.
          continue;
        }
      }
      wIndex++;
    }

    if (hasPinnedTabs) {
      // Move cookies over from so that they're restored right away and pinned tabs will load correctly.
      defaultState.cookies = state.cookies;
      delete state.cookies;
    }
    // we return state here rather than startupState so as to avoid duplicating
    // pinned tabs that we add to the defaultState (when a user restores a session)
    return [defaultState, state];
  },

  _sendRestoreCompletedNotifications:
    function ssi_sendRestoreCompletedNotifications() {
      // not all windows restored, yet
      if (this._restoreCount > 1) {
        this._restoreCount--;
        this._log.warn(
          `waiting on ${this._restoreCount} windows to be restored before sending restore complete notifications.`
        );
        return;
      }

      // observers were already notified
      if (this._restoreCount == -1) {
        return;
      }

      // This was the last window restored at startup, notify observers.
      if (!this._browserSetState) {
        Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED);
        this._deferredAllWindowsRestored.resolve();
      } else {
        // _browserSetState is used only by tests, and it uses an alternate
        // notification in order not to retrigger startup observers that
        // are listening for NOTIFY_WINDOWS_RESTORED.
        Services.obs.notifyObservers(null, NOTIFY_BROWSER_STATE_RESTORED);
      }

      this._browserSetState = false;
      this._restoreCount = -1;
    },

  /**
   * Set the given window's busy state
   * @param aWindow the window
   * @param aValue the window's busy state
   */
  _setWindowStateBusyValue: function ssi_changeWindowStateBusyValue(
    aWindow,
    aValue
  ) {
    this._windows[aWindow.__SSi].busy = aValue;

    // Keep the to-be-restored state in sync because that is returned by
    // getWindowState() as long as the window isn't loaded, yet.
    if (!this._isWindowLoaded(aWindow)) {
      let stateToRestore =
        this._statesToRestore[WINDOW_RESTORE_IDS.get(aWindow)].windows[0];
      stateToRestore.busy = aValue;
    }
  },

  /**
   * Set the given window's state to 'not busy'.
   * @param aWindow the window
   */
  _setWindowStateReady: function ssi_setWindowStateReady(aWindow) {
    let newCount = (this._windowBusyStates.get(aWindow) || 0) - 1;
    if (newCount < 0) {
      throw new Error("Invalid window busy state (less than zero).");
    }
    this._windowBusyStates.set(aWindow, newCount);

    if (newCount == 0) {
      this._setWindowStateBusyValue(aWindow, false);
      this._sendWindowStateReadyEvent(aWindow);
    }
  },

  /**
   * Set the given window's state to 'busy'.
   * @param aWindow the window
   */
  _setWindowStateBusy: function ssi_setWindowStateBusy(aWindow) {
    let newCount = (this._windowBusyStates.get(aWindow) || 0) + 1;
    this._windowBusyStates.set(aWindow, newCount);

    if (newCount == 1) {
      this._setWindowStateBusyValue(aWindow, true);
      this._sendWindowStateBusyEvent(aWindow);
    }
  },

  /**
   * Dispatch an SSWindowStateReady event for the given window.
   * @param aWindow the window
   */
  _sendWindowStateReadyEvent: function ssi_sendWindowStateReadyEvent(aWindow) {
    let event = aWindow.document.createEvent("Events");
    event.initEvent("SSWindowStateReady", true, false);
    aWindow.dispatchEvent(event);
  },

  /**
   * Dispatch an SSWindowStateBusy event for the given window.
   * @param aWindow the window
   */
  _sendWindowStateBusyEvent: function ssi_sendWindowStateBusyEvent(aWindow) {
    let event = aWindow.document.createEvent("Events");
    event.initEvent("SSWindowStateBusy", true, false);
    aWindow.dispatchEvent(event);
  },

  /**
   * Dispatch the SSWindowRestoring event for the given window.
   * @param aWindow
   *        The window which is going to be restored
   */
  _sendWindowRestoringNotification(aWindow) {
    let event = aWindow.document.createEvent("Events");
    event.initEvent("SSWindowRestoring", true, false);
    aWindow.dispatchEvent(event);
  },

  /**
   * Dispatch the SSWindowRestored event for the given window.
   * @param aWindow
   *        The window which has been restored
   */
  _sendWindowRestoredNotification(aWindow) {
    let event = aWindow.document.createEvent("Events");
    event.initEvent("SSWindowRestored", true, false);
    aWindow.dispatchEvent(event);
  },

  /**
   * Dispatch the SSTabRestored event for the given tab.
   * @param aTab
   *        The tab which has been restored
   * @param aIsRemotenessUpdate
   *        True if this tab was restored due to flip from running from
   *        out-of-main-process to in-main-process or vice-versa.
   */
  _sendTabRestoredNotification(aTab, aIsRemotenessUpdate) {
    let event = aTab.ownerDocument.createEvent("CustomEvent");
    event.initCustomEvent("SSTabRestored", true, false, {
      isRemotenessUpdate: aIsRemotenessUpdate,
    });
    aTab.dispatchEvent(event);
  },

  /**
   * @param aWindow
   *        Window reference
   * @returns whether this window's data is still cached in _statesToRestore
   *          because it's not fully loaded yet
   */
  _isWindowLoaded: function ssi_isWindowLoaded(aWindow) {
    return !WINDOW_RESTORE_IDS.has(aWindow);
  },

  /**
   * Resize this._closedWindows to the value of the pref, except in the case
   * where we don't have any non-popup windows on Windows and Linux. Then we must
   * resize such that we have at least one non-popup window.
   */
  _capClosedWindows: function ssi_capClosedWindows() {
    if (this._closedWindows.length <= this._max_windows_undo) {
      return;
    }
    let spliceTo = this._max_windows_undo;
    if (AppConstants.platform != "macosx") {
      let normalWindowIndex = 0;
      // try to find a non-popup window in this._closedWindows
      while (
        normalWindowIndex < this._closedWindows.length &&
        !!this._closedWindows[normalWindowIndex].isPopup
      ) {
        normalWindowIndex++;
      }
      if (normalWindowIndex >= this._max_windows_undo) {
        spliceTo = normalWindowIndex + 1;
      }
    }
    if (spliceTo < this._closedWindows.length) {
      this._closedWindows.splice(spliceTo, this._closedWindows.length);
      this._closedObjectsChanged = true;
    }
  },

  /**
   * Clears the set of windows that are "resurrected" before writing to disk to
   * make closing windows one after the other until shutdown work as expected.
   *
   * This function should only be called when we are sure that there has been
   * a user action that indicates the browser is actively being used and all
   * windows that have been closed before are not part of a series of closing
   * windows.
   */
  _clearRestoringWindows: function ssi_clearRestoringWindows() {
    for (let i = 0; i < this._closedWindows.length; i++) {
      delete this._closedWindows[i]._shouldRestore;
    }
  },

  /**
   * Reset state to prepare for a new session state to be restored.
   */
  _resetRestoringState: function ssi_initRestoringState() {
    TabRestoreQueue.reset();
    this._tabsRestoringCount = 0;
  },

  /**
   * Reset the restoring state for a particular tab. This will be called when
   * removing a tab or when a tab needs to be reset (it's being overwritten).
   *
   * @param aTab
   *        The tab that will be "reset"
   */
  _resetLocalTabRestoringState(aTab) {
    let browser = aTab.linkedBrowser;

    // Keep the tab's previous state for later in this method
    let previousState = TAB_STATE_FOR_BROWSER.get(browser);

    if (!previousState) {
      console.error("Given tab is not restoring.");
      return;
    }

    // The browser is no longer in any sort of restoring state.
    TAB_STATE_FOR_BROWSER.delete(browser);

    if (Services.appinfo.sessionHistoryInParent) {
      this._restoreListeners.get(browser.permanentKey)?.unregister();
      browser.browsingContext.clearRestoreState();
    }

    aTab.removeAttribute("pending");

    if (previousState == TAB_STATE_RESTORING) {
      if (this._tabsRestoringCount) {
        this._tabsRestoringCount--;
      }
    } else if (previousState == TAB_STATE_NEEDS_RESTORE) {
      // Make sure that the tab is removed from the list of tabs to restore.
      // Again, this is normally done in restoreTabContent, but that isn't being called
      // for this tab.
      TabRestoreQueue.remove(aTab);
    }
  },

  _resetTabRestoringState(tab) {
    let browser = tab.linkedBrowser;

    if (!TAB_STATE_FOR_BROWSER.has(browser)) {
      console.error("Given tab is not restoring.");
      return;
    }

    if (!Services.appinfo.sessionHistoryInParent) {
      browser.messageManager.sendAsyncMessage("SessionStore:resetRestore", {});
    }
    this._resetLocalTabRestoringState(tab);
  },

  /**
   * Each fresh tab starts out with epoch=0. This function can be used to
   * start a next epoch by incrementing the current value. It will enables us
   * to ignore stale messages sent from previous epochs. The function returns
   * the new epoch ID for the given |browser|.
   */
  startNextEpoch(permanentKey) {
    let next = this.getCurrentEpoch(permanentKey) + 1;
    this._browserEpochs.set(permanentKey, next);
    return next;
  },

  /**
   * Returns the current epoch for the given <browser>. If we haven't assigned
   * a new epoch this will default to zero for new tabs.
   */
  getCurrentEpoch(permanentKey) {
    return this._browserEpochs.get(permanentKey) || 0;
  },

  /**
   * Each time a <browser> element is restored, we increment its "epoch". To
   * check if a message from content-sessionStore.js is out of date, we can
   * compare the epoch received with the message to the <browser> element's
   * epoch. This function does that, and returns true if |epoch| is up-to-date
   * with respect to |browser|.
   */
  isCurrentEpoch(permanentKey, epoch) {
    return this.getCurrentEpoch(permanentKey) == epoch;
  },

  /**
   * Resets the epoch for a given <browser>. We need to this every time we
   * receive a hint that a new docShell has been loaded into the browser as
   * the frame script starts out with epoch=0.
   */
  resetEpoch(permanentKey, frameLoader = null) {
    this._browserEpochs.delete(permanentKey);
    if (frameLoader) {
      frameLoader.requestEpochUpdate(0);
    }
  },

  /**
   * Countdown for a given duration, skipping beats if the computer is too busy,
   * sleeping or otherwise unavailable.
   *
   * @param {number} delay An approximate delay to wait in milliseconds (rounded
   * up to the closest second).
   *
   * @return Promise
   */
  looseTimer(delay) {
    let DELAY_BEAT = 1000;
    let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    let beats = Math.ceil(delay / DELAY_BEAT);
    let deferred = Promise.withResolvers();
    timer.initWithCallback(
      function () {
        if (beats <= 0) {
          deferred.resolve();
        }
        --beats;
      },
      DELAY_BEAT,
      Ci.nsITimer.TYPE_REPEATING_PRECISE_CAN_SKIP
    );
    // Ensure that the timer is both canceled once we are done with it
    // and not garbage-collected until then.
    deferred.promise.then(
      () => timer.cancel(),
      () => timer.cancel()
    );
    return deferred;
  },

  /**
   * Builds a single nsISessionStoreRestoreData tree for the provided |formdata|
   * and |scroll| trees.
   */
  buildRestoreData(formdata, scroll) {
    function addFormEntries(root, fields, isXpath) {
      for (let [key, value] of Object.entries(fields)) {
        switch (typeof value) {
          case "string":
            root.addTextField(isXpath, key, value);
            break;
          case "boolean":
            root.addCheckbox(isXpath, key, value);
            break;
          case "object": {
            if (value === null) {
              break;
            }
            if (
              value.hasOwnProperty("type") &&
              value.hasOwnProperty("fileList")
            ) {
              root.addFileList(isXpath, key, value.type, value.fileList);
              break;
            }
            if (
              value.hasOwnProperty("selectedIndex") &&
              value.hasOwnProperty("value")
            ) {
              root.addSingleSelect(
                isXpath,
                key,
                value.selectedIndex,
                value.value
              );
              break;
            }
            if (
              value.hasOwnProperty("value") &&
              value.hasOwnProperty("state")
            ) {
              root.addCustomElement(isXpath, key, value.value, value.state);
              break;
            }
            if (
              key === "sessionData" &&
              ["about:sessionrestore", "about:welcomeback"].includes(
                formdata.url
              )
            ) {
              root.addTextField(isXpath, key, JSON.stringify(value));
              break;
            }
            if (Array.isArray(value)) {
              root.addMultipleSelect(isXpath, key, value);
              break;
            }
          }
        }
      }
    }

    let root = SessionStoreUtils.constructSessionStoreRestoreData();
    if (scroll?.hasOwnProperty("scroll")) {
      root.scroll = scroll.scroll;
    }
    if (formdata?.hasOwnProperty("url")) {
      root.url = formdata.url;
      if (formdata.hasOwnProperty("innerHTML")) {
        // eslint-disable-next-line no-unsanitized/property
        root.innerHTML = formdata.innerHTML;
      }
      if (formdata.hasOwnProperty("xpath")) {
        addFormEntries(root, formdata.xpath, /* isXpath */ true);
      }
      if (formdata.hasOwnProperty("id")) {
        addFormEntries(root, formdata.id, /* isXpath */ false);
      }
    }
    let childrenLength = Math.max(
      scroll?.children?.length || 0,
      formdata?.children?.length || 0
    );
    for (let i = 0; i < childrenLength; i++) {
      root.addChild(
        this.buildRestoreData(formdata?.children?.[i], scroll?.children?.[i]),
        i
      );
    }
    return root;
  },

  _waitForStateStop(browser, expectedURL = null) {
    const deferred = Promise.withResolvers();

    const listener = {
      unregister(reject = true) {
        if (reject) {
          deferred.reject();
        }

        SessionStoreInternal._restoreListeners.delete(browser.permanentKey);

        try {
          browser.removeProgressListener(
            this,
            Ci.nsIWebProgress.NOTIFY_STATE_WINDOW
          );
        } catch {} // May have already gotten rid of the browser's webProgress.
      },

      onStateChange(webProgress, request, stateFlags, status) {
        if (
          webProgress.isTopLevel &&
          stateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW &&
          stateFlags & Ci.nsIWebProgressListener.STATE_STOP
        ) {
          // FIXME: We sometimes see spurious STATE_STOP events for about:blank
          // loads, so we have to account for that here.
          let aboutBlankOK = !expectedURL || expectedURL === "about:blank";
          let url = request.QueryInterface(Ci.nsIChannel).originalURI.spec;
          if (url !== "about:blank" || aboutBlankOK) {
            this.unregister(false);
            deferred.resolve();
          }
        }
      },

      QueryInterface: ChromeUtils.generateQI([
        "nsIWebProgressListener",
        "nsISupportsWeakReference",
      ]),
    };

    this._restoreListeners.get(browser.permanentKey)?.unregister();
    this._restoreListeners.set(browser.permanentKey, listener);

    browser.addProgressListener(
      listener,
      Ci.nsIWebProgress.NOTIFY_STATE_WINDOW
    );

    return deferred.promise;
  },

  _listenForNavigations(browser, callbacks) {
    const listener = {
      unregister() {
        browser.browsingContext?.sessionHistory?.removeSHistoryListener(this);

        try {
          browser.removeProgressListener(
            this,
            Ci.nsIWebProgress.NOTIFY_STATE_WINDOW
          );
        } catch {} // May have already gotten rid of the browser's webProgress.

        SessionStoreInternal._restoreListeners.delete(browser.permanentKey);
      },

      OnHistoryReload() {
        this.unregister();
        return callbacks.onHistoryReload();
      },

      // TODO(kashav): ContentRestore.sys.mjs handles OnHistoryNewEntry
      // separately, so we should eventually support that here as well.
      OnHistoryNewEntry() {},
      OnHistoryGotoIndex() {},
      OnHistoryPurge() {},
      OnHistoryReplaceEntry() {},

      onStateChange(webProgress, request, stateFlags, status) {
        if (
          webProgress.isTopLevel &&
          stateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW &&
          stateFlags & Ci.nsIWebProgressListener.STATE_START
        ) {
          this.unregister();
          callbacks.onStartRequest();
        }
      },

      QueryInterface: ChromeUtils.generateQI([
        "nsISHistoryListener",
        "nsIWebProgressListener",
        "nsISupportsWeakReference",
      ]),
    };

    this._restoreListeners.get(browser.permanentKey)?.unregister();
    this._restoreListeners.set(browser.permanentKey, listener);

    browser.browsingContext?.sessionHistory?.addSHistoryListener(listener);

    browser.addProgressListener(
      listener,
      Ci.nsIWebProgress.NOTIFY_STATE_WINDOW
    );
  },

  /**
   * This mirrors ContentRestore.restoreHistory() for parent process session
   * history restores.
   */
  _restoreHistory(browser, data) {
    if (!Services.appinfo.sessionHistoryInParent) {
      throw new Error("This function should only be used with SHIP");
    }

    this._tabStateToRestore.set(browser.permanentKey, data);

    // In case about:blank isn't done yet.
    // XXX(kashav): Does this actually accomplish anything? Can we remove?
    browser.stop();

    lazy.SessionHistory.restoreFromParent(
      browser.browsingContext.sessionHistory,
      data.tabData
    );

    let url = data.tabData?.entries[data.tabData.index - 1]?.url;
    let disallow = data.tabData?.disallow;

    let promise = SessionStoreUtils.restoreDocShellState(
      browser.browsingContext,
      url,
      disallow
    );
    this._tabStateRestorePromises.set(browser.permanentKey, promise);

    const onResolve = () => {
      if (TAB_STATE_FOR_BROWSER.get(browser) !== TAB_STATE_RESTORING) {
        this._listenForNavigations(browser, {
          // The history entry was reloaded before we began restoring tab
          // content, just proceed as we would normally.
          onHistoryReload: () => {
            this._restoreTabContent(browser);
            return false;
          },

          // Some foreign code, like an extension, loaded a new URI on the
          // browser. We no longer want to restore saved tab data, but may
          // still have browser state that needs to be restored.
          onStartRequest: () => {
            this._tabStateToRestore.delete(browser.permanentKey);
            this._restoreTabContent(browser);
          },
        });
      }

      this._tabStateRestorePromises.delete(browser.permanentKey);

      this._restoreHistoryComplete(browser, data);
    };

    promise.then(onResolve).catch(() => {});
  },

  /**
   * Either load the saved typed value or restore the active history entry.
   * If neither is possible, just load an empty document.
   */
  _restoreTabEntry(browser, tabData) {
    let haveUserTypedValue = tabData.userTypedValue && tabData.userTypedClear;
    // First take care of the common case where we load the history entry.
    if (!haveUserTypedValue && tabData.entries.length) {
      return SessionStoreUtils.initializeRestore(
        browser.browsingContext,
        this.buildRestoreData(tabData.formdata, tabData.scroll)
      );
    }
    // Here, we need to load user data or about:blank instead.
    // As it's user-typed (or blank), it gets system triggering principal:
    let triggeringPrincipal =
      Services.scriptSecurityManager.getSystemPrincipal();
    // Bypass all the fixup goop for about:blank:
    if (!haveUserTypedValue) {
      let blankPromise = this._waitForStateStop(browser, "about:blank");
      browser.browsingContext.loadURI(lazy.blankURI, {
        triggeringPrincipal,
        loadFlags: Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY,
      });
      return blankPromise;
    }

    // We have a user typed value, load that with fixup:
    let loadPromise = this._waitForStateStop(browser, tabData.userTypedValue);
    browser.browsingContext.fixupAndLoadURIString(tabData.userTypedValue, {
      loadFlags: Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP,
      triggeringPrincipal,
    });

    return loadPromise;
  },

  /**
   * This mirrors ContentRestore.restoreTabContent() for parent process session
   * history restores.
   */
  _restoreTabContent(browser, options = {}) {
    if (!Services.appinfo.sessionHistoryInParent) {
      throw new Error("This function should only be used with SHIP");
    }

    this._restoreListeners.get(browser.permanentKey)?.unregister();

    this._restoreTabContentStarted(browser, options);

    let state = this._tabStateToRestore.get(browser.permanentKey);
    this._tabStateToRestore.delete(browser.permanentKey);

    let promises = [this._tabStateRestorePromises.get(browser.permanentKey)];

    if (state) {
      promises.push(this._restoreTabEntry(browser, state.tabData));
    } else {
      // The browser started another load, so we decided to not restore
      // saved tab data. We should still wait for that new load to finish
      // before proceeding.
      promises.push(this._waitForStateStop(browser));
    }

    Promise.allSettled(promises).then(() => {
      this._restoreTabContentComplete(browser, options);
    });
  },

  _sendRestoreTabContent(browser, options) {
    if (Services.appinfo.sessionHistoryInParent) {
      this._restoreTabContent(browser, options);
    } else {
      browser.messageManager.sendAsyncMessage(
        "SessionStore:restoreTabContent",
        options
      );
    }
  },

  _restoreHistoryComplete(browser, data) {
    let win = browser.ownerGlobal;
    let tab = win?.gBrowser.getTabForBrowser(browser);
    if (!tab) {
      return;
    }

    // Notify the tabbrowser that the tab chrome has been restored.
    let tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab));

    // Update tab label and icon again after the tab history was updated.
    this.updateTabLabelAndIcon(tab, tabData);

    let event = win.document.createEvent("Events");
    event.initEvent("SSTabRestoring", true, false);
    tab.dispatchEvent(event);
  },

  _restoreTabContentStarted(browser, data) {
    let win = browser.ownerGlobal;
    let tab = win?.gBrowser.getTabForBrowser(browser);
    if (!tab) {
      return;
    }

    let initiatedBySessionStore =
      TAB_STATE_FOR_BROWSER.get(browser) != TAB_STATE_NEEDS_RESTORE;
    let isNavigateAndRestore =
      data.reason == RESTORE_TAB_CONTENT_REASON.NAVIGATE_AND_RESTORE;

    // We need to be careful when restoring the urlbar's search mode because
    // we race a call to gURLBar.setURI due to the location change.  setURI
    // will exit search mode and set gURLBar.value to the restored URL,
    // clobbering any search mode and userTypedValue we restore here.  If
    // this is a typical restore -- restoring on startup or restoring a
    // closed tab for example -- then we need to restore search mode after
    // that setURI call, and so we wait until restoreTabContentComplete, at
    // which point setURI will have been called.  If this is not a typical
    // restore -- it was not initiated by session store or it's due to a
    // remoteness change -- then we do not want to restore search mode at
    // all, and so we remove it from the tab state cache.  In particular, if
    // the restore is due to a remoteness change, then the user is loading a
    // new URL and the current search mode should not be carried over to it.
    let cacheState = lazy.TabStateCache.get(browser.permanentKey);
    if (cacheState.searchMode) {
      if (!initiatedBySessionStore || isNavigateAndRestore) {
        lazy.TabStateCache.update(browser.permanentKey, {
          searchMode: null,
          userTypedValue: null,
        });
      }
      return;
    }

    if (!initiatedBySessionStore) {
      // If a load not initiated by sessionstore was started in a
      // previously pending tab. Mark the tab as no longer pending.
      this.markTabAsRestoring(tab);
    } else if (!isNavigateAndRestore) {
      // If the user was typing into the URL bar when we crashed, but hadn't hit
      // enter yet, then we just need to write that value to the URL bar without
      // loading anything. This must happen after the load, as the load will clear
      // userTypedValue.
      //
      // Note that we only want to do that if we're restoring state for reasons
      // _other_ than a navigateAndRestore remoteness-flip, as such a flip
      // implies that the user was navigating.
      let tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab));
      if (
        tabData.userTypedValue &&
        !tabData.userTypedClear &&
        !browser.userTypedValue
      ) {
        browser.userTypedValue = tabData.userTypedValue;
        if (tab.selected) {
          win.gURLBar.setURI();
        }
      }

      // Remove state we don't need any longer.
      lazy.TabStateCache.update(browser.permanentKey, {
        userTypedValue: null,
        userTypedClear: null,
      });
    }
  },

  _restoreTabContentComplete(browser, data) {
    let win = browser.ownerGlobal;
    let tab = browser.ownerGlobal?.gBrowser.getTabForBrowser(browser);
    if (!tab) {
      return;
    }
    // Restore search mode and its search string in userTypedValue, if
    // appropriate.
    let cacheState = lazy.TabStateCache.get(browser.permanentKey);
    if (cacheState.searchMode) {
      win.gURLBar.setSearchMode(cacheState.searchMode, browser);
      browser.userTypedValue = cacheState.userTypedValue;
      if (tab.selected) {
        win.gURLBar.setURI();
      }
      lazy.TabStateCache.update(browser.permanentKey, {
        searchMode: null,
        userTypedValue: null,
      });
    }

    // This callback is used exclusively by tests that want to
    // monitor the progress of network loads.
    if (gDebuggingEnabled) {
      Services.obs.notifyObservers(browser, NOTIFY_TAB_RESTORED);
    }

    SessionStoreInternal._resetLocalTabRestoringState(tab);
    SessionStoreInternal.restoreNextTab();

    this._sendTabRestoredNotification(tab, data.isRemotenessUpdate);

    Services.obs.notifyObservers(null, "sessionstore-one-or-no-tab-restored");
  },

  /**
   * Send the "SessionStore:restoreHistory" message to content, triggering a
   * content restore. This method is intended to be used internally by
   * SessionStore, as it also ensures that permissions are avaliable in the
   * content process before triggering the history restore in the content
   * process.
   *
   * @param browser The browser to transmit the permissions for
   * @param options The options data to send to content.
   */
  _sendRestoreHistory(browser, options) {
    if (options.tabData.storage) {
      SessionStoreUtils.restoreSessionStorageFromParent(
        browser.browsingContext,
        options.tabData.storage
      );
      delete options.tabData.storage;
    }

    if (Services.appinfo.sessionHistoryInParent) {
      this._restoreHistory(browser, options);
    } else {
      browser.messageManager.sendAsyncMessage(
        "SessionStore:restoreHistory",
        options
      );
    }

    if (browser && browser.frameLoader) {
      browser.frameLoader.requestEpochUpdate(options.epoch);
    }
  },

  // Flush out session history state so that it can be used to restore the state
  // into a new process in `finishTabRemotenessChange`.
  //
  // NOTE: This codepath is temporary while the Fission Session History rewrite
  // is in process, and will be removed & replaced once that rewrite is
  // complete. (bug 1645062)
  async prepareToChangeRemoteness(aBrowser) {
    aBrowser.messageManager.sendAsyncMessage(
      "SessionStore:prepareForProcessChange"
    );
    await lazy.TabStateFlusher.flush(aBrowser);
  },

  // Handle finishing the remoteness change for a tab by restoring session
  // history state into it, and resuming the ongoing network load.
  //
  // NOTE: This codepath is temporary while the Fission Session History rewrite
  // is in process, and will be removed & replaced once that rewrite is
  // complete. (bug 1645062)
  finishTabRemotenessChange(aTab, aSwitchId) {
    let window = aTab.ownerGlobal;
    if (!window || !window.__SSi || window.closed) {
      return;
    }

    let tabState = lazy.TabState.clone(aTab, TAB_CUSTOM_VALUES.get(aTab));
    let options = {
      restoreImmediately: true,
      restoreContentReason: RESTORE_TAB_CONTENT_REASON.NAVIGATE_AND_RESTORE,
      isRemotenessUpdate: true,
      loadArguments: {
        redirectLoadSwitchId: aSwitchId,
        // As we're resuming a load which has been redirected from another
        // process, record the history index which is currently being requested.
        // It has to be offset by 1 to get back to native history indices from
        // SessionStore history indicies.
        redirectHistoryIndex: tabState.requestedIndex - 1,
      },
    };

    // Need to reset restoring tabs.
    if (TAB_STATE_FOR_BROWSER.has(aTab.linkedBrowser)) {
      this._resetLocalTabRestoringState(aTab);
    }

    // Restore the state into the tab.
    this.restoreTab(aTab, tabState, options);
  },
};

/**
 * Priority queue that keeps track of a list of tabs to restore and returns
 * the tab we should restore next, based on priority rules. We decide between
 * pinned, visible and hidden tabs in that and FIFO order. Hidden tabs are only
 * restored with restore_hidden_tabs=true.
 */
var TabRestoreQueue = {
  // The separate buckets used to store tabs.
  tabs: { priority: [], visible: [], hidden: [] },

  // Preferences used by the TabRestoreQueue to determine which tabs
  // are restored automatically and which tabs will be on-demand.
  prefs: {
    // Lazy getter that returns whether tabs are restored on demand.
    get restoreOnDemand() {
      let updateValue = () => {
        let value = Services.prefs.getBoolPref(PREF);
        let definition = { value, configurable: true };
        Object.defineProperty(this, "restoreOnDemand", definition);
        return value;
      };

      const PREF = "browser.sessionstore.restore_on_demand";
      Services.prefs.addObserver(PREF, updateValue);
      return updateValue();
    },

    // Lazy getter that returns whether pinned tabs are restored on demand.
    get restorePinnedTabsOnDemand() {
      let updateValue = () => {
        let value = Services.prefs.getBoolPref(PREF);
        let definition = { value, configurable: true };
        Object.defineProperty(this, "restorePinnedTabsOnDemand", definition);
        return value;
      };

      const PREF = "browser.sessionstore.restore_pinned_tabs_on_demand";
      Services.prefs.addObserver(PREF, updateValue);
      return updateValue();
    },

    // Lazy getter that returns whether we should restore hidden tabs.
    get restoreHiddenTabs() {
      let updateValue = () => {
        let value = Services.prefs.getBoolPref(PREF);
        let definition = { value, configurable: true };
        Object.defineProperty(this, "restoreHiddenTabs", definition);
        return value;
      };

      const PREF = "browser.sessionstore.restore_hidden_tabs";
      Services.prefs.addObserver(PREF, updateValue);
      return updateValue();
    },
  },

  // Resets the queue and removes all tabs.
  reset() {
    this.tabs = { priority: [], visible: [], hidden: [] };
  },

  // Adds a tab to the queue and determines its priority bucket.
  add(tab) {
    let { priority, hidden, visible } = this.tabs;

    if (tab.pinned) {
      priority.push(tab);
    } else if (tab.hidden) {
      hidden.push(tab);
    } else {
      visible.push(tab);
    }
  },

  // Removes a given tab from the queue, if it's in there.
  remove(tab) {
    let { priority, hidden, visible } = this.tabs;

    // We'll always check priority first since we don't
    // have an indicator if a tab will be there or not.
    let set = priority;
    let index = set.indexOf(tab);

    if (index == -1) {
      set = tab.hidden ? hidden : visible;
      index = set.indexOf(tab);
    }

    if (index > -1) {
      set.splice(index, 1);
    }
  },

  // Returns and removes the tab with the highest priority.
  shift() {
    let set;
    let { priority, hidden, visible } = this.tabs;

    let { restoreOnDemand, restorePinnedTabsOnDemand } = this.prefs;
    let restorePinned = !(restoreOnDemand && restorePinnedTabsOnDemand);
    if (restorePinned && priority.length) {
      set = priority;
    } else if (!restoreOnDemand) {
      if (visible.length) {
        set = visible;
      } else if (this.prefs.restoreHiddenTabs && hidden.length) {
        set = hidden;
      }
    }

    return set && set.shift();
  },

  // Moves a given tab from the 'hidden' to the 'visible' bucket.
  hiddenToVisible(tab) {
    let { hidden, visible } = this.tabs;
    let index = hidden.indexOf(tab);

    if (index > -1) {
      hidden.splice(index, 1);
      visible.push(tab);
    }
  },

  // Moves a given tab from the 'visible' to the 'hidden' bucket.
  visibleToHidden(tab) {
    let { visible, hidden } = this.tabs;
    let index = visible.indexOf(tab);

    if (index > -1) {
      visible.splice(index, 1);
      hidden.push(tab);
    }
  },

  /**
   * Returns true if the passed tab is in one of the sets that we're
   * restoring content in automatically.
   *
   * @param tab (<xul:tab>)
   *        The tab to check
   * @returns bool
   */
  willRestoreSoon(tab) {
    let { priority, hidden, visible } = this.tabs;
    let { restoreOnDemand, restorePinnedTabsOnDemand, restoreHiddenTabs } =
      this.prefs;
    let restorePinned = !(restoreOnDemand && restorePinnedTabsOnDemand);
    let candidateSet = [];

    if (restorePinned && priority.length) {
      candidateSet.push(...priority);
    }

    if (!restoreOnDemand) {
      if (visible.length) {
        candidateSet.push(...visible);
      }

      if (restoreHiddenTabs && hidden.length) {
        candidateSet.push(...hidden);
      }
    }

    return candidateSet.indexOf(tab) > -1;
  },
};

// A map storing a closed window's state data until it goes aways (is GC'ed).
// This ensures that API clients can still read (but not write) states of
// windows they still hold a reference to but we don't.
var DyingWindowCache = {
  _data: new WeakMap(),

  has(window) {
    return this._data.has(window);
  },

  get(window) {
    return this._data.get(window);
  },

  set(window, data) {
    this._data.set(window, data);
  },

  remove(window) {
    this._data.delete(window);
  },
};

// A weak set of dirty windows. We use it to determine which windows we need to
// recollect data for when getCurrentState() is called.
var DirtyWindows = {
  _data: new WeakMap(),

  has(window) {
    return this._data.has(window);
  },

  add(window) {
    return this._data.set(window, true);
  },

  remove(window) {
    this._data.delete(window);
  },

  clear(window) {
    this._data = new WeakMap();
  },
};

// The state from the previous session (after restoring pinned tabs). This
// state is persisted and passed through to the next session during an app
// restart to make the third party add-on warning not trash the deferred
// session
var LastSession = {
  _state: null,

  get canRestore() {
    return !!this._state;
  },

  getState() {
    return this._state;
  },

  setState(state) {
    this._state = state;
  },

  clear(silent = false) {
    if (this._state) {
      this._state = null;
      if (!silent) {
        Services.obs.notifyObservers(null, NOTIFY_LAST_SESSION_CLEARED);
      }
    }
  },
};

// Exposed for tests
export const _LastSession = LastSession;