summaryrefslogtreecommitdiffstats
path: root/devtools/client/framework/toolbox.js
blob: a03360aa26ee3d4c25bf4c06f17b955738aa52dd (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
/* 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/. */

"use strict";

const MAX_ORDINAL = 99;
const SPLITCONSOLE_ENABLED_PREF = "devtools.toolbox.splitconsoleEnabled";
const SPLITCONSOLE_HEIGHT_PREF = "devtools.toolbox.splitconsoleHeight";
const DEVTOOLS_ALWAYS_ON_TOP = "devtools.toolbox.alwaysOnTop";
const DISABLE_AUTOHIDE_PREF = "ui.popup.disable_autohide";
const PSEUDO_LOCALE_PREF = "intl.l10n.pseudo";
const HOST_HISTOGRAM = "DEVTOOLS_TOOLBOX_HOST";
const CURRENT_THEME_SCALAR = "devtools.current_theme";
const HTML_NS = "http://www.w3.org/1999/xhtml";
const REGEX_4XX_5XX = /^[4,5]\d\d$/;

const BROWSERTOOLBOX_SCOPE_PREF = "devtools.browsertoolbox.scope";
const BROWSERTOOLBOX_SCOPE_EVERYTHING = "everything";
const BROWSERTOOLBOX_SCOPE_PARENTPROCESS = "parent-process";

const { debounce } = require("resource://devtools/shared/debounce.js");
const { throttle } = require("resource://devtools/shared/throttle.js");
const {
  safeAsyncMethod,
} = require("resource://devtools/shared/async-utils.js");
var { gDevTools } = require("resource://devtools/client/framework/devtools.js");
var EventEmitter = require("resource://devtools/shared/event-emitter.js");
const Selection = require("resource://devtools/client/framework/selection.js");
var Telemetry = require("resource://devtools/client/shared/telemetry.js");
const {
  getUnicodeUrl,
} = require("resource://devtools/client/shared/unicode-url.js");
var { DOMHelpers } = require("resource://devtools/shared/dom-helpers.js");
const { KeyCodes } = require("resource://devtools/client/shared/keycodes.js");
const {
  FluentL10n,
} = require("resource://devtools/client/shared/fluent-l10n/fluent-l10n.js");

var Startup = Cc["@mozilla.org/devtools/startup-clh;1"].getService(
  Ci.nsISupports
).wrappedJSObject;

const { BrowserLoader } = ChromeUtils.import(
  "resource://devtools/shared/loader/browser-loader.js"
);

const {
  MultiLocalizationHelper,
} = require("resource://devtools/shared/l10n.js");
const L10N = new MultiLocalizationHelper(
  "devtools/client/locales/toolbox.properties",
  "chrome://branding/locale/brand.properties"
);

loader.lazyRequireGetter(
  this,
  "registerStoreObserver",
  "resource://devtools/client/shared/redux/subscriber.js",
  true
);
loader.lazyRequireGetter(
  this,
  "createToolboxStore",
  "resource://devtools/client/framework/store.js",
  true
);
loader.lazyRequireGetter(
  this,
  ["registerWalkerListeners", "removeTarget"],
  "resource://devtools/client/framework/actions/index.js",
  true
);
loader.lazyRequireGetter(
  this,
  ["selectTarget"],
  "resource://devtools/shared/commands/target/actions/targets.js",
  true
);

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  AppConstants: "resource://gre/modules/AppConstants.sys.mjs",
});
loader.lazyRequireGetter(this, "flags", "resource://devtools/shared/flags.js");
loader.lazyRequireGetter(
  this,
  "KeyShortcuts",
  "resource://devtools/client/shared/key-shortcuts.js"
);
loader.lazyRequireGetter(
  this,
  "ZoomKeys",
  "resource://devtools/client/shared/zoom-keys.js"
);
loader.lazyRequireGetter(
  this,
  "ToolboxButtons",
  "resource://devtools/client/definitions.js",
  true
);
loader.lazyRequireGetter(
  this,
  "SourceMapURLService",
  "resource://devtools/client/framework/source-map-url-service.js",
  true
);
loader.lazyRequireGetter(
  this,
  "BrowserConsoleManager",
  "resource://devtools/client/webconsole/browser-console-manager.js",
  true
);
loader.lazyRequireGetter(
  this,
  "viewSource",
  "resource://devtools/client/shared/view-source.js"
);
loader.lazyRequireGetter(
  this,
  "buildHarLog",
  "resource://devtools/client/netmonitor/src/har/har-builder-utils.js",
  true
);
loader.lazyRequireGetter(
  this,
  "NetMonitorAPI",
  "resource://devtools/client/netmonitor/src/api.js",
  true
);
loader.lazyRequireGetter(
  this,
  "sortPanelDefinitions",
  "resource://devtools/client/framework/toolbox-tabs-order-manager.js",
  true
);
loader.lazyRequireGetter(
  this,
  "createEditContextMenu",
  "resource://devtools/client/framework/toolbox-context-menu.js",
  true
);
loader.lazyRequireGetter(
  this,
  "getSelectedTarget",
  "resource://devtools/shared/commands/target/selectors/targets.js",
  true
);
loader.lazyRequireGetter(
  this,
  "remoteClientManager",
  "resource://devtools/client/shared/remote-debugging/remote-client-manager.js",
  true
);
loader.lazyRequireGetter(
  this,
  "ResponsiveUIManager",
  "resource://devtools/client/responsive/manager.js"
);
loader.lazyRequireGetter(
  this,
  "DevToolsUtils",
  "resource://devtools/shared/DevToolsUtils.js"
);
loader.lazyRequireGetter(
  this,
  "NodePicker",
  "resource://devtools/client/inspector/node-picker.js"
);

loader.lazyGetter(this, "domNodeConstants", () => {
  return require("resource://devtools/shared/dom-node-constants.js");
});

loader.lazyRequireGetter(
  this,
  "NodeFront",
  "resource://devtools/client/fronts/node.js",
  true
);

loader.lazyRequireGetter(
  this,
  "PICKER_TYPES",
  "resource://devtools/shared/picker-constants.js"
);

loader.lazyRequireGetter(
  this,
  "HarAutomation",
  "resource://devtools/client/netmonitor/src/har/har-automation.js",
  true
);

loader.lazyRequireGetter(
  this,
  "getThreadOptions",
  "resource://devtools/client/shared/thread-utils.js",
  true
);
loader.lazyRequireGetter(
  this,
  "SourceMapLoader",
  "resource://devtools/client/shared/source-map-loader/index.js",
  true
);
loader.lazyRequireGetter(
  this,
  "openProfilerTab",
  "resource://devtools/client/performance-new/shared/browser.js",
  true
);
loader.lazyGetter(this, "ProfilerBackground", () => {
  return ChromeUtils.importESModule(
    "resource://devtools/client/performance-new/shared/background.sys.mjs"
  );
});

const BOOLEAN_CONFIGURATION_PREFS = {
  "devtools.cache.disabled": {
    name: "cacheDisabled",
  },
  "devtools.custom-formatters.enabled": {
    name: "customFormatters",
  },
  "devtools.serviceWorkers.testing.enabled": {
    name: "serviceWorkersTestingEnabled",
  },
  "devtools.inspector.simple-highlighters-reduced-motion": {
    name: "useSimpleHighlightersForReducedMotion",
  },
  "devtools.debugger.features.overlay": {
    name: "pauseOverlay",
    thread: true,
  },
};

/**
 * A "Toolbox" is the component that holds all the tools for one specific
 * target. Visually, it's a document that includes the tools tabs and all
 * the iframes where the tool panels will be living in.
 *
 * @param {object} commands
 *        The context to inspect identified by this commands.
 * @param {string} selectedTool
 *        Tool to select initially
 * @param {Toolbox.HostType} hostType
 *        Type of host that will host the toolbox (e.g. sidebar, window)
 * @param {DOMWindow} contentWindow
 *        The window object of the toolbox document
 * @param {string} frameId
 *        A unique identifier to differentiate toolbox documents from the
 *        chrome codebase when passing DOM messages
 */
function Toolbox(commands, selectedTool, hostType, contentWindow, frameId) {
  this._win = contentWindow;
  this.frameId = frameId;
  this.selection = new Selection();
  this.telemetry = new Telemetry({ useSessionId: true });
  // This attribute helps identify one particular toolbox instance.
  this.sessionId = this.telemetry.sessionId;

  // This attribute is meant to be a public attribute on the Toolbox object
  // It exposes commands modules listed in devtools/shared/commands/index.js
  // which are an abstraction on top of RDP methods.
  // See devtools/shared/commands/README.md
  this.commands = commands;
  this._descriptorFront = commands.descriptorFront;

  // Map of the available DevTools WebExtensions:
  //   Map<extensionUUID, extensionName>
  this._webExtensions = new Map();

  this._toolPanels = new Map();
  this._inspectorExtensionSidebars = new Map();

  this._netMonitorAPI = null;

  // Map of frames (id => frame-info) and currently selected frame id.
  this.frameMap = new Map();
  this.selectedFrameId = null;

  // Number of targets currently paused
  this._pausedTargets = 0;

  /**
   * KeyShortcuts instance specific to WINDOW host type.
   * This is the key shortcuts that are only register when the toolbox
   * is loaded in its own window. Otherwise, these shortcuts are typically
   * registered by devtools-startup.js module.
   */
  this._windowHostShortcuts = null;

  this._toolRegistered = this._toolRegistered.bind(this);
  this._toolUnregistered = this._toolUnregistered.bind(this);
  this._refreshHostTitle = this._refreshHostTitle.bind(this);
  this.toggleNoAutohide = this.toggleNoAutohide.bind(this);
  this.toggleAlwaysOnTop = this.toggleAlwaysOnTop.bind(this);
  this.disablePseudoLocale = () => this.changePseudoLocale("none");
  this.enableAccentedPseudoLocale = () => this.changePseudoLocale("accented");
  this.enableBidiPseudoLocale = () => this.changePseudoLocale("bidi");
  this._updateFrames = this._updateFrames.bind(this);
  this._splitConsoleOnKeypress = this._splitConsoleOnKeypress.bind(this);
  this.closeToolbox = this.closeToolbox.bind(this);
  this.destroy = this.destroy.bind(this);
  this._saveSplitConsoleHeight = this._saveSplitConsoleHeight.bind(this);
  this._onFocus = this._onFocus.bind(this);
  this._onBlur = this._onBlur.bind(this);
  this._onBrowserMessage = this._onBrowserMessage.bind(this);
  this._onTabsOrderUpdated = this._onTabsOrderUpdated.bind(this);
  this._onToolbarFocus = this._onToolbarFocus.bind(this);
  this._onToolbarArrowKeypress = this._onToolbarArrowKeypress.bind(this);
  this._onPickerClick = this._onPickerClick.bind(this);
  this._onPickerKeypress = this._onPickerKeypress.bind(this);
  this._onPickerStarting = this._onPickerStarting.bind(this);
  this._onPickerStarted = this._onPickerStarted.bind(this);
  this._onPickerStopped = this._onPickerStopped.bind(this);
  this._onPickerCanceled = this._onPickerCanceled.bind(this);
  this._onPickerPicked = this._onPickerPicked.bind(this);
  this._onPickerPreviewed = this._onPickerPreviewed.bind(this);
  this._onInspectObject = this._onInspectObject.bind(this);
  this._onNewSelectedNodeFront = this._onNewSelectedNodeFront.bind(this);
  this._onToolSelected = this._onToolSelected.bind(this);
  this._onContextMenu = this._onContextMenu.bind(this);
  this._onMouseDown = this._onMouseDown.bind(this);
  this.updateToolboxButtonsVisibility =
    this.updateToolboxButtonsVisibility.bind(this);
  this.updateToolboxButtons = this.updateToolboxButtons.bind(this);
  this.selectTool = this.selectTool.bind(this);
  this._pingTelemetrySelectTool = this._pingTelemetrySelectTool.bind(this);
  this.toggleSplitConsole = this.toggleSplitConsole.bind(this);
  this.toggleOptions = this.toggleOptions.bind(this);
  this._onTargetAvailable = this._onTargetAvailable.bind(this);
  this._onTargetDestroyed = this._onTargetDestroyed.bind(this);
  this._onTargetSelected = this._onTargetSelected.bind(this);
  this._onResourceAvailable = this._onResourceAvailable.bind(this);
  this._onResourceUpdated = this._onResourceUpdated.bind(this);
  this._onToolSelectedStopPicker = this._onToolSelectedStopPicker.bind(this);

  // `component` might be null if the toolbox was destroying during the throttling
  this._throttledSetToolboxButtons = throttle(
    () => this.component?.setToolboxButtons(this.toolbarButtons),
    500,
    this
  );

  this._debounceUpdateFocusedState = debounce(
    () => {
      this.component?.setFocusedState(this._isToolboxFocused);
    },
    500,
    this
  );

  if (!selectedTool) {
    selectedTool = Services.prefs.getCharPref(this._prefs.LAST_TOOL);
  }
  this._defaultToolId = selectedTool;

  this._hostType = hostType;

  this.isOpen = new Promise(
    function (resolve) {
      this._resolveIsOpen = resolve;
    }.bind(this)
  );

  EventEmitter.decorate(this);

  this.on("host-changed", this._refreshHostTitle);
  this.on("select", this._onToolSelected);

  this.selection.on("new-node-front", this._onNewSelectedNodeFront);

  gDevTools.on("tool-registered", this._toolRegistered);
  gDevTools.on("tool-unregistered", this._toolUnregistered);

  /**
   * Get text direction for the current locale direction.
   *
   * `getComputedStyle` forces a synchronous reflow, so use a lazy getter in order to
   * call it only once.
   */
  loader.lazyGetter(this, "direction", () => {
    const { documentElement } = this.doc;
    const isRtl =
      this.win.getComputedStyle(documentElement).direction === "rtl";
    return isRtl ? "rtl" : "ltr";
  });
}
exports.Toolbox = Toolbox;

/**
 * The toolbox can be 'hosted' either embedded in a browser window
 * or in a separate window.
 */
Toolbox.HostType = {
  BOTTOM: "bottom",
  RIGHT: "right",
  LEFT: "left",
  WINDOW: "window",
  BROWSERTOOLBOX: "browsertoolbox",
  // This is typically used by `about:debugging`, when opening toolbox in a new tab,
  // via `about:devtools-toolbox` URLs.
  PAGE: "page",
};

Toolbox.prototype = {
  _URL: "about:devtools-toolbox",

  _prefs: {
    LAST_TOOL: "devtools.toolbox.selectedTool",
  },

  get nodePicker() {
    if (!this._nodePicker) {
      this._nodePicker = new NodePicker(this.commands, this.selection);
      this._nodePicker.on("picker-starting", this._onPickerStarting);
      this._nodePicker.on("picker-started", this._onPickerStarted);
      this._nodePicker.on("picker-stopped", this._onPickerStopped);
      this._nodePicker.on("picker-node-canceled", this._onPickerCanceled);
      this._nodePicker.on("picker-node-picked", this._onPickerPicked);
      this._nodePicker.on("picker-node-previewed", this._onPickerPreviewed);
    }

    return this._nodePicker;
  },

  get store() {
    if (!this._store) {
      this._store = createToolboxStore();
    }
    return this._store;
  },

  get currentToolId() {
    return this._currentToolId;
  },

  set currentToolId(id) {
    this._currentToolId = id;
    this.component.setCurrentToolId(id);
  },

  get defaultToolId() {
    return this._defaultToolId;
  },

  get panelDefinitions() {
    return this._panelDefinitions;
  },

  set panelDefinitions(definitions) {
    this._panelDefinitions = definitions;
    this._combineAndSortPanelDefinitions();
  },

  get visibleAdditionalTools() {
    if (!this._visibleAdditionalTools) {
      this._visibleAdditionalTools = [];
    }

    return this._visibleAdditionalTools;
  },

  set visibleAdditionalTools(tools) {
    this._visibleAdditionalTools = tools;
    if (this.isReady) {
      this._combineAndSortPanelDefinitions();
    }
  },

  /**
   * Combines the built-in panel definitions and the additional tool definitions that
   * can be set by add-ons.
   */
  _combineAndSortPanelDefinitions() {
    let definitions = [
      ...this._panelDefinitions,
      ...this.getVisibleAdditionalTools(),
    ];
    definitions = sortPanelDefinitions(definitions);
    this.component.setPanelDefinitions(definitions);
  },

  lastUsedToolId: null,

  /**
   * Returns a *copy* of the _toolPanels collection.
   *
   * @return {Map} panels
   *         All the running panels in the toolbox
   */
  getToolPanels() {
    return new Map(this._toolPanels);
  },

  /**
   * Access the panel for a given tool
   */
  getPanel(id) {
    return this._toolPanels.get(id);
  },

  /**
   * Get the panel instance for a given tool once it is ready.
   * If the tool is already opened, the promise will resolve immediately,
   * otherwise it will wait until the tool has been opened before resolving.
   *
   * Note that this does not open the tool, use selectTool if you'd
   * like to select the tool right away.
   *
   * @param  {String} id
   *         The id of the panel, for example "jsdebugger".
   * @returns Promise
   *          A promise that resolves once the panel is ready.
   */
  getPanelWhenReady(id) {
    const panel = this.getPanel(id);
    return new Promise(resolve => {
      if (panel) {
        resolve(panel);
      } else {
        this.on(id + "-ready", initializedPanel => {
          resolve(initializedPanel);
        });
      }
    });
  },

  /**
   * This is a shortcut for getPanel(currentToolId) because it is much more
   * likely that we're going to want to get the panel that we've just made
   * visible
   */
  getCurrentPanel() {
    return this._toolPanels.get(this.currentToolId);
  },

  /**
   * Get the current top level target the toolbox is debugging.
   *
   * This will only be defined *after* calling Toolbox.open(),
   * after it has called `targetCommands.startListening`.
   */
  get target() {
    return this.commands.targetCommand.targetFront;
  },

  get threadFront() {
    return this.commands.targetCommand.targetFront.threadFront;
  },

  /**
   * Get/alter the host of a Toolbox, i.e. is it in browser or in a separate
   * tab. See HostType for more details.
   */
  get hostType() {
    return this._hostType;
  },

  /**
   * Shortcut to the window containing the toolbox UI
   */
  get win() {
    return this._win;
  },

  /**
   * When the toolbox is loaded in a frame with type="content", win.parent will not return
   * the parent Chrome window. This getter should return the parent Chrome window
   * regardless of the frame type. See Bug 1539979.
   */
  get topWindow() {
    return DevToolsUtils.getTopWindow(this.win);
  },

  get topDoc() {
    return this.topWindow.document;
  },

  /**
   * Shortcut to the document containing the toolbox UI
   */
  get doc() {
    return this.win.document;
  },

  /**
   * Get the toggled state of the split console
   */
  get splitConsole() {
    return this._splitConsole;
  },

  /**
   * Get the focused state of the split console
   */
  isSplitConsoleFocused() {
    if (!this._splitConsole) {
      return false;
    }
    const focusedWin = Services.focus.focusedWindow;
    return (
      focusedWin &&
      focusedWin ===
        this.doc.querySelector("#toolbox-panel-iframe-webconsole").contentWindow
    );
  },

  get isBrowserToolbox() {
    return this.hostType === Toolbox.HostType.BROWSERTOOLBOX;
  },

  get isMultiProcessBrowserToolbox() {
    return this.isBrowserToolbox;
  },

  /**
   * Set a given target as selected (which may impact the console evaluation context selector).
   *
   * @param {String} targetActorID: The actorID of the target we want to select.
   */
  selectTarget(targetActorID) {
    if (this.getSelectedTargetFront()?.actorID !== targetActorID) {
      // The selected target is managed by the TargetCommand's store.
      // So dispatch this action against that other store.
      this.commands.targetCommand.store.dispatch(selectTarget(targetActorID));
    }
  },

  /**
   * @returns {ThreadFront|null} The selected thread front, or null if there is none.
   */
  getSelectedTargetFront() {
    // The selected target is managed by the TargetCommand's store.
    // So pull the state from that other store.
    const selectedTarget = getSelectedTarget(
      this.commands.targetCommand.store.getState()
    );
    if (!selectedTarget) {
      return null;
    }

    return this.commands.client.getFrontByID(selectedTarget.actorID);
  },

  /**
   * For now, the debugger isn't hooked to TargetCommand's store
   * to display its thread list. So manually forward target selection change
   * to the debugger via a dedicated action
   */
  _onTargetCommandStateChange(state, oldState) {
    if (getSelectedTarget(state) !== getSelectedTarget(oldState)) {
      const dbg = this.getPanel("jsdebugger");
      if (!dbg) {
        return;
      }

      const threadActorID = getSelectedTarget(state)?.threadFront?.actorID;
      if (!threadActorID) {
        return;
      }

      dbg.selectThread(threadActorID);
    }
  },

  /**
   * Called on each new THREAD_STATE resource
   *
   * @param {Object} resource The THREAD_STATE resource
   */
  _onThreadStateChanged(resource) {
    if (resource.state == "paused") {
      this._pauseToolbox(resource.why.type);
    } else if (resource.state == "resumed") {
      this._resumeToolbox();
    }
  },

  /**
   * Called on each new JSTRACER_STATE resource
   *
   * @param {Object} resource The JSTRACER_STATE resource
   */
  async _onTracingStateChanged(resource) {
    const { profile } = resource;
    if (!profile) {
      return;
    }
    const browser = await openProfilerTab();

    const profileCaptureResult = {
      type: "SUCCESS",
      profile,
    };
    ProfilerBackground.registerProfileCaptureForBrowser(
      browser,
      profileCaptureResult,
      null
    );
  },

  /**
   * Be careful, this method is synchronous, but highlightTool, raise, selectTool
   * are all async.
   */
  _pauseToolbox(reason) {
    // Suppress interrupted events by default because the thread is
    // paused/resumed a lot for various actions.
    if (reason === "interrupted") {
      return;
    }

    this.highlightTool("jsdebugger");

    if (
      reason === "debuggerStatement" ||
      reason === "mutationBreakpoint" ||
      reason === "eventBreakpoint" ||
      reason === "breakpoint" ||
      reason === "exception" ||
      reason === "resumeLimit" ||
      reason === "XHR" ||
      reason === "breakpointConditionThrown"
    ) {
      this.raise();
      this.selectTool("jsdebugger", reason);
      // Each Target/Thread can be paused only once at a time,
      // so, for each pause, we should have a related resumed event.
      // But we may have multiple targets paused at the same time
      this._pausedTargets++;
      this.emit("toolbox-paused");
    }
  },

  _resumeToolbox() {
    if (this.isHighlighted("jsdebugger")) {
      this._pausedTargets--;
      if (this._pausedTargets == 0) {
        this.emit("toolbox-resumed");
        this.unhighlightTool("jsdebugger");
      }
    }
  },

  /**
   * This method will be called for the top-level target, as well as any potential
   * additional targets we may care about.
   */
  async _onTargetAvailable({ targetFront, isTargetSwitching }) {
    if (targetFront.isTopLevel) {
      // Attach to a new top-level target.
      // For now, register these event listeners only on the top level target
      if (!targetFront.targetForm.ignoreSubFrames) {
        targetFront.on("frame-update", this._updateFrames);
      }
      const consoleFront = await targetFront.getFront("console");
      consoleFront.on("inspectObject", this._onInspectObject);
    }

    // Walker listeners allow to monitor DOM Mutation breakpoint updates.
    // All targets should be monitored.
    targetFront.watchFronts("inspector", async inspectorFront => {
      registerWalkerListeners(this.store, inspectorFront.walker);
    });

    if (targetFront.isTopLevel && isTargetSwitching) {
      // These methods expect the target to be attached, which is guaranteed by the time
      // _onTargetAvailable is called by the targetCommand.
      await this._listFrames();
      // The target may have been destroyed while calling _listFrames if we navigate quickly
      if (targetFront.isDestroyed()) {
        return;
      }
    }

    if (targetFront.targetForm.ignoreSubFrames) {
      this._updateFrames({
        frames: [
          {
            id: targetFront.actorID,
            targetFront,
            url: targetFront.url,
            title: targetFront.title,
            isTopLevel: targetFront.isTopLevel,
          },
        ],
      });
    }

    // If a new popup is debugged, automagically switch the toolbox to become
    // an independant window so that we can easily keep debugging the new tab.
    // Only do that if that's not the current top level, otherwise it means
    // we opened a toolbox dedicated to the popup.
    if (
      targetFront.targetForm.isPopup &&
      !targetFront.isTopLevel &&
      this._descriptorFront.isLocalTab
    ) {
      await this.switchHostToTab(targetFront.targetForm.browsingContextID);
    }
  },

  async _onTargetSelected({ targetFront }) {
    this._updateFrames({ selected: targetFront.actorID });
    this.selectTarget(targetFront.actorID);
  },

  _onTargetDestroyed({ targetFront }) {
    removeTarget(this.store, targetFront);

    if (targetFront.isTopLevel) {
      const consoleFront = targetFront.getCachedFront("console");
      // If the target has already been destroyed, its console front will
      // also already be destroyed and so we won't be able to retrieve it.
      // Nor is it important to clear its listener as fronts automatically clears
      // all their listeners on destroy.
      if (consoleFront) {
        consoleFront.off("inspectObject", this._onInspectObject);
      }
      targetFront.off("frame-update", this._updateFrames);
    } else if (this.selection) {
      this.selection.onTargetDestroyed(targetFront);
    }

    // When navigating the old (top level) target can get destroyed before the thread state changed
    // event for the target is received, so it gets lost. This currently happens with bf-cache
    // navigations when paused, so lets make sure we resumed if not.
    //
    // We should also resume if a paused non-top-level target is destroyed
    if (targetFront.isTopLevel || targetFront.threadFront?.paused) {
      this._resumeToolbox();
    }

    if (targetFront.targetForm.ignoreSubFrames) {
      this._updateFrames({
        frames: [
          {
            id: targetFront.actorID,
            destroy: true,
          },
        ],
      });
    }
  },

  _onTargetThreadFrontResumeWrongOrder() {
    const box = this.getNotificationBox();
    box.appendNotification(
      L10N.getStr("toolbox.resumeOrderWarning"),
      "wrong-resume-order",
      "",
      box.PRIORITY_WARNING_HIGH
    );
  },

  /**
   * Open the toolbox
   */
  open() {
    return async function () {
      // Kick off async loading the Fluent bundles.
      const fluentL10n = new FluentL10n();
      const fluentInitPromise = fluentL10n.init([
        "devtools/client/toolbox.ftl",
      ]);

      const isToolboxURL = this.win.location.href.startsWith(this._URL);
      if (isToolboxURL) {
        // Update the URL so that onceDOMReady watch for the right url.
        this._URL = this.win.location.href;
      }

      const domReady = new Promise(resolve => {
        DOMHelpers.onceDOMReady(
          this.win,
          () => {
            resolve();
          },
          this._URL
        );
      });

      this.commands.targetCommand.on(
        "target-thread-wrong-order-on-resume",
        this._onTargetThreadFrontResumeWrongOrder.bind(this)
      );
      registerStoreObserver(
        this.commands.targetCommand.store,
        this._onTargetCommandStateChange.bind(this)
      );

      // Bug 1709063: Use commands.resourceCommand instead of toolbox.resourceCommand
      this.resourceCommand = this.commands.resourceCommand;

      // Optimization: fire up a few other things before waiting on
      // the iframe being ready (makes startup faster)
      await this.commands.targetCommand.startListening();

      // Transfer settings early, before watching resources as it may impact them.
      // (this is the case for custom formatter pref and console messages)
      await this._listenAndApplyConfigurationPref();

      // The targetCommand is created right before this code.
      // It means that this call to watchTargets is the first,
      // and we are registering the first target listener, which means
      // Toolbox._onTargetAvailable will be called first, before any other
      // onTargetAvailable listener that might be registered on targetCommand.
      await this.commands.targetCommand.watchTargets({
        types: this.commands.targetCommand.ALL_TYPES,
        onAvailable: this._onTargetAvailable,
        onSelected: this._onTargetSelected,
        onDestroyed: this._onTargetDestroyed,
      });

      const watchedResources = [
        // Watch for console API messages, errors and network events in order to populate
        // the error count icon in the toolbox.
        this.resourceCommand.TYPES.CONSOLE_MESSAGE,
        this.resourceCommand.TYPES.ERROR_MESSAGE,
        this.resourceCommand.TYPES.DOCUMENT_EVENT,
        this.resourceCommand.TYPES.THREAD_STATE,
      ];

      let tracerInitialization;
      if (
        Services.prefs.getBoolPref(
          "devtools.debugger.features.javascript-tracing",
          false
        )
      ) {
        watchedResources.push(this.resourceCommand.TYPES.JSTRACER_STATE);
        tracerInitialization = this.commands.tracerCommand.initialize();
      }

      if (!this.isBrowserToolbox) {
        // Independently of watching network event resources for the error count icon,
        // we need to start tracking network activity on toolbox open for targets such
        // as tabs, in order to ensure there is always at least one listener existing
        // for network events across the lifetime of the various panels, so stopping
        // the resource command from clearing out its cache of network event resources.
        watchedResources.push(this.resourceCommand.TYPES.NETWORK_EVENT);
      }

      const onResourcesWatched = this.resourceCommand.watchResources(
        watchedResources,
        {
          onAvailable: this._onResourceAvailable,
          onUpdated: this._onResourceUpdated,
        }
      );

      await domReady;

      this.browserRequire = BrowserLoader({
        window: this.win,
        useOnlyShared: true,
      }).require;

      this.isReady = true;

      const framesPromise = this._listFrames();

      Services.prefs.addObserver(
        BROWSERTOOLBOX_SCOPE_PREF,
        this._refreshHostTitle
      );

      // Get the DOM element to mount the ToolboxController to.
      this._componentMount = this.doc.getElementById("toolbox-toolbar-mount");

      await fluentInitPromise;

      // Mount the ToolboxController component and update all its state
      // that can be updated synchronousl
      this._mountReactComponent(fluentL10n.getBundles());
      this._buildDockOptions();
      this._buildInitialPanelDefinitions();
      this._setDebugTargetData();

      this._addWindowListeners();
      this._addChromeEventHandlerEvents();

      // Get the tab bar of the ToolboxController to attach the "keypress" event listener to.
      this._tabBar = this.doc.querySelector(".devtools-tabbar");
      this._tabBar.addEventListener("keypress", this._onToolbarArrowKeypress);

      this._componentMount.setAttribute(
        "aria-label",
        L10N.getStr("toolbox.label")
      );

      this.webconsolePanel = this.doc.querySelector(
        "#toolbox-panel-webconsole"
      );
      this.webconsolePanel.style.height =
        Services.prefs.getIntPref(SPLITCONSOLE_HEIGHT_PREF) + "px";
      this.webconsolePanel.addEventListener(
        "resize",
        this._saveSplitConsoleHeight
      );

      this._buildButtons();

      this._pingTelemetry();

      // The isToolSupported check needs to happen after the target is
      // remoted, otherwise we could have done it in the toolbox constructor
      // (bug 1072764).
      const toolDef = gDevTools.getToolDefinition(this._defaultToolId);
      if (!toolDef || !toolDef.isToolSupported(this)) {
        this._defaultToolId = "webconsole";
      }

      // Update all ToolboxController state that can only be done asynchronously
      await this._setInitialMeatballState();

      // Start rendering the toolbox toolbar before selecting the tool, as the tools
      // can take a few hundred milliseconds seconds to start up.
      //
      // Delay React rendering as Toolbox.open is synchronous.
      // Even if this involve promises, it is synchronous. Toolbox.open already loads
      // react modules and freeze the event loop for a significant time.
      // requestIdleCallback allows releasing it to allow user events to be processed.
      // Use 16ms maximum delay to allow one frame to be rendered at 60FPS
      // (1000ms/60FPS=16ms)
      this.win.requestIdleCallback(
        () => {
          this.component.setCanRender();
        },
        { timeout: 16 }
      );

      await this.selectTool(this._defaultToolId, "initial_panel");

      // Wait until the original tool is selected so that the split
      // console input will receive focus.
      let splitConsolePromise = Promise.resolve();
      if (Services.prefs.getBoolPref(SPLITCONSOLE_ENABLED_PREF)) {
        splitConsolePromise = this.openSplitConsole();
        this.telemetry.addEventProperty(
          this.topWindow,
          "open",
          "tools",
          null,
          "splitconsole",
          true
        );
      } else {
        this.telemetry.addEventProperty(
          this.topWindow,
          "open",
          "tools",
          null,
          "splitconsole",
          false
        );
      }

      await Promise.all([
        splitConsolePromise,
        framesPromise,
        onResourcesWatched,
        tracerInitialization,
      ]);

      // We do not expect the focus to be restored when using about:debugging toolboxes
      // Otherwise, when reloading the toolbox, the debugged tab will be focused.
      if (this.hostType !== Toolbox.HostType.PAGE) {
        // Request the actor to restore the focus to the content page once the
        // target is detached. This typically happens when the console closes.
        // We restore the focus as it may have been stolen by the console input.
        await this.commands.targetConfigurationCommand.updateConfiguration({
          restoreFocus: true,
        });
      }

      await this.initHarAutomation();

      this.emit("ready");
      this._resolveIsOpen();
    }
      .bind(this)()
      .catch(e => {
        console.error("Exception while opening the toolbox", String(e), e);
        // While the exception stack is correctly printed in the Browser console when
        // passing `e` to console.error, it is not on the stdout, so print it via dump.
        dump(e.stack + "\n");
      });
  },

  /**
   * Retrieve the ChromeEventHandler associated to the toolbox frame.
   * When DevTools are loaded in a content frame, this will return the containing chrome
   * frame. Events from nested frames will bubble up to this chrome frame, which allows to
   * listen to events from nested frames.
   */
  getChromeEventHandler() {
    if (!this.win || !this.win.docShell) {
      return null;
    }
    return this.win.docShell.chromeEventHandler;
  },

  /**
   * Attach events on the chromeEventHandler for the current window. When loaded in a
   * frame with type set to "content", events will not bubble across frames. The
   * chromeEventHandler does not have this limitation and will catch all events triggered
   * on any of the frames under the devtools document.
   *
   * Events relying on the chromeEventHandler need to be added and removed at specific
   * moments in the lifecycle of the toolbox, so all the events relying on it should be
   * grouped here.
   */
  _addChromeEventHandlerEvents() {
    // win.docShell.chromeEventHandler might not be accessible anymore when removing the
    // events, so we can't rely on a dynamic getter here.
    // Keep a reference on the chromeEventHandler used to addEventListener to be sure we
    // can remove the listeners afterwards.
    this._chromeEventHandler = this.getChromeEventHandler();
    if (!this._chromeEventHandler) {
      return;
    }

    // Add shortcuts and window-host-shortcuts that use the ChromeEventHandler as target.
    this._addShortcuts();
    this._addWindowHostShortcuts();

    this._chromeEventHandler.addEventListener(
      "keypress",
      this._splitConsoleOnKeypress
    );
    this._chromeEventHandler.addEventListener("focus", this._onFocus, true);
    this._chromeEventHandler.addEventListener("blur", this._onBlur, true);
    this._chromeEventHandler.addEventListener(
      "contextmenu",
      this._onContextMenu
    );
    this._chromeEventHandler.addEventListener("mousedown", this._onMouseDown);
  },

  _removeChromeEventHandlerEvents() {
    if (!this._chromeEventHandler) {
      return;
    }

    // Remove shortcuts and window-host-shortcuts that use the ChromeEventHandler as
    // target.
    this._removeShortcuts();
    this._removeWindowHostShortcuts();

    this._chromeEventHandler.removeEventListener(
      "keypress",
      this._splitConsoleOnKeypress
    );
    this._chromeEventHandler.removeEventListener("focus", this._onFocus, true);
    this._chromeEventHandler.removeEventListener("focus", this._onBlur, true);
    this._chromeEventHandler.removeEventListener(
      "contextmenu",
      this._onContextMenu
    );
    this._chromeEventHandler.removeEventListener(
      "mousedown",
      this._onMouseDown
    );

    this._chromeEventHandler = null;
  },

  _addShortcuts() {
    // Create shortcuts instance for the toolbox
    if (!this.shortcuts) {
      this.shortcuts = new KeyShortcuts({
        window: this.doc.defaultView,
        // The toolbox key shortcuts should be triggered from any frame in DevTools.
        // Use the chromeEventHandler as the target to catch events from all frames.
        target: this.getChromeEventHandler(),
      });
    }

    // Listen for the shortcut key to show the frame list
    this.shortcuts.on(L10N.getStr("toolbox.showFrames.key"), event => {
      if (event.target.id === "command-button-frames") {
        event.target.click();
      }
    });

    // Listen for tool navigation shortcuts.
    this.shortcuts.on(L10N.getStr("toolbox.nextTool.key"), event => {
      this.selectNextTool();
      event.preventDefault();
    });
    this.shortcuts.on(L10N.getStr("toolbox.previousTool.key"), event => {
      this.selectPreviousTool();
      event.preventDefault();
    });
    this.shortcuts.on(L10N.getStr("toolbox.toggleHost.key"), event => {
      this.switchToPreviousHost();
      event.preventDefault();
    });

    // List for Help/Settings key.
    this.shortcuts.on(L10N.getStr("toolbox.help.key"), this.toggleOptions);

    if (!this.isBrowserToolbox) {
      // Listen for Reload shortcuts
      [
        ["reload", false],
        ["reload2", false],
        ["forceReload", true],
        ["forceReload2", true],
      ].forEach(([id, force]) => {
        const key = L10N.getStr("toolbox." + id + ".key");
        this.shortcuts.on(key, event => {
          this.commands.targetCommand.reloadTopLevelTarget(force);

          // Prevent Firefox shortcuts from reloading the page
          event.preventDefault();
        });
      });
    }

    // Add zoom-related shortcuts.
    if (this.hostType != Toolbox.HostType.PAGE) {
      // When the toolbox is rendered in a tab (ie host type is PAGE), the
      // zoom should be handled by the default browser shortcuts.
      ZoomKeys.register(this.win, this.shortcuts);
    }
  },

  _removeShortcuts() {
    if (this.shortcuts) {
      this.shortcuts.destroy();
      this.shortcuts = null;
    }
  },

  /**
   * Adds the keys and commands to the Toolbox Window in window mode.
   */
  _addWindowHostShortcuts() {
    if (this.hostType != Toolbox.HostType.WINDOW) {
      // Those shortcuts are only valid for host type WINDOW.
      return;
    }

    if (!this._windowHostShortcuts) {
      this._windowHostShortcuts = new KeyShortcuts({
        window: this.win,
        // The window host key shortcuts should be triggered from any frame in DevTools.
        // Use the chromeEventHandler as the target to catch events from all frames.
        target: this.getChromeEventHandler(),
      });
    }

    const shortcuts = this._windowHostShortcuts;

    for (const item of Startup.KeyShortcuts) {
      const { id, toolId, shortcut, modifiers } = item;
      const electronKey = KeyShortcuts.parseXulKey(modifiers, shortcut);

      if (id == "browserConsole") {
        // Add key for toggling the browser console from the detached window
        shortcuts.on(electronKey, () => {
          BrowserConsoleManager.toggleBrowserConsole();
        });
      } else if (toolId) {
        // KeyShortcuts contain tool-specific and global key shortcuts,
        // here we only need to copy shortcut specific to each tool.
        shortcuts.on(electronKey, () => {
          this.selectTool(toolId, "key_shortcut").then(() =>
            this.fireCustomKey(toolId)
          );
        });
      }
    }

    // CmdOrCtrl+W is registered only when the toolbox is running in
    // detached window. In the other case the entire browser tab
    // is closed when the user uses this shortcut.
    shortcuts.on(L10N.getStr("toolbox.closeToolbox.key"), this.closeToolbox);

    // The others are only registered in window host type as for other hosts,
    // these keys are already registered by devtools-startup.js
    shortcuts.on(
      L10N.getStr("toolbox.toggleToolboxF12.key"),
      this.closeToolbox
    );
    if (lazy.AppConstants.platform == "macosx") {
      shortcuts.on(
        L10N.getStr("toolbox.toggleToolboxOSX.key"),
        this.closeToolbox
      );
    } else {
      shortcuts.on(L10N.getStr("toolbox.toggleToolbox.key"), this.closeToolbox);
    }
  },

  _removeWindowHostShortcuts() {
    if (this._windowHostShortcuts) {
      this._windowHostShortcuts.destroy();
      this._windowHostShortcuts = null;
    }
  },

  _onContextMenu(e) {
    // Handle context menu events in standard input elements: <input> and <textarea>.
    // Also support for custom input elements using .devtools-input class
    // (e.g. CodeMirror instances).
    const isInInput =
      e.originalTarget.closest("input[type=text]") ||
      e.originalTarget.closest("input[type=search]") ||
      e.originalTarget.closest("input:not([type])") ||
      e.originalTarget.closest(".devtools-input") ||
      e.originalTarget.closest("textarea");

    const doc = e.originalTarget.ownerDocument;
    const isHTMLPanel = doc.documentElement.namespaceURI === HTML_NS;

    if (
      // Context-menu events on input elements will use a custom context menu.
      isInInput ||
      // Context-menu events from HTML panels should not trigger the default
      // browser context menu for HTML documents.
      isHTMLPanel
    ) {
      e.stopPropagation();
      e.preventDefault();
    }

    if (isInInput) {
      this.openTextBoxContextMenu(e.screenX, e.screenY);
    }
  },

  _onMouseDown(e) {
    const isMiddleClick = e.button === 1;
    if (isMiddleClick) {
      // Middle clicks will trigger the scroll lock feature to turn on.
      // When the DevTools toolbox was running in an <iframe>, this behavior was
      // disabled by default. When running in a <browser> element, we now need
      // to catch and preventDefault() on those events.
      e.preventDefault();
    }
  },

  _getDebugTargetData() {
    const url = new URL(this.win.location);
    const remoteId = url.searchParams.get("remoteId");
    const runtimeInfo = remoteClientManager.getRuntimeInfoByRemoteId(remoteId);
    const connectionType =
      remoteClientManager.getConnectionTypeByRemoteId(remoteId);

    return {
      connectionType,
      runtimeInfo,
      descriptorType: this._descriptorFront.descriptorType,
    };
  },

  isDebugTargetFenix() {
    return this._getDebugTargetData()?.runtimeInfo?.isFenix;
  },

  /**
   * loading React modules when needed (to avoid performance penalties
   * during Firefox start up time).
   */
  get React() {
    return this.browserRequire("devtools/client/shared/vendor/react");
  },

  get ReactDOM() {
    return this.browserRequire("devtools/client/shared/vendor/react-dom");
  },

  get ReactRedux() {
    return this.browserRequire("devtools/client/shared/vendor/react-redux");
  },

  get ToolboxController() {
    return this.browserRequire(
      "devtools/client/framework/components/ToolboxController"
    );
  },

  /**
   * A common access point for the client-side mapping service for source maps that
   * any panel can use.  This is a "low-level" API that connects to
   * the source map worker.
   */
  get sourceMapLoader() {
    if (this._sourceMapLoader) {
      return this._sourceMapLoader;
    }
    this._sourceMapLoader = new SourceMapLoader(this.commands.targetCommand);
    return this._sourceMapLoader;
  },

  /**
   * Expose the "Parser" debugger worker to both webconsole and debugger.
   *
   * Note that the Browser Console will also self-instantiate it as it doesn't involve a toolbox.
   */
  get parserWorker() {
    if (this._parserWorker) {
      return this._parserWorker;
    }

    const {
      ParserDispatcher,
    } = require("resource://devtools/client/debugger/src/workers/parser/index.js");

    this._parserWorker = new ParserDispatcher();
    return this._parserWorker;
  },

  /**
   * Clients wishing to use source maps but that want the toolbox to
   * track the source and style sheet actor mapping can use this
   * source map service.  This is a higher-level service than the one
   * returned by |sourceMapLoader|, in that it automatically tracks
   * source and style sheet actor IDs.
   */
  get sourceMapURLService() {
    if (this._sourceMapURLService) {
      return this._sourceMapURLService;
    }
    this._sourceMapURLService = new SourceMapURLService(
      this.commands,
      this.sourceMapLoader
    );
    return this._sourceMapURLService;
  },

  // Return HostType id for telemetry
  _getTelemetryHostId() {
    switch (this.hostType) {
      case Toolbox.HostType.BOTTOM:
        return 0;
      case Toolbox.HostType.RIGHT:
        return 1;
      case Toolbox.HostType.WINDOW:
        return 2;
      case Toolbox.HostType.BROWSERTOOLBOX:
        return 3;
      case Toolbox.HostType.LEFT:
        return 4;
      case Toolbox.HostType.PAGE:
        return 5;
      default:
        return 9;
    }
  },

  // Return HostType string for telemetry
  _getTelemetryHostString() {
    switch (this.hostType) {
      case Toolbox.HostType.BOTTOM:
        return "bottom";
      case Toolbox.HostType.LEFT:
        return "left";
      case Toolbox.HostType.RIGHT:
        return "right";
      case Toolbox.HostType.WINDOW:
        return "window";
      case Toolbox.HostType.PAGE:
        return "page";
      case Toolbox.HostType.BROWSERTOOLBOX:
        return "other";
      default:
        return "bottom";
    }
  },

  _pingTelemetry() {
    Services.prefs.setBoolPref("devtools.everOpened", true);
    this.telemetry.toolOpened("toolbox", this);

    this.telemetry
      .getHistogramById(HOST_HISTOGRAM)
      .add(this._getTelemetryHostId());

    // Log current theme. The question we want to answer is:
    // "What proportion of users use which themes?"
    const currentTheme = Services.prefs.getCharPref("devtools.theme");
    this.telemetry.keyedScalarAdd(CURRENT_THEME_SCALAR, currentTheme, 1);

    const browserWin = this.topWindow;
    this.telemetry.preparePendingEvent(browserWin, "open", "tools", null, [
      "entrypoint",
      "first_panel",
      "host",
      "shortcut",
      "splitconsole",
      "width",
    ]);
    this.telemetry.addEventProperty(
      browserWin,
      "open",
      "tools",
      null,
      "host",
      this._getTelemetryHostString()
    );
  },

  /**
   * Create a simple object to store the state of a toolbox button. The checked state of
   * a button can be updated arbitrarily outside of the scope of the toolbar and its
   * controllers. In order to simplify this interaction this object emits an
   * "updatechecked" event any time the isChecked value is updated, allowing any consuming
   * components to listen and respond to updates.
   *
   * @param {Object} options:
   *
   * @property {String} id - The id of the button or command.
   * @property {String} className - An optional additional className for the button.
   * @property {String} description - The value that will display as a tooltip and in
   *                    the options panel for enabling/disabling.
   * @property {Boolean} disabled - An optional disabled state for the button.
   * @property {Function} onClick - The function to run when the button is activated by
   *                      click or keyboard shortcut. First argument will be the 'click'
   *                      event, and second argument is the toolbox instance.
   * @property {Boolean} isInStartContainer - Buttons can either be placed at the start
   *                     of the toolbar, or at the end.
   * @property {Function} setup - Function run immediately to listen for events changing
   *                      whenever the button is checked or unchecked. The toolbox object
   *                      is passed as first argument and a callback is passed as second
   *                       argument, to be called whenever the checked state changes.
   * @property {Function} teardown - Function run on toolbox close to let a chance to
   *                      unregister listeners set when `setup` was called and avoid
   *                      memory leaks. The same arguments than `setup` function are
   *                      passed to `teardown`.
   * @property {Function} isToolSupported - Function to automatically enable/disable
   *                      the button based on the toolbox. If the toolbox don't support
   *                      the button feature, this method should return false.
   * @property {Function} isCurrentlyVisible - Function to automatically
   *                      hide/show the button based on current state.
   * @property {Function} isChecked - Optional function called to known if the button
   *                      is toggled or not. The function should return true when
   *                      the button should be displayed as toggled on.
   */
  _createButtonState(options) {
    let isCheckedValue = false;
    const {
      id,
      className,
      description,
      disabled,
      onClick,
      isInStartContainer,
      setup,
      teardown,
      isToolSupported,
      isCurrentlyVisible,
      isChecked,
      isToggle,
      onKeyDown,
      experimentalURL,
    } = options;
    const toolbox = this;
    const button = {
      id,
      className,
      description,
      disabled,
      async onClick(event) {
        if (typeof onClick == "function") {
          await onClick(event, toolbox);
          button.emit("updatechecked");
        }
      },
      onKeyDown(event) {
        if (typeof onKeyDown == "function") {
          onKeyDown(event, toolbox);
        }
      },
      isToolSupported,
      isCurrentlyVisible,
      get isChecked() {
        if (typeof isChecked == "function") {
          return isChecked(toolbox);
        }
        return isCheckedValue;
      },
      set isChecked(value) {
        // Note that if options.isChecked is given, this is ignored
        isCheckedValue = value;
        this.emit("updatechecked");
      },
      isToggle,
      // The preference for having this button visible.
      visibilityswitch: `devtools.${id}.enabled`,
      // The toolbar has a container at the start and end of the toolbar for
      // holding buttons. By default the buttons are placed in the end container.
      isInStartContainer: !!isInStartContainer,
      experimentalURL,
    };
    if (typeof setup == "function") {
      const onChange = () => {
        button.emit("updatechecked");
      };
      setup(this, onChange);
      // Save a reference to the cleanup method that will unregister the onChange
      // callback. Immediately bind the function argument so that we don't have to
      // also save a reference to them.
      button.teardown = teardown.bind(options, this, onChange);
    }
    button.isVisible = this._commandIsVisible(button);

    EventEmitter.decorate(button);

    return button;
  },

  _splitConsoleOnKeypress(e) {
    if (e.keyCode !== KeyCodes.DOM_VK_ESCAPE) {
      return;
    }

    const currentPanel = this.getCurrentPanel();
    if (
      typeof currentPanel.onToolboxChromeEventHandlerEscapeKeyDown ===
      "function"
    ) {
      const ac = new this.win.AbortController();
      currentPanel.onToolboxChromeEventHandlerEscapeKeyDown(ac);
      if (ac.signal.aborted) {
        return;
      }
    }

    this.toggleSplitConsole();
    // If the debugger is paused, don't let the ESC key stop any pending navigation.
    // If the host is page, don't let the ESC stop the load of the webconsole frame.
    if (
      this.threadFront.state == "paused" ||
      this.hostType === Toolbox.HostType.PAGE
    ) {
      e.preventDefault();
    }
  },

  /**
   * Add a shortcut key that should work when a split console
   * has focus to the toolbox.
   *
   * @param {String} key
   *        The electron key shortcut.
   * @param {Function} handler
   *        The callback that should be called when the provided key shortcut is pressed.
   * @param {String} whichTool
   *        The tool the key belongs to. The corresponding handler will only be triggered
   *        if this tool is active.
   */
  useKeyWithSplitConsole(key, handler, whichTool) {
    this.shortcuts.on(key, event => {
      if (this.currentToolId === whichTool && this.isSplitConsoleFocused()) {
        handler();
        event.preventDefault();
      }
    });
  },

  _addWindowListeners() {
    this.win.addEventListener("unload", this.destroy);
    this.win.addEventListener("message", this._onBrowserMessage, true);
  },

  _removeWindowListeners() {
    // The host iframe's contentDocument may already be gone.
    if (this.win) {
      this.win.removeEventListener("unload", this.destroy);
      this.win.removeEventListener("message", this._onBrowserMessage, true);
    }
  },

  // Called whenever the chrome send a message
  _onBrowserMessage(event) {
    if (event.data?.name === "switched-host") {
      this._onSwitchedHost(event.data);
    }
    if (event.data?.name === "switched-host-to-tab") {
      this._onSwitchedHostToTab(event.data.browsingContextID);
    }
    if (event.data?.name === "host-raised") {
      this.emit("host-raised");
    }
  },

  _saveSplitConsoleHeight() {
    const height = parseInt(this.webconsolePanel.style.height, 10);
    if (!isNaN(height)) {
      Services.prefs.setIntPref(SPLITCONSOLE_HEIGHT_PREF, height);
    }
  },

  /**
   * Make sure that the console is showing up properly based on all the
   * possible conditions.
   *   1) If the console tab is selected, then regardless of split state
   *      it should take up the full height of the deck, and we should
   *      hide the deck and splitter.
   *   2) If the console tab is not selected and it is split, then we should
   *      show the splitter, deck, and console.
   *   3) If the console tab is not selected and it is *not* split,
   *      then we should hide the console and splitter, and show the deck
   *      at full height.
   */
  _refreshConsoleDisplay() {
    const deck = this.doc.getElementById("toolbox-deck");
    const webconsolePanel = this.webconsolePanel;
    const splitter = this.doc.getElementById("toolbox-console-splitter");
    const openedConsolePanel = this.currentToolId === "webconsole";

    if (openedConsolePanel) {
      deck.collapsed = true;
      deck.removeAttribute("expanded");
      splitter.hidden = true;
      webconsolePanel.collapsed = false;
      webconsolePanel.setAttribute("expanded", "");
    } else {
      deck.collapsed = false;
      deck.toggleAttribute("expanded", !this.splitConsole);
      splitter.hidden = !this.splitConsole;
      webconsolePanel.collapsed = !this.splitConsole;
      webconsolePanel.removeAttribute("expanded");
    }
  },

  /**
   * Handle any custom key events.  Returns true if there was a custom key
   * binding run.
   * @param {string} toolId Which tool to run the command on (skip if not
   * current)
   */
  fireCustomKey(toolId) {
    const toolDefinition = gDevTools.getToolDefinition(toolId);

    if (
      toolDefinition.onkey &&
      (this.currentToolId === toolId ||
        (toolId == "webconsole" && this.splitConsole))
    ) {
      toolDefinition.onkey(this.getCurrentPanel(), this);
    }
  },

  /**
   * Build the notification box as soon as needed.
   */
  get notificationBox() {
    if (!this._notificationBox) {
      let { NotificationBox, PriorityLevels } = this.browserRequire(
        "devtools/client/shared/components/NotificationBox"
      );

      NotificationBox = this.React.createFactory(NotificationBox);

      // Render NotificationBox and assign priority levels to it.
      const box = this.doc.getElementById("toolbox-notificationbox");
      this._notificationBox = Object.assign(
        this.ReactDOM.render(NotificationBox({}), box),
        PriorityLevels
      );
    }
    return this._notificationBox;
  },

  /**
   * Build the options for changing hosts. Called every time
   * the host changes.
   */
  _buildDockOptions() {
    if (!this._descriptorFront.isLocalTab) {
      this.component.setDockOptionsEnabled(false);
      this.component.setCanCloseToolbox(false);
      return;
    }

    this.component.setDockOptionsEnabled(true);
    this.component.setCanCloseToolbox(
      this.hostType !== Toolbox.HostType.WINDOW
    );

    const hostTypes = [];
    for (const type in Toolbox.HostType) {
      const position = Toolbox.HostType[type];
      if (
        position == Toolbox.HostType.BROWSERTOOLBOX ||
        position == Toolbox.HostType.PAGE
      ) {
        continue;
      }

      hostTypes.push({
        position,
        switchHost: this.switchHost.bind(this, position),
      });
    }

    this.component.setCurrentHostType(this.hostType);
    this.component.setHostTypes(hostTypes);
  },

  postMessage(msg) {
    // We sometime try to send messages in middle of destroy(), where the
    // toolbox iframe may already be detached.
    if (!this._destroyer) {
      // Toolbox document is still chrome and disallow identifying message
      // origin via event.source as it is null. So use a custom id.
      msg.frameId = this.frameId;
      this.topWindow.postMessage(msg, "*");
    }
  },

  /**
   * This will fetch the panel definitions from the constants in definitions module
   * and populate the state within the ToolboxController component.
   */
  async _buildInitialPanelDefinitions() {
    // Get the initial list of tab definitions. This list can be amended at a later time
    // by tools registering themselves.
    const definitions = gDevTools.getToolDefinitionArray();
    definitions.forEach(definition => this._buildPanelForTool(definition));

    // Get the definitions that will only affect the main tab area.
    this.panelDefinitions = definitions.filter(
      definition =>
        definition.isToolSupported(this) && definition.id !== "options"
    );
  },

  async _setInitialMeatballState() {
    let disableAutohide, pseudoLocale;
    // Popup auto-hide disabling is only available in browser toolbox and webextension toolboxes.
    if (
      this.isBrowserToolbox ||
      this._descriptorFront.isWebExtensionDescriptor
    ) {
      disableAutohide = await this._isDisableAutohideEnabled();
    }
    // Pseudo locale items are only displayed in the browser toolbox
    if (this.isBrowserToolbox) {
      pseudoLocale = await this.getPseudoLocale();
    }
    // Parallelize the asynchronous calls, so that the DOM is only updated once when
    // updating the React components.
    if (typeof disableAutohide == "boolean") {
      this.component.setDisableAutohide(disableAutohide);
    }
    if (typeof pseudoLocale == "string") {
      this.component.setPseudoLocale(pseudoLocale);
    }
    if (
      this._descriptorFront.isWebExtensionDescriptor &&
      this.hostType === Toolbox.HostType.WINDOW
    ) {
      const alwaysOnTop = Services.prefs.getBoolPref(
        DEVTOOLS_ALWAYS_ON_TOP,
        false
      );
      this.component.setAlwaysOnTop(alwaysOnTop);
    }
  },

  /**
   * Initiate ToolboxController React component and all it's properties. Do the initial render.
   *
   * @param {Object} fluentBundles
   *        A FluentBundle instance used to display any localized text in the React component.
   */
  _mountReactComponent(fluentBundles) {
    // Ensure the toolbar doesn't try to render until the tool is ready.
    const element = this.React.createElement(this.ToolboxController, {
      L10N,
      fluentBundles,
      currentToolId: this.currentToolId,
      selectTool: this.selectTool,
      toggleOptions: this.toggleOptions,
      toggleSplitConsole: this.toggleSplitConsole,
      toggleNoAutohide: this.toggleNoAutohide,
      toggleAlwaysOnTop: this.toggleAlwaysOnTop,
      disablePseudoLocale: this.disablePseudoLocale,
      enableAccentedPseudoLocale: this.enableAccentedPseudoLocale,
      enableBidiPseudoLocale: this.enableBidiPseudoLocale,
      closeToolbox: this.closeToolbox,
      focusButton: this._onToolbarFocus,
      toolbox: this,
      onTabsOrderUpdated: this._onTabsOrderUpdated,
    });

    this.component = this.ReactDOM.render(element, this._componentMount);
  },

  /**
   * Reset tabindex attributes across all focusable elements inside the toolbar.
   * Only have one element with tabindex=0 at a time to make sure that tabbing
   * results in navigating away from the toolbar container.
   * @param  {FocusEvent} event
   */
  _onToolbarFocus(id) {
    this.component.setFocusedButton(id);
  },

  /**
   * On left/right arrow press, attempt to move the focus inside the toolbar to
   * the previous/next focusable element. This is not in the React component
   * as it is difficult to coordinate between different component elements.
   * The components are responsible for setting the correct tabindex value
   * for if they are the focused element.
   * @param  {KeyboardEvent} event
   */
  _onToolbarArrowKeypress(event) {
    const { key, target, ctrlKey, shiftKey, altKey, metaKey } = event;

    // If any of the modifier keys are pressed do not attempt navigation as it
    // might conflict with global shortcuts (Bug 1327972).
    if (ctrlKey || shiftKey || altKey || metaKey) {
      return;
    }

    const buttons = [...this._tabBar.querySelectorAll("button")];
    const curIndex = buttons.indexOf(target);

    if (curIndex === -1) {
      console.warn(
        target +
          " is not found among Developer Tools tab bar " +
          "focusable elements."
      );
      return;
    }

    let newTarget;
    const firstTabIndex = 0;
    const lastTabIndex = buttons.length - 1;
    const nextOrLastTabIndex = Math.min(lastTabIndex, curIndex + 1);
    const previousOrFirstTabIndex = Math.max(firstTabIndex, curIndex - 1);
    const ltr = this.direction === "ltr";

    if (key === "ArrowLeft") {
      // Do nothing if already at the beginning.
      if (
        (ltr && curIndex === firstTabIndex) ||
        (!ltr && curIndex === lastTabIndex)
      ) {
        return;
      }
      newTarget = buttons[ltr ? previousOrFirstTabIndex : nextOrLastTabIndex];
    } else if (key === "ArrowRight") {
      // Do nothing if already at the end.
      if (
        (ltr && curIndex === lastTabIndex) ||
        (!ltr && curIndex === firstTabIndex)
      ) {
        return;
      }
      newTarget = buttons[ltr ? nextOrLastTabIndex : previousOrFirstTabIndex];
    } else {
      return;
    }

    newTarget.focus();

    event.preventDefault();
    event.stopPropagation();
  },

  /**
   * Add buttons to the UI as specified in devtools/client/definitions.js
   */
  _buildButtons() {
    // Beyond the normal preference filtering
    this.toolbarButtons = [
      this._buildErrorCountButton(),
      this._buildPickerButton(),
      this._buildFrameButton(),
    ];

    ToolboxButtons.forEach(definition => {
      const button = this._createButtonState(definition);
      this.toolbarButtons.push(button);
    });

    this.component.setToolboxButtons(this.toolbarButtons);
  },

  /**
   * Button to select a frame for the inspector to target.
   */
  _buildFrameButton() {
    this.frameButton = this._createButtonState({
      id: "command-button-frames",
      description: L10N.getStr("toolbox.frames.tooltip"),
      isToolSupported: toolbox => {
        return toolbox.target.getTrait("frames");
      },
      isCurrentlyVisible: () => {
        const hasFrames = this.frameMap.size > 1;
        const isOnOptionsPanel = this.currentToolId === "options";
        return hasFrames || isOnOptionsPanel;
      },
    });

    return this.frameButton;
  },

  /**
   * Button to display the number of errors.
   */
  _buildErrorCountButton() {
    this.errorCountButton = this._createButtonState({
      id: "command-button-errorcount",
      isInStartContainer: false,
      isToolSupported: () => true,
      description: L10N.getStr("toolbox.errorCountButton.description"),
    });
    // Use updateErrorCountButton to set some properties so we don't have to repeat
    // the logic here.
    this.updateErrorCountButton();

    return this.errorCountButton;
  },

  /**
   * Toggle the picker, but also decide whether or not the highlighter should
   * focus the window. This is only desirable when the toolbox is mounted to the
   * window. When devtools is free floating, then the target window should not
   * pop in front of the viewer when the picker is clicked.
   *
   * Note: Toggle picker can be overwritten by panel other than the inspector to
   * allow for custom picker behaviour.
   */
  async _onPickerClick() {
    const focus =
      this.hostType === Toolbox.HostType.BOTTOM ||
      this.hostType === Toolbox.HostType.LEFT ||
      this.hostType === Toolbox.HostType.RIGHT;
    const currentPanel = this.getCurrentPanel();
    if (currentPanel.togglePicker) {
      currentPanel.togglePicker(focus);
    } else {
      this.nodePicker.togglePicker(focus);
    }
  },

  /**
   * If the picker is activated, then allow the Escape key to deactivate the
   * functionality instead of the default behavior of toggling the console.
   */
  _onPickerKeypress(event) {
    if (event.keyCode === KeyCodes.DOM_VK_ESCAPE) {
      const currentPanel = this.getCurrentPanel();
      if (currentPanel.cancelPicker) {
        currentPanel.cancelPicker();
      } else {
        this.nodePicker.stop({ canceled: true });
      }
      // Stop the console from toggling.
      event.stopImmediatePropagation();
    }
  },

  async _onPickerStarting() {
    if (this.isDestroying()) {
      return;
    }
    this.tellRDMAboutPickerState(true, PICKER_TYPES.ELEMENT);
    this.pickerButton.isChecked = true;
    await this.selectTool("inspector", "inspect_dom");
    // turn off color picker when node picker is starting
    this.getPanel("inspector").hideEyeDropper();
    this.on("select", this._onToolSelectedStopPicker);
  },

  async _onPickerStarted() {
    this.doc.addEventListener("keypress", this._onPickerKeypress, true);
  },

  _onPickerStopped() {
    if (this.isDestroying()) {
      return;
    }
    this.tellRDMAboutPickerState(false, PICKER_TYPES.ELEMENT);
    this.off("select", this._onToolSelectedStopPicker);
    this.doc.removeEventListener("keypress", this._onPickerKeypress, true);
    this.pickerButton.isChecked = false;
  },

  _onToolSelectedStopPicker() {
    this.nodePicker.stop({ canceled: true });
  },

  /**
   * When the picker is canceled, make sure the toolbox
   * gets the focus.
   */
  _onPickerCanceled() {
    if (this.hostType !== Toolbox.HostType.WINDOW) {
      this.win.focus();
    }
  },

  _onPickerPicked(nodeFront) {
    this.selection.setNodeFront(nodeFront, { reason: "picker-node-picked" });
  },

  _onPickerPreviewed(nodeFront) {
    this.selection.setNodeFront(nodeFront, { reason: "picker-node-previewed" });
  },

  /**
   * RDM sometimes simulates touch events. For this to work correctly at all times, it
   * needs to know when the picker is active or not.
   * This method communicates with the RDM Manager if it exists.
   *
   * @param {Boolean} state
   * @param {String} pickerType
   *        One of devtools/shared/picker-constants
   */
  async tellRDMAboutPickerState(state, pickerType) {
    const { localTab } = this.target;

    if (!ResponsiveUIManager.isActiveForTab(localTab)) {
      return;
    }

    const ui = ResponsiveUIManager.getResponsiveUIForTab(localTab);
    await ui.responsiveFront.setElementPickerState(state, pickerType);
  },

  /**
   * The element picker button enables the ability to select a DOM node by clicking
   * it on the page.
   */
  _buildPickerButton() {
    this.pickerButton = this._createButtonState({
      id: "command-button-pick",
      className: this._getPickerAdditionalClassName(),
      description: this._getPickerTooltip(),
      onClick: this._onPickerClick,
      isInStartContainer: true,
      isToolSupported: toolbox => {
        return toolbox.target.getTrait("frames");
      },
      isToggle: true,
    });

    return this.pickerButton;
  },

  _getPickerAdditionalClassName() {
    if (this.isDebugTargetFenix()) {
      return "remote-fenix";
    }
    return null;
  },

  /**
   * Get the tooltip for the element picker button.
   * It has multiple possible keyboard shortcuts for macOS.
   *
   * @return {String}
   */
  _getPickerTooltip() {
    let shortcut = L10N.getStr("toolbox.elementPicker.key");
    shortcut = KeyShortcuts.parseElectronKey(this.win, shortcut);
    shortcut = KeyShortcuts.stringify(shortcut);
    const shortcutMac = L10N.getStr("toolbox.elementPicker.mac.key");
    const isMac = Services.appinfo.OS === "Darwin";

    let label;
    if (this.isDebugTargetFenix()) {
      label = isMac
        ? "toolbox.androidElementPicker.mac.tooltip"
        : "toolbox.androidElementPicker.tooltip";
    } else {
      label = isMac
        ? "toolbox.elementPicker.mac.tooltip"
        : "toolbox.elementPicker.tooltip";
    }

    return isMac
      ? L10N.getFormatStr(label, shortcut, shortcutMac)
      : L10N.getFormatStr(label, shortcut);
  },

  async _listenAndApplyConfigurationPref() {
    this._onBooleanConfigurationPrefChange =
      this._onBooleanConfigurationPrefChange.bind(this);

    // We have two configurations:
    //  * target specific configurations, which are set on all target actors, themself easily accessible from any actor.
    //    Most configurations should be set this way.
    //  * thread specific configurations, which are set on directly on the thread actor.
    //    Only configuration used by the thread actor should be set this way.
    const targetConfiguration = {};

    // Get the current thread settings from the prefs as well as debugger internal storage for breakpoints.
    const threadConfiguration = await getThreadOptions();

    for (const prefName in BOOLEAN_CONFIGURATION_PREFS) {
      const { name, thread } = BOOLEAN_CONFIGURATION_PREFS[prefName];
      const value = Services.prefs.getBoolPref(prefName, false);

      // Based on the pref name, this will be stored in either target or thread specific configuration
      if (thread) {
        threadConfiguration[name] = value;
      } else {
        targetConfiguration[name] = value;
      }

      // Also listen for any future change
      Services.prefs.addObserver(
        prefName,
        this._onBooleanConfigurationPrefChange
      );
    }

    // Now communicate the configurations to the server
    await this.commands.targetConfigurationCommand.updateConfiguration(
      targetConfiguration
    );
    await this.commands.threadConfigurationCommand.updateConfiguration(
      threadConfiguration
    );
  },

  /**
   * Called whenever a preference registered in BOOLEAN_CONFIGURATION_PREFS
   * changes.
   * This is used to communicate the new setting's value to the server.
   *
   * @param {String} subject
   * @param {String} topic
   * @param {String} prefName
   *        The preference name which changed
   */
  async _onBooleanConfigurationPrefChange(subject, topic, prefName) {
    const { name, thread } = BOOLEAN_CONFIGURATION_PREFS[prefName];
    const value = Services.prefs.getBoolPref(prefName, false);

    const configurationCommand = thread
      ? this.commands.threadConfigurationCommand
      : this.commands.targetConfigurationCommand;
    await configurationCommand.updateConfiguration({
      [name]: value,
    });

    // This event is only emitted for tests in order to know when the setting has been applied by the backend.
    this.emitForTests("new-configuration-applied", prefName);
  },

  /**
   * Update the visibility of the buttons.
   */
  updateToolboxButtonsVisibility() {
    this.toolbarButtons.forEach(button => {
      button.isVisible = this._commandIsVisible(button);
    });
    this.component.setToolboxButtons(this.toolbarButtons);
  },

  /**
   * Update the buttons.
   */
  updateToolboxButtons() {
    const inspectorFront = this.target.getCachedFront("inspector");
    // two of the buttons have highlighters that need to be cleared
    // on will-navigate, otherwise we hold on to the stale highlighter
    const hasHighlighters =
      inspectorFront &&
      (inspectorFront.hasHighlighter("RulersHighlighter") ||
        inspectorFront.hasHighlighter("MeasuringToolHighlighter"));
    if (hasHighlighters) {
      inspectorFront.destroyHighlighters();
      this.component.setToolboxButtons(this.toolbarButtons);
    }
  },

  /**
   * Visually update picker button.
   * This function is called on every "select" event. Newly selected panel can
   * update the visual state of the picker button such as disabled state,
   * additional CSS classes (className), and tooltip (description).
   */
  updatePickerButton() {
    const button = this.pickerButton;
    const currentPanel = this.getCurrentPanel();

    if (currentPanel?.updatePickerButton) {
      currentPanel.updatePickerButton();
    } else {
      // If the current panel doesn't define a custom updatePickerButton,
      // revert the button to its default state
      button.description = this._getPickerTooltip();
      button.className = this._getPickerAdditionalClassName();
      button.disabled = null;
    }
  },

  /**
   * Update the visual state of the Frame picker button.
   */
  updateFrameButton() {
    if (this.isDestroying()) {
      return;
    }

    if (this.currentToolId === "options" && this.frameMap.size <= 1) {
      // If the button is only visible because the user is on the Options panel, disable
      // the button and set an appropriate description.
      this.frameButton.disabled = true;
      this.frameButton.description = L10N.getStr(
        "toolbox.frames.disabled.tooltip"
      );
    } else {
      // Otherwise, enable the button and update the description.
      this.frameButton.disabled = false;
      this.frameButton.description = L10N.getStr("toolbox.frames.tooltip");
    }

    // Highlight the button when a child frame is selected and visible.
    const selectedFrame = this.frameMap.get(this.selectedFrameId) || {};

    // We need to do something a bit different to avoid some test failures. This function
    // can be called from onWillNavigate, and the current target might have this `traits`
    // property nullifed, which is unfortunate as that's what isToolSupported is checking,
    // so it will throw.
    // So here, we check first if the button isn't going to be visible anyway (it only checks
    // for this.frameMap size) so we don't call _commandIsVisible.
    const isVisible = !this.frameButton.isCurrentlyVisible()
      ? false
      : this._commandIsVisible(this.frameButton);

    this.frameButton.isVisible = isVisible;

    if (isVisible) {
      this.frameButton.isChecked = !selectedFrame.isTopLevel;
    }
  },

  updateErrorCountButton() {
    this.errorCountButton.isVisible =
      this._commandIsVisible(this.errorCountButton) && this._errorCount > 0;
    this.errorCountButton.errorCount = this._errorCount;
  },

  /**
   * Ensure the visibility of each toolbox button matches the preference value.
   */
  _commandIsVisible(button) {
    const { isToolSupported, isCurrentlyVisible, visibilityswitch } = button;

    if (!Services.prefs.getBoolPref(visibilityswitch, true)) {
      return false;
    }

    if (isToolSupported && !isToolSupported(this)) {
      return false;
    }

    if (isCurrentlyVisible && !isCurrentlyVisible()) {
      return false;
    }

    return true;
  },

  /**
   * Build a panel for a tool definition.
   *
   * @param {string} toolDefinition
   *        Tool definition of the tool to build a tab for.
   */
  _buildPanelForTool(toolDefinition) {
    if (!toolDefinition.isToolSupported(this)) {
      return;
    }

    const deck = this.doc.getElementById("toolbox-deck");
    const id = toolDefinition.id;

    if (toolDefinition.ordinal == undefined || toolDefinition.ordinal < 0) {
      toolDefinition.ordinal = MAX_ORDINAL;
    }

    if (!toolDefinition.bgTheme) {
      toolDefinition.bgTheme = "theme-toolbar";
    }
    const panel = this.doc.createXULElement("vbox");
    panel.className = "toolbox-panel " + toolDefinition.bgTheme;

    // There is already a container for the webconsole frame.
    if (!this.doc.getElementById("toolbox-panel-" + id)) {
      panel.id = "toolbox-panel-" + id;
    }

    deck.appendChild(panel);
  },

  /**
   * Lazily created map of the additional tools registered to this toolbox.
   *
   * @returns {Map<string, object>}
   *          a map of the tools definitions registered to this
   *          particular toolbox (the key is the toolId string, the value
   *          is the tool definition plain javascript object).
   */
  get additionalToolDefinitions() {
    if (!this._additionalToolDefinitions) {
      this._additionalToolDefinitions = new Map();
    }

    return this._additionalToolDefinitions;
  },

  /**
   * Retrieve the array of the additional tools registered to this toolbox.
   *
   * @return {Array<object>}
   *         the array of additional tool definitions registered on this toolbox.
   */
  getAdditionalTools() {
    if (this._additionalToolDefinitions) {
      return Array.from(this.additionalToolDefinitions.values());
    }
    return [];
  },

  /**
   * Get the additional tools that have been registered and are visible.
   *
   * @return {Array<object>}
   *         the array of additional tool definitions registered on this toolbox.
   */
  getVisibleAdditionalTools() {
    return this.visibleAdditionalTools.map(toolId =>
      this.additionalToolDefinitions.get(toolId)
    );
  },

  /**
   * Test the existence of a additional tools registered to this toolbox by tool id.
   *
   * @param {string} toolId
   *        the id of the tool to test for existence.
   *
   * @return {boolean}
   *
   */
  hasAdditionalTool(toolId) {
    return this.additionalToolDefinitions.has(toolId);
  },

  /**
   * Register and load an additional tool on this particular toolbox.
   *
   * @param {object} definition
   *        the additional tool definition to register and add to this toolbox.
   */
  addAdditionalTool(definition) {
    if (!definition.id) {
      throw new Error("Tool definition id is missing");
    }

    if (this.isToolRegistered(definition.id)) {
      throw new Error("Tool definition already registered: " + definition.id);
    }

    this.additionalToolDefinitions.set(definition.id, definition);
    this.visibleAdditionalTools = [
      ...this.visibleAdditionalTools,
      definition.id,
    ];

    const buildPanel = () => this._buildPanelForTool(definition);

    if (this.isReady) {
      buildPanel();
    } else {
      this.once("ready", buildPanel);
    }
  },

  /**
   * Retrieve the registered inspector extension sidebars
   * (used by the inspector panel during its deferred initialization).
   */
  get inspectorExtensionSidebars() {
    return this._inspectorExtensionSidebars;
  },

  /**
   * Register an extension sidebar for the inspector panel.
   *
   * @param {String} id
   *        An unique sidebar id
   * @param {Object} options
   * @param {String} options.title
   *        A title for the sidebar
   */
  async registerInspectorExtensionSidebar(id, options) {
    this._inspectorExtensionSidebars.set(id, options);

    // Defer the extension sidebar creation if the inspector
    // has not been created yet (and do not create the inspector
    // only to register an extension sidebar).
    if (!this.target.getCachedFront("inspector")) {
      return;
    }

    const inspector = this.getPanel("inspector");
    if (!inspector) {
      return;
    }

    inspector.addExtensionSidebar(id, options);
  },

  /**
   * Unregister an extension sidebar for the inspector panel.
   *
   * @param {String} id
   *        An unique sidebar id
   */
  unregisterInspectorExtensionSidebar(id) {
    // Unregister the sidebar from the toolbox if the toolbox is not already
    // being destroyed (otherwise we would trigger a re-rendering of the
    // inspector sidebar tabs while the toolbox is going away).
    if (this._destroyer) {
      return;
    }

    const sidebarDef = this._inspectorExtensionSidebars.get(id);
    if (!sidebarDef) {
      return;
    }

    this._inspectorExtensionSidebars.delete(id);

    // Remove the created sidebar instance if the inspector panel
    // has been already created.
    if (!this.target.getCachedFront("inspector")) {
      return;
    }

    const inspector = this.getPanel("inspector");
    inspector.removeExtensionSidebar(id);
  },

  /**
   * Unregister and unload an additional tool from this particular toolbox.
   *
   * @param {string} toolId
   *        the id of the additional tool to unregister and remove.
   */
  removeAdditionalTool(toolId) {
    // Early exit if the toolbox is already destroying itself.
    if (this._destroyer) {
      return;
    }

    if (!this.hasAdditionalTool(toolId)) {
      throw new Error(
        "Tool definition not registered to this toolbox: " + toolId
      );
    }

    this.additionalToolDefinitions.delete(toolId);
    this.visibleAdditionalTools = this.visibleAdditionalTools.filter(
      id => id !== toolId
    );
    this.unloadTool(toolId);
  },

  /**
   * Ensure the tool with the given id is loaded.
   *
   * @param {string} id
   *        The id of the tool to load.
   * @param {Object} options
   *        Object that will be passed to the panel `open` method.
   */
  loadTool(id, options) {
    let iframe = this.doc.getElementById("toolbox-panel-iframe-" + id);
    if (iframe) {
      const panel = this._toolPanels.get(id);
      return new Promise(resolve => {
        if (panel) {
          resolve(panel);
        } else {
          this.once(id + "-ready", initializedPanel => {
            resolve(initializedPanel);
          });
        }
      });
    }

    return new Promise((resolve, reject) => {
      // Retrieve the tool definition (from the global or the per-toolbox tool maps)
      const definition = this.getToolDefinition(id);

      if (!definition) {
        reject(new Error("no such tool id " + id));
        return;
      }

      iframe = this.doc.createXULElement("iframe");
      iframe.className = "toolbox-panel-iframe";
      iframe.id = "toolbox-panel-iframe-" + id;
      iframe.setAttribute("flex", 1);
      iframe.setAttribute("forceOwnRefreshDriver", "");
      iframe.tooltip = "aHTMLTooltip";
      iframe.style.visibility = "hidden";

      gDevTools.emit(id + "-init", this, iframe);
      this.emit(id + "-init", iframe);

      // If no parent yet, append the frame into default location.
      if (!iframe.parentNode) {
        const vbox = this.doc.getElementById("toolbox-panel-" + id);
        vbox.appendChild(iframe);
        vbox.visibility = "visible";
      }

      const onLoad = async () => {
        // Prevent flicker while loading by waiting to make visible until now.
        iframe.style.visibility = "visible";

        // Try to set the dir attribute as early as possible.
        this.setIframeDocumentDir(iframe);

        // The build method should return a panel instance, so events can
        // be fired with the panel as an argument. However, in order to keep
        // backward compatibility with existing extensions do a check
        // for a promise return value.
        let built = definition.build(iframe.contentWindow, this, this.commands);

        if (!(typeof built.then == "function")) {
          const panel = built;
          iframe.panel = panel;

          // The panel instance is expected to fire (and listen to) various
          // framework events, so make sure it's properly decorated with
          // appropriate API (on, off, once, emit).
          // In this case we decorate panel instances directly returned by
          // the tool definition 'build' method.
          if (typeof panel.emit == "undefined") {
            EventEmitter.decorate(panel);
          }

          gDevTools.emit(id + "-build", this, panel);
          this.emit(id + "-build", panel);

          // The panel can implement an 'open' method for asynchronous
          // initialization sequence.
          if (typeof panel.open == "function") {
            built = panel.open(options);
          } else {
            built = new Promise(resolve => {
              resolve(panel);
            });
          }
        }

        // Wait till the panel is fully ready and fire 'ready' events.
        Promise.resolve(built).then(panel => {
          this._toolPanels.set(id, panel);

          // Make sure to decorate panel object with event API also in case
          // where the tool definition 'build' method returns only a promise
          // and the actual panel instance is available as soon as the
          // promise is resolved.
          if (typeof panel.emit == "undefined") {
            EventEmitter.decorate(panel);
          }

          gDevTools.emit(id + "-ready", this, panel);
          this.emit(id + "-ready", panel);

          resolve(panel);
        }, console.error);
      };

      iframe.setAttribute("src", definition.url);
      if (definition.panelLabel) {
        iframe.setAttribute("aria-label", definition.panelLabel);
      }

      // Depending on the host, iframe.contentWindow is not always
      // defined at this moment. If it is not defined, we use an
      // event listener on the iframe DOM node. If it's defined,
      // we use the chromeEventHandler. We can't use a listener
      // on the DOM node every time because this won't work
      // if the (xul chrome) iframe is loaded in a content docshell.
      if (iframe.contentWindow) {
        DOMHelpers.onceDOMReady(iframe.contentWindow, onLoad);
      } else {
        const callback = () => {
          iframe.removeEventListener("DOMContentLoaded", callback);
          onLoad();
        };

        iframe.addEventListener("DOMContentLoaded", callback);
      }
    });
  },

  /**
   * Set the dir attribute on the content document element of the provided iframe.
   *
   * @param {IFrameElement} iframe
   */
  setIframeDocumentDir(iframe) {
    const docEl = iframe.contentWindow?.document.documentElement;
    if (!docEl || docEl.namespaceURI !== HTML_NS) {
      // Bail out if the content window or document is not ready or if the document is not
      // HTML.
      return;
    }

    if (docEl.hasAttribute("dir")) {
      // Set the dir attribute value only if dir is already present on the document.
      docEl.setAttribute("dir", this.direction);
    }
  },

  /**
   * Mark all in collection as unselected; and id as selected
   * @param {string} collection
   *        DOM collection of items
   * @param {string} id
   *        The Id of the item within the collection to select
   */
  selectSingleNode(collection, id) {
    [...collection].forEach(node => {
      if (node.id === id) {
        node.setAttribute("selected", "true");
        node.setAttribute("aria-selected", "true");
      } else {
        node.removeAttribute("selected");
        node.removeAttribute("aria-selected");
      }
      // The webconsole panel is in a special location due to split console
      if (!node.id) {
        node = this.webconsolePanel;
      }

      const iframe = node.querySelector(".toolbox-panel-iframe");
      if (iframe) {
        let visible = node.id == id;
        // Prevents hiding the split-console if it is currently enabled
        if (node == this.webconsolePanel && this.splitConsole) {
          visible = true;
        }
        this.setIframeVisible(iframe, visible);
      }
    });
  },

  /**
   * Make a privileged iframe visible/hidden.
   *
   * For now, XUL Iframes loading chrome documents (i.e. <iframe type!="content" />)
   * can't be hidden at platform level. And so don't support 'visibilitychange' event.
   *
   * This helper workarounds that by at least being able to send these kind of events.
   * It will help panel react differently depending on them being displayed or in
   * background.
   */
  setIframeVisible(iframe, visible) {
    const state = visible ? "visible" : "hidden";
    const win = iframe.contentWindow;
    const doc = win.document;
    if (doc.visibilityState != state) {
      // 1) Overload document's `visibilityState` attribute
      // Use defineProperty, as by default `document.visbilityState` is read only.
      Object.defineProperty(doc, "visibilityState", {
        value: state,
        configurable: true,
      });

      // 2) Fake the 'visibilitychange' event
      doc.dispatchEvent(new win.Event("visibilitychange"));
    }
  },

  /**
   * Switch to the tool with the given id
   *
   * @param {string} id
   *        The id of the tool to switch to
   * @param {string} reason
   *        Reason the tool was opened
   * @param {Object} options
   *        Object that will be passed to the panel
   */
  selectTool(id, reason = "unknown", options) {
    this.emit("panel-changed");

    if (this.currentToolId == id) {
      const panel = this._toolPanels.get(id);
      if (panel) {
        // We have a panel instance, so the tool is already fully loaded.

        // re-focus tool to get key events again
        this.focusTool(id);

        // Return the existing panel in order to have a consistent return value.
        return Promise.resolve(panel);
      }
      // Otherwise, if there is no panel instance, it is still loading,
      // so we are racing another call to selectTool with the same id.
      return this.once("select").then(() =>
        Promise.resolve(this._toolPanels.get(id))
      );
    }

    if (!this.isReady) {
      throw new Error("Can't select tool, wait for toolbox 'ready' event");
    }

    // Check if the tool exists.
    if (
      this.panelDefinitions.find(definition => definition.id === id) ||
      id === "options" ||
      this.additionalToolDefinitions.get(id)
    ) {
      if (this.currentToolId) {
        this.telemetry.toolClosed(this.currentToolId, this);
      }

      this._pingTelemetrySelectTool(id, reason);
    } else {
      throw new Error("No tool found");
    }

    // and select the right iframe
    const toolboxPanels = this.doc.querySelectorAll(".toolbox-panel");
    this.selectSingleNode(toolboxPanels, "toolbox-panel-" + id);

    this.lastUsedToolId = this.currentToolId;
    this.currentToolId = id;
    this._refreshConsoleDisplay();
    if (id != "options") {
      Services.prefs.setCharPref(this._prefs.LAST_TOOL, id);
    }

    return this.loadTool(id, options).then(panel => {
      // focus the tool's frame to start receiving key events
      this.focusTool(id);

      this.emit("select", id);
      this.emit(id + "-selected", panel);
      return panel;
    });
  },

  _pingTelemetrySelectTool(id, reason) {
    const width = Math.ceil(this.win.outerWidth / 50) * 50;
    const panelName = this.getTelemetryPanelNameOrOther(id);
    const prevPanelName = this.getTelemetryPanelNameOrOther(this.currentToolId);
    const cold = !this.getPanel(id);
    const pending = ["host", "width", "start_state", "panel_name", "cold"];

    // On first load this.currentToolId === undefined so we need to skip sending
    // a devtools.main.exit telemetry event.
    if (this.currentToolId) {
      this.telemetry.recordEvent("exit", prevPanelName, null, {
        host: this._hostType,
        width,
        panel_name: prevPanelName,
        next_panel: panelName,
        reason,
      });
    }

    this.telemetry.addEventProperties(this.topWindow, "open", "tools", null, {
      width,
    });

    if (id === "webconsole") {
      pending.push("message_count");
    }

    this.telemetry.preparePendingEvent(this, "enter", panelName, null, pending);

    this.telemetry.addEventProperties(this, "enter", panelName, null, {
      host: this._hostType,
      start_state: reason,
      panel_name: panelName,
      cold,
    });

    if (reason !== "initial_panel") {
      const width = Math.ceil(this.win.outerWidth / 50) * 50;
      this.telemetry.addEventProperty(
        this,
        "enter",
        panelName,
        null,
        "width",
        width
      );
    }

    // Cold webconsole event message_count is handled in
    // devtools/client/webconsole/webconsole-wrapper.js
    if (!cold && id === "webconsole") {
      this.telemetry.addEventProperty(
        this,
        "enter",
        "webconsole",
        null,
        "message_count",
        0
      );
    }

    this.telemetry.toolOpened(id, this);
  },

  /**
   * Focus a tool's panel by id
   * @param  {string} id
   *         The id of tool to focus
   */
  focusTool(id, state = true) {
    const iframe = this.doc.getElementById("toolbox-panel-iframe-" + id);

    if (state) {
      iframe.focus();
    } else {
      iframe.blur();
    }
  },

  /**
   * Focus split console's input line
   */
  focusConsoleInput() {
    const consolePanel = this.getPanel("webconsole");
    if (consolePanel) {
      consolePanel.focusInput();
    }
  },

  /**
   * Disable all network logs in the console
   */
  disableAllConsoleNetworkLogs() {
    const consolePanel = this.getPanel("webconsole");
    if (consolePanel) {
      consolePanel.hud.ui.disableAllNetworkMessages();
    }
  },

  /**
   * If the console is split and we are focusing an element outside
   * of the console, then store the newly focused element, so that
   * it can be restored once the split console closes.
   *
   * @param Element originalTarget
   *        The DOM Element that just got focused.
   */
  _updateLastFocusedElementForSplitConsole(originalTarget) {
    // Ignore any non element nodes, or any elements contained
    // within the webconsole frame.
    const webconsoleURL = gDevTools.getToolDefinition("webconsole").url;
    if (
      originalTarget.nodeType !== 1 ||
      originalTarget.baseURI === webconsoleURL
    ) {
      return;
    }

    this._lastFocusedElement = originalTarget;
  },

  // Report if the toolbox is currently focused,
  // or the focus in elsewhere in the browser or another app.
  _isToolboxFocused: false,

  _onFocus({ originalTarget }) {
    this._isToolboxFocused = true;
    this._debounceUpdateFocusedState();

    this._updateLastFocusedElementForSplitConsole(originalTarget);
  },

  _onBlur() {
    this._isToolboxFocused = false;
    this._debounceUpdateFocusedState();
  },

  _onTabsOrderUpdated() {
    this._combineAndSortPanelDefinitions();
  },

  /**
   * Opens the split console.
   *
   * @param {boolean} focusConsoleInput
   *        By default, the console input will be focused.
   *        Pass false in order to prevent this.
   *
   * @returns {Promise} a promise that resolves once the tool has been
   *          loaded and focused.
   */
  openSplitConsole({ focusConsoleInput = true } = {}) {
    this._splitConsole = true;
    Services.prefs.setBoolPref(SPLITCONSOLE_ENABLED_PREF, true);
    this._refreshConsoleDisplay();

    // Ensure split console is visible if console was already loaded in background
    const iframe = this.webconsolePanel.querySelector(".toolbox-panel-iframe");
    if (iframe) {
      this.setIframeVisible(iframe, true);
    }

    return this.loadTool("webconsole").then(() => {
      this.component.setIsSplitConsoleActive(true);
      this.telemetry.recordEvent("activate", "split_console", null, {
        host: this._getTelemetryHostString(),
        width: Math.ceil(this.win.outerWidth / 50) * 50,
      });
      this.emit("split-console");
      if (focusConsoleInput) {
        this.focusConsoleInput();
      }
    });
  },

  /**
   * Closes the split console.
   *
   * @returns {Promise} a promise that resolves once the tool has been
   *          closed.
   */
  closeSplitConsole() {
    this._splitConsole = false;
    Services.prefs.setBoolPref(SPLITCONSOLE_ENABLED_PREF, false);
    this._refreshConsoleDisplay();
    this.component.setIsSplitConsoleActive(false);

    this.telemetry.recordEvent("deactivate", "split_console", null, {
      host: this._getTelemetryHostString(),
      width: Math.ceil(this.win.outerWidth / 50) * 50,
    });

    this.emit("split-console");

    if (this._lastFocusedElement) {
      this._lastFocusedElement.focus();
    }
    return Promise.resolve();
  },

  /**
   * Toggles the split state of the webconsole.  If the webconsole panel
   * is already selected then this command is ignored.
   *
   * @returns {Promise} a promise that resolves once the tool has been
   *          opened or closed.
   */
  toggleSplitConsole() {
    if (this.currentToolId !== "webconsole") {
      return this.splitConsole
        ? this.closeSplitConsole()
        : this.openSplitConsole();
    }

    return Promise.resolve();
  },

  /**
   * Toggles the options panel.
   * If the option panel is already selected then select the last selected panel.
   */
  toggleOptions(event) {
    // Flip back to the last used panel if we are already
    // on the options panel.
    if (
      this.currentToolId === "options" &&
      gDevTools.getToolDefinition(this.lastUsedToolId)
    ) {
      this.selectTool(this.lastUsedToolId, "toggle_settings_off");
    } else {
      this.selectTool("options", "toggle_settings_on");
    }

    // preventDefault will avoid a Linux only bug when the focus is on a text input
    // See Bug 1519087.
    event.preventDefault();
  },

  /**
   * Loads the tool next to the currently selected tool.
   */
  selectNextTool() {
    const definitions = this.component.panelDefinitions;
    const index = definitions.findIndex(({ id }) => id === this.currentToolId);
    const definition =
      index === -1 || index >= definitions.length - 1
        ? definitions[0]
        : definitions[index + 1];
    return this.selectTool(definition.id, "select_next_key");
  },

  /**
   * Loads the tool just left to the currently selected tool.
   */
  selectPreviousTool() {
    const definitions = this.component.panelDefinitions;
    const index = definitions.findIndex(({ id }) => id === this.currentToolId);
    const definition =
      index === -1 || index < 1
        ? definitions[definitions.length - 1]
        : definitions[index - 1];
    return this.selectTool(definition.id, "select_prev_key");
  },

  /**
   * Tells if the given tool is currently highlighted.
   * (doesn't mean selected, its tab header will be green)
   *
   * @param {string} id
   *        The id of the tool to check.
   */
  isHighlighted(id) {
    return this.component.state.highlightedTools.has(id);
  },

  /**
   * Highlights the tool's tab if it is not the currently selected tool.
   *
   * @param {string} id
   *        The id of the tool to highlight
   */
  async highlightTool(id) {
    if (!this.component) {
      await this.isOpen;
    }
    this.component.highlightTool(id);
  },

  /**
   * De-highlights the tool's tab.
   *
   * @param {string} id
   *        The id of the tool to unhighlight
   */
  async unhighlightTool(id) {
    if (!this.component) {
      await this.isOpen;
    }
    this.component.unhighlightTool(id);
  },

  /**
   * Raise the toolbox host.
   */
  raise() {
    this.postMessage({ name: "raise-host" });

    return this.once("host-raised");
  },

  /**
   * Fired when user just started navigating away to another web page.
   */
  async _onWillNavigate({ isFrameSwitching } = {}) {
    // On navigate, the server will resume all paused threads, but due to an
    // issue which can cause loosing outgoing messages/RDP packets, the THREAD_STATE
    // resources for the resumed state might not get received. So let assume it happens
    // make use the UI is the appropriate state.
    if (this._pausedTargets > 0) {
      this.emit("toolbox-resumed");
      this._pausedTargets = 0;
      if (this.isHighlighted("jsdebugger")) {
        this.unhighlightTool("jsdebugger");
      }
    }

    // Clearing the error count and the iframe list as soon as we navigate
    this.setErrorCount(0);
    if (!isFrameSwitching) {
      this._updateFrames({ destroyAll: true });
    }
    this.updateToolboxButtons();
    const toolId = this.currentToolId;
    // For now, only inspector, webconsole, netmonitor and accessibility fire "reloaded" event
    if (
      toolId != "inspector" &&
      toolId != "webconsole" &&
      toolId != "netmonitor" &&
      toolId != "accessibility"
    ) {
      return;
    }

    const start = this.win.performance.now();
    const panel = this.getPanel(toolId);
    // Ignore the timing if the panel is still loading
    if (!panel) {
      return;
    }

    await panel.once("reloaded");
    // The toolbox may have been destroyed while the panel was reloading
    if (this.isDestroying()) {
      return;
    }
    const delay = this.win.performance.now() - start;

    const telemetryKey = "DEVTOOLS_TOOLBOX_PAGE_RELOAD_DELAY_MS";
    this.telemetry.getKeyedHistogramById(telemetryKey).add(toolId, delay);
  },

  /**
   * Refresh the host's title.
   */
  _refreshHostTitle() {
    let title;

    if (this.target.isXpcShellTarget) {
      // This will only be displayed for local development and can remain
      // hardcoded in english.
      title = "XPCShell Toolbox";
    } else if (this.isMultiProcessBrowserToolbox) {
      const scope = Services.prefs.getCharPref(BROWSERTOOLBOX_SCOPE_PREF);
      if (scope == BROWSERTOOLBOX_SCOPE_EVERYTHING) {
        title = L10N.getStr("toolbox.multiProcessBrowserToolboxTitle");
      } else if (scope == BROWSERTOOLBOX_SCOPE_PARENTPROCESS) {
        title = L10N.getStr("toolbox.parentProcessBrowserToolboxTitle");
      } else {
        throw new Error("Unsupported scope: " + scope);
      }
    } else if (this.target.name && this.target.name != this.target.url) {
      const url = this.target.isWebExtension
        ? this.target.getExtensionPathName(this.target.url)
        : getUnicodeUrl(this.target.url);
      title = L10N.getFormatStr(
        "toolbox.titleTemplate2",
        this.target.name,
        url
      );
    } else {
      title = L10N.getFormatStr(
        "toolbox.titleTemplate1",
        getUnicodeUrl(this.target.url)
      );
    }
    this.postMessage({
      name: "set-host-title",
      title,
    });
  },

  /**
   * Returns an instance of the preference actor. This is a lazily initialized root
   * actor that persists preferences to the debuggee, instead of just to the DevTools
   * client. See the definition of the preference actor for more information.
   */
  get preferenceFront() {
    if (!this._preferenceFrontRequest) {
      // Set the _preferenceFrontRequest property to allow the resetPreference toolbox
      // method to cleanup the preference set when the toolbox is closed.
      this._preferenceFrontRequest =
        this.commands.client.mainRoot.getFront("preference");
    }
    return this._preferenceFrontRequest;
  },

  /**
   * See: https://firefox-source-docs.mozilla.org/l10n/fluent/tutorial.html#manually-testing-ui-with-pseudolocalization
   *
   * @param {"bidi" | "accented" | "none"} pseudoLocale
   */
  async changePseudoLocale(pseudoLocale) {
    await this.isOpen;
    const prefFront = await this.preferenceFront;
    if (pseudoLocale === "none") {
      await prefFront.clearUserPref(PSEUDO_LOCALE_PREF);
    } else {
      await prefFront.setCharPref(PSEUDO_LOCALE_PREF, pseudoLocale);
    }
    this.component.setPseudoLocale(pseudoLocale);
    this._pseudoLocaleChanged = true;
  },

  /**
   * Returns the pseudo-locale when the target is browser chrome, otherwise undefined.
   *
   * @returns {"bidi" | "accented" | "none" | undefined}
   */
  async getPseudoLocale() {
    if (!this.isBrowserToolbox) {
      return undefined;
    }

    const prefFront = await this.preferenceFront;
    const locale = await prefFront.getCharPref(PSEUDO_LOCALE_PREF);

    switch (locale) {
      case "bidi":
      case "accented":
        return locale;
      default:
        return "none";
    }
  },

  async toggleNoAutohide() {
    const front = await this.preferenceFront;

    const toggledValue = !(await this._isDisableAutohideEnabled());

    front.setBoolPref(DISABLE_AUTOHIDE_PREF, toggledValue);

    if (
      this.isBrowserToolbox ||
      this._descriptorFront.isWebExtensionDescriptor
    ) {
      this.component.setDisableAutohide(toggledValue);
    }
    this._autohideHasBeenToggled = true;
  },

  /**
   * Toggling "always on top" behavior is a bit special.
   *
   * We toggle the preference and then destroy and re-create the toolbox
   * as there is no way to change this behavior on an existing window
   * (see bug 1788946).
   */
  async toggleAlwaysOnTop() {
    const currentValue = Services.prefs.getBoolPref(
      DEVTOOLS_ALWAYS_ON_TOP,
      false
    );
    Services.prefs.setBoolPref(DEVTOOLS_ALWAYS_ON_TOP, !currentValue);

    const addonId = this._descriptorFront.id;
    await this.destroy();
    gDevTools.showToolboxForWebExtension(addonId);
  },

  async _isDisableAutohideEnabled() {
    if (
      !this.isBrowserToolbox &&
      !this._descriptorFront.isWebExtensionDescriptor
    ) {
      return false;
    }

    const prefFront = await this.preferenceFront;
    return prefFront.getBoolPref(DISABLE_AUTOHIDE_PREF);
  },

  async _listFrames() {
    if (
      !this.target.getTrait("frames") ||
      this.target.targetForm.ignoreSubFrames
    ) {
      // We are not targetting a regular WindowGlobalTargetActor (it can be either an
      // addon or browser toolbox actor), or EFT is enabled.
      return;
    }

    try {
      const { frames } = await this.target.listFrames();
      this._updateFrames({ frames });
    } catch (e) {
      console.error("Error while listing frames", e);
    }
  },

  /**
   * Called by the iframe picker when the user selected a frame.
   *
   * @param {String} frameIdOrTargetActorId
   */
  onIframePickerFrameSelected(frameIdOrTargetActorId) {
    if (!this.frameMap.has(frameIdOrTargetActorId)) {
      console.error(
        `Can't focus on frame "${frameIdOrTargetActorId}", it is not a known frame`
      );
      return;
    }

    const frameInfo = this.frameMap.get(frameIdOrTargetActorId);
    // If there is no targetFront in the frameData, this means EFT is not enabled.
    // Send packet to the backend to select specified frame and  wait for 'frameUpdate'
    // event packet to update the UI.
    if (!frameInfo.targetFront) {
      this.target.switchToFrame({ windowId: frameIdOrTargetActorId });
      return;
    }

    // Here, EFT is enabled, so we want to focus the toolbox on the specific targetFront
    // that was selected by the user. This will trigger this._onTargetSelected which will
    // take care of updating the iframe picker state.
    this.commands.targetCommand.selectTarget(frameInfo.targetFront);
  },

  /**
   * Highlight a frame in the page
   *
   * @param {String} frameIdOrTargetActorId
   */
  async onHighlightFrame(frameIdOrTargetActorId) {
    // Only enable frame highlighting when the top level document is targeted
    if (!this.rootFrameSelected) {
      return null;
    }

    const frameInfo = this.frameMap.get(frameIdOrTargetActorId);
    if (!frameInfo) {
      return null;
    }

    let nodeFront;
    if (frameInfo.targetFront) {
      const inspectorFront = await frameInfo.targetFront.getFront("inspector");
      nodeFront = await inspectorFront.walker.documentElement();
    } else {
      const inspectorFront = await this.target.getFront("inspector");
      nodeFront = await inspectorFront.walker.getNodeActorFromWindowID(
        frameIdOrTargetActorId
      );
    }
    const highlighter = this.getHighlighter();
    return highlighter.highlight(nodeFront);
  },

  /**
   * Handles changes in document frames.
   *
   * @param {Object} data
   * @param {Boolean} data.destroyAll: All frames have been destroyed.
   * @param {Number} data.selected: A frame has been selected
   * @param {Object} data.frameData: Some frame data were updated
   * @param {String} data.frameData.url: new frame URL (it might have been blank or about:blank)
   * @param {String} data.frameData.title: new frame title
   * @param {Number|String} data.frameData.id: frame ID / targetFront actorID when EFT is enabled.
   * @param {Array<Object>} data.frames: List of frames. Every frame can have:
   * @param {Number|String} data.frames[].id: frame ID / targetFront actorID when EFT is enabled.
   * @param {String} data.frames[].url: frame URL
   * @param {String} data.frames[].title: frame title
   * @param {Boolean} data.frames[].destroy: Set to true if destroyed
   * @param {Boolean} data.frames[].isTopLevel: true for top level window
   */
  _updateFrames(data) {
    // At the moment, frames `id` can either be outerWindowID (a Number),
    // or a targetActorID (a String).
    // In order to have the same type of data as a key of `frameMap`, we transform any
    // outerWindowID into a string.
    // This can be removed once EFT is enabled by default
    if (data.selected) {
      data.selected = data.selected.toString();
    } else if (data.frameData) {
      data.frameData.id = data.frameData.id.toString();
    } else if (data.frames) {
      data.frames.forEach(frame => {
        if (frame.id) {
          frame.id = frame.id.toString();
        }
      });
    }

    // Store (synchronize) data about all existing frames on the backend
    if (data.destroyAll) {
      this.frameMap.clear();
      this.selectedFrameId = null;
    } else if (data.selected) {
      // If we select the top level target, default back to no particular selected document.
      if (data.selected == this.target.actorID) {
        this.selectedFrameId = null;
      } else {
        this.selectedFrameId = data.selected;
      }
    } else if (data.frameData && this.frameMap.has(data.frameData.id)) {
      const existingFrameData = this.frameMap.get(data.frameData.id);
      if (
        existingFrameData.title == data.frameData.title &&
        existingFrameData.url == data.frameData.url
      ) {
        return;
      }

      this.frameMap.set(data.frameData.id, {
        ...existingFrameData,
        url: data.frameData.url,
        title: data.frameData.title,
      });
    } else if (data.frames) {
      data.frames.forEach(frame => {
        if (frame.destroy) {
          this.frameMap.delete(frame.id);

          // Reset the currently selected frame if it's destroyed.
          if (this.selectedFrameId == frame.id) {
            this.selectedFrameId = null;
          }
        } else {
          this.frameMap.set(frame.id, frame);
        }
      });
    }

    // If there is no selected frame select the first top level
    // frame by default. Note that there might be more top level
    // frames in case of the BrowserToolbox.
    if (!this.selectedFrameId) {
      const frames = [...this.frameMap.values()];
      const topFrames = frames.filter(frame => frame.isTopLevel);
      this.selectedFrameId = topFrames.length ? topFrames[0].id : null;
    }

    // Debounce the update to avoid unnecessary flickering/rendering.
    if (!this.debouncedToolbarUpdate) {
      this.debouncedToolbarUpdate = debounce(
        () => {
          // Toolbox may have been destroyed in the meantime
          if (this.component) {
            this.component.setToolboxButtons(this.toolbarButtons);
          }
          this.debouncedToolbarUpdate = null;
        },
        200,
        this
      );
    }

    const updateUiElements = () => {
      // We may need to hide/show the frames button now.
      this.updateFrameButton();

      if (this.debouncedToolbarUpdate) {
        this.debouncedToolbarUpdate();
      }
    };

    // This may have been called before the toolbox is ready (= the dom elements for
    // the iframe picker don't exist yet).
    if (!this.isReady) {
      this.once("ready").then(() => updateUiElements);
    } else {
      updateUiElements();
    }
  },

  /**
   * Returns whether a root frame (with no parent frame) is selected.
   */
  get rootFrameSelected() {
    // If the frame switcher is disabled, we won't have a selected frame ID.
    // In this case, we're always showing the root frame.
    if (!this.selectedFrameId) {
      return true;
    }

    return this.frameMap.get(this.selectedFrameId).isTopLevel;
  },

  /**
   * Switch to the last used host for the toolbox UI.
   */
  switchToPreviousHost() {
    return this.switchHost("previous");
  },

  /**
   * Switch to a new host for the toolbox UI. E.g. bottom, sidebar, window,
   * and focus the window when done.
   *
   * @param {string} hostType
   *        The host type of the new host object
   */
  switchHost(hostType) {
    if (hostType == this.hostType || !this._descriptorFront.isLocalTab) {
      return null;
    }

    // chromeEventHandler will change after swapping hosts, remove events relying on it.
    this._removeChromeEventHandlerEvents();

    this.emit("host-will-change", hostType);

    // ToolboxHostManager is going to call swapFrameLoaders which mess up with
    // focus. We have to blur before calling it in order to be able to restore
    // the focus after, in _onSwitchedHost.
    this.focusTool(this.currentToolId, false);

    // Host code on the chrome side will send back a message once the host
    // switched
    this.postMessage({
      name: "switch-host",
      hostType,
    });

    return this.once("host-changed");
  },

  /**
   * Request to Firefox UI to move the toolbox to another tab.
   * This is used when we move a toolbox to a new popup opened by the tab we were currently debugging.
   * We also move the toolbox back to the original tab we were debugging if we select it via Firefox tabs.
   *
   * @param {String} tabBrowsingContextID
   *        The BrowsingContext ID of the tab we want to move to.
   * @returns {Promise<undefined>}
   *        This will resolve only once we moved to the new tab.
   */
  switchHostToTab(tabBrowsingContextID) {
    this.postMessage({
      name: "switch-host-to-tab",
      tabBrowsingContextID,
    });

    return this.once("switched-host-to-tab");
  },

  _onSwitchedHost({ hostType }) {
    this._hostType = hostType;

    this._buildDockOptions();

    // chromeEventHandler changed after swapping hosts, add again events relying on it.
    this._addChromeEventHandlerEvents();

    // We blurred the tools at start of switchHost, but also when clicking on
    // host switching button. We now have to restore the focus.
    this.focusTool(this.currentToolId, true);

    this.emit("host-changed");
    this.telemetry
      .getHistogramById(HOST_HISTOGRAM)
      .add(this._getTelemetryHostId());

    this.component.setCurrentHostType(hostType);
  },

  /**
   * Event handler fired when the toolbox was moved to another tab.
   * This fires when the toolbox itself requests to be moved to another tab,
   * but also when we select the original tab where the toolbox originally was.
   *
   * @param {String} browsingContextID
   *        The BrowsingContext ID of the tab the toolbox has been moved to.
   */
  _onSwitchedHostToTab(browsingContextID) {
    const targets = this.commands.targetCommand.getAllTargets([
      this.commands.targetCommand.TYPES.FRAME,
    ]);
    const target = targets.find(
      target => target.browsingContextID == browsingContextID
    );

    this.commands.targetCommand.selectTarget(target);

    this.emit("switched-host-to-tab");
  },

  /**
   * Test the availability of a tool (both globally registered tools and
   * additional tools registered to this toolbox) by tool id.
   *
   * @param  {string} toolId
   *         Id of the tool definition to search in the per-toolbox or globally
   *         registered tools.
   *
   * @returns {bool}
   *         Returns true if the tool is registered globally or on this toolbox.
   */
  isToolRegistered(toolId) {
    return !!this.getToolDefinition(toolId);
  },

  /**
   * Return the tool definition registered globally or additional tools registered
   * to this toolbox.
   *
   * @param  {string} toolId
   *         Id of the tool definition to retrieve for the per-toolbox and globally
   *         registered tools.
   *
   * @returns {object}
   *         The plain javascript object that represents the requested tool definition.
   */
  getToolDefinition(toolId) {
    return (
      gDevTools.getToolDefinition(toolId) ||
      this.additionalToolDefinitions.get(toolId)
    );
  },

  /**
   * Internal helper that removes a loaded tool from the toolbox,
   * it removes a loaded tool panel and tab from the toolbox without removing
   * its definition, so that it can still be listed in options and re-added later.
   *
   * @param  {string} toolId
   *         Id of the tool to be removed.
   */
  unloadTool(toolId) {
    if (typeof toolId != "string") {
      throw new Error("Unexpected non-string toolId received.");
    }

    if (this._toolPanels.has(toolId)) {
      const instance = this._toolPanels.get(toolId);
      instance.destroy();
      this._toolPanels.delete(toolId);
    }

    const panel = this.doc.getElementById("toolbox-panel-" + toolId);

    // Select another tool.
    if (this.currentToolId == toolId) {
      const index = this.panelDefinitions.findIndex(({ id }) => id === toolId);
      const nextTool = this.panelDefinitions[index + 1];
      const previousTool = this.panelDefinitions[index - 1];
      let toolNameToSelect;

      if (nextTool) {
        toolNameToSelect = nextTool.id;
      }
      if (previousTool) {
        toolNameToSelect = previousTool.id;
      }
      if (toolNameToSelect) {
        this.selectTool(toolNameToSelect, "tool_unloaded");
      }
    }

    // Remove this tool from the current panel definitions.
    this.panelDefinitions = this.panelDefinitions.filter(
      ({ id }) => id !== toolId
    );
    this.visibleAdditionalTools = this.visibleAdditionalTools.filter(
      id => id !== toolId
    );
    this._combineAndSortPanelDefinitions();

    if (panel) {
      panel.remove();
    }

    if (this.hostType == Toolbox.HostType.WINDOW) {
      const doc = this.win.parent.document;
      const key = doc.getElementById("key_" + toolId);
      if (key) {
        key.remove();
      }
    }
  },

  /**
   * Handler for the tool-registered event.
   * @param  {string} toolId
   *         Id of the tool that was registered
   */
  _toolRegistered(toolId) {
    // Tools can either be in the global devtools, or added to this specific toolbox
    // as an additional tool.
    let definition = gDevTools.getToolDefinition(toolId);
    let isAdditionalTool = false;
    if (!definition) {
      definition = this.additionalToolDefinitions.get(toolId);
      isAdditionalTool = true;
    }

    if (definition.isToolSupported(this)) {
      if (isAdditionalTool) {
        this.visibleAdditionalTools = [...this.visibleAdditionalTools, toolId];
        this._combineAndSortPanelDefinitions();
      } else {
        this.panelDefinitions = this.panelDefinitions.concat(definition);
      }
      this._buildPanelForTool(definition);

      // Emit the event so tools can listen to it from the toolbox level
      // instead of gDevTools.
      this.emit("tool-registered", toolId);
    }
  },

  /**
   * Handler for the tool-unregistered event.
   * @param  {string} toolId
   *         id of the tool that was unregistered
   */
  _toolUnregistered(toolId) {
    this.unloadTool(toolId);

    // Emit the event so tools can listen to it from the toolbox level
    // instead of gDevTools
    this.emit("tool-unregistered", toolId);
  },

  /**
   * A helper function that returns an object containing methods to show and hide the
   * Box Model Highlighter on a given NodeFront or node grip (object with metadata which
   * can be used to obtain a NodeFront for a node), as well as helpers to listen to the
   * higligher show and hide events. The event helpers are used in tests where it is
   * cumbersome to load the Inspector panel in order to listen to highlighter events.
   *
   * @returns {Object} an object of the following shape:
   *   - {AsyncFunction} highlight: A function that will show a Box Model Highlighter
   *                     for the provided NodeFront or node grip.
   *   - {AsyncFunction} unhighlight: A function that will hide any Box Model Highlighter
   *                     that is visible. If the `highlight` promise isn't settled yet,
   *                     it will wait until it's done and then unhighlight to prevent
   *                     zombie highlighters.
   *   - {AsyncFunction} waitForHighlighterShown: Returns a promise which resolves with
   *                     the "highlighter-shown" event data once the highlighter is shown.
   *   - {AsyncFunction} waitForHighlighterHidden: Returns a promise which resolves with
   *                     the "highlighter-hidden" event data once the highlighter is
   *                     hidden.
   *
   */
  getHighlighter() {
    let pendingHighlight;

    /**
     * Return a promise wich resolves with a reference to the Inspector panel.
     */
    const _getInspector = async () => {
      const inspector = this.getPanel("inspector");
      if (inspector) {
        return inspector;
      }

      return this.loadTool("inspector");
    };

    /**
     * Returns a promise which resolves when a Box Model Highlighter emits the given event
     *
     * @param  {String} eventName
     *         Name of the event to listen to.
     * @return {Promise}
     *         Promise which resolves when the highlighter event occurs.
     *         Resolves with the data payload attached to the event.
     */
    async function _waitForHighlighterEvent(eventName) {
      const inspector = await _getInspector();
      return new Promise(resolve => {
        function _handler(data) {
          if (data.type === inspector.highlighters.TYPES.BOXMODEL) {
            inspector.highlighters.off(eventName, _handler);
            resolve(data);
          }
        }

        inspector.highlighters.on(eventName, _handler);
      });
    }

    return {
      // highlight might be triggered right before a test finishes. Wrap it
      // with safeAsyncMethod to avoid intermittents.
      highlight: this._safeAsyncAfterDestroy(async (object, options) => {
        pendingHighlight = (async () => {
          let nodeFront = object;

          if (!(nodeFront instanceof NodeFront)) {
            const inspectorFront = await this.target.getFront("inspector");
            nodeFront = await inspectorFront.getNodeFrontFromNodeGrip(object);
          }

          if (!nodeFront) {
            return null;
          }

          const inspector = await _getInspector();
          return inspector.highlighters.showHighlighterTypeForNode(
            inspector.highlighters.TYPES.BOXMODEL,
            nodeFront,
            options
          );
        })();
        return pendingHighlight;
      }),
      unhighlight: this._safeAsyncAfterDestroy(async () => {
        if (pendingHighlight) {
          await pendingHighlight;
          pendingHighlight = null;
        }

        const inspector = await _getInspector();
        return inspector.highlighters.hideHighlighterType(
          inspector.highlighters.TYPES.BOXMODEL
        );
      }),

      waitForHighlighterShown: this._safeAsyncAfterDestroy(async () => {
        return _waitForHighlighterEvent("highlighter-shown");
      }),

      waitForHighlighterHidden: this._safeAsyncAfterDestroy(async () => {
        return _waitForHighlighterEvent("highlighter-hidden");
      }),
    };
  },

  /**
   * Shortcut to avoid throwing errors when an async method fails after toolbox
   * destroy. Should be used with methods that might be triggered by a user
   * input, regardless of the toolbox lifecycle.
   */
  _safeAsyncAfterDestroy(fn) {
    return safeAsyncMethod(fn, () => !!this._destroyer);
  },

  async _onNewSelectedNodeFront() {
    // Emit a "selection-changed" event when the toolbox.selection has been set
    // to a new node (or cleared). Currently used in the WebExtensions APIs (to
    // provide the `devtools.panels.elements.onSelectionChanged` event).
    this.emit("selection-changed");

    const targetFrontActorID = this.selection?.nodeFront?.targetFront?.actorID;
    if (targetFrontActorID) {
      this.selectTarget(targetFrontActorID);
    }
  },

  _onToolSelected() {
    this._refreshHostTitle();

    this.updatePickerButton();
    this.updateFrameButton();
    this.updateErrorCountButton();

    // Calling setToolboxButtons in case the visibility of a button changed.
    this.component.setToolboxButtons(this.toolbarButtons);
  },

  /**
   * Listener for "inspectObject" event on console top level target actor.
   */
  _onInspectObject(packet) {
    this.inspectObjectActor(packet.objectActor, packet.inspectFromAnnotation);
  },

  async inspectObjectActor(objectActor, inspectFromAnnotation) {
    const objectGrip = objectActor?.getGrip
      ? objectActor.getGrip()
      : objectActor;

    if (
      objectGrip.preview &&
      objectGrip.preview.nodeType === domNodeConstants.ELEMENT_NODE
    ) {
      await this.viewElementInInspector(objectGrip, inspectFromAnnotation);
      return;
    }

    if (objectGrip.class == "Function") {
      if (!objectGrip.location) {
        console.error("Missing location in Function objectGrip", objectGrip);
        return;
      }

      const { url, line, column } = objectGrip.location;
      await this.viewSourceInDebugger(url, line, column);
      return;
    }

    if (objectGrip.type !== "null" && objectGrip.type !== "undefined") {
      // Open then split console and inspect the object in the variables view,
      // when the objectActor doesn't represent an undefined or null value.
      if (this.currentToolId != "webconsole") {
        await this.openSplitConsole();
      }

      const panel = this.getPanel("webconsole");
      panel.hud.ui.inspectObjectActor(objectActor);
    }
  },

  /**
   * Get the toolbox's notification component
   *
   * @return The notification box component.
   */
  getNotificationBox() {
    return this.notificationBox;
  },

  async closeToolbox() {
    await this.destroy();
  },

  /**
   * Public API to check is the current toolbox is currently being destroyed.
   */
  isDestroying() {
    return this._destroyer;
  },

  /**
   * Remove all UI elements, detach from target and clear up
   */
  destroy() {
    // If several things call destroy then we give them all the same
    // destruction promise so we're sure to destroy only once
    if (this._destroyer) {
      return this._destroyer;
    }

    // This pattern allows to immediately return the destroyer promise.
    // See Bug 1602727 for more details.
    let destroyerResolve;
    this._destroyer = new Promise(r => (destroyerResolve = r));
    this._destroyToolbox().then(destroyerResolve);

    return this._destroyer;
  },

  async _destroyToolbox() {
    this.emit("destroy");

    // This flag will be checked by Fronts in order to decide if they should
    // skip their destroy.
    this.commands.client.isToolboxDestroy = true;

    this.off("select", this._onToolSelected);
    this.off("host-changed", this._refreshHostTitle);

    gDevTools.off("tool-registered", this._toolRegistered);
    gDevTools.off("tool-unregistered", this._toolUnregistered);

    for (const prefName in BOOLEAN_CONFIGURATION_PREFS) {
      Services.prefs.removeObserver(
        prefName,
        this._onBooleanConfigurationPrefChange
      );
    }
    Services.prefs.removeObserver(
      BROWSERTOOLBOX_SCOPE_PREF,
      this._refreshHostTitle
    );

    // We normally handle toolClosed from selectTool() but in the event of the
    // toolbox closing we need to handle it here instead.
    this.telemetry.toolClosed(this.currentToolId, this);

    this._lastFocusedElement = null;
    this._pausedTargets = null;

    if (this._sourceMapLoader) {
      this._sourceMapLoader.destroy();
      this._sourceMapLoader = null;
    }

    if (this._parserWorker) {
      this._parserWorker.stop();
      this._parserWorker = null;
    }

    if (this.webconsolePanel) {
      this._saveSplitConsoleHeight();
      this.webconsolePanel.removeEventListener(
        "resize",
        this._saveSplitConsoleHeight
      );
      this.webconsolePanel = null;
    }
    if (this._componentMount) {
      this._tabBar.removeEventListener(
        "keypress",
        this._onToolbarArrowKeypress
      );
      this.ReactDOM.unmountComponentAtNode(this._componentMount);
      this.component = null;
      this._componentMount = null;
      this._tabBar = null;
    }
    this.destroyHarAutomation();

    for (const [id, panel] of this._toolPanels) {
      try {
        gDevTools.emit(id + "-destroy", this, panel);
        this.emit(id + "-destroy", panel);

        const rv = panel.destroy();
        if (rv) {
          console.error(
            `Panel ${id}'s destroy method returned something whereas it shouldn't (and should be synchronous).`
          );
        }
      } catch (e) {
        // We don't want to stop here if any panel fail to close.
        console.error("Panel " + id + ":", e);
      }
    }

    this.browserRequire = null;
    this._toolNames = null;

    // Reset preferences set by the toolbox, then remove the preference front.
    const onResetPreference = this.resetPreference().then(() => {
      this._preferenceFrontRequest = null;
    });

    this.commands.targetCommand.unwatchTargets({
      types: this.commands.targetCommand.ALL_TYPES,
      onAvailable: this._onTargetAvailable,
      onSelected: this._onTargetSelected,
      onDestroyed: this._onTargetDestroyed,
    });

    const watchedResources = [
      this.resourceCommand.TYPES.CONSOLE_MESSAGE,
      this.resourceCommand.TYPES.ERROR_MESSAGE,
      this.resourceCommand.TYPES.DOCUMENT_EVENT,
      this.resourceCommand.TYPES.THREAD_STATE,
    ];

    if (!this.isBrowserToolbox) {
      watchedResources.push(this.resourceCommand.TYPES.NETWORK_EVENT);
    }

    this.resourceCommand.unwatchResources(watchedResources, {
      onAvailable: this._onResourceAvailable,
    });

    // Unregister buttons listeners
    this.toolbarButtons.forEach(button => {
      if (typeof button.teardown == "function") {
        // teardown arguments have already been bound in _createButtonState
        button.teardown();
      }
    });

    // We need to grab a reference to win before this._host is destroyed.
    const win = this.win;
    const host = this._getTelemetryHostString();
    const width = Math.ceil(win.outerWidth / 50) * 50;
    const prevPanelName = this.getTelemetryPanelNameOrOther(this.currentToolId);

    this.telemetry.toolClosed("toolbox", this);
    this.telemetry.recordEvent("exit", prevPanelName, null, {
      host,
      width,
      panel_name: this.getTelemetryPanelNameOrOther(this.currentToolId),
      next_panel: "none",
      reason: "toolbox_close",
    });
    this.telemetry.recordEvent("close", "tools", null, {
      host,
      width,
    });

    // Wait for the preferences to be reset before destroying the target descriptor (which will destroy the preference front)
    const onceDestroyed = new Promise(resolve => {
      resolve(
        onResetPreference
          .catch(console.error)
          .then(async () => {
            // Destroy the node picker *after* destroying the panel,
            // which may still try to access it. (And might spawn a new one)
            if (this._nodePicker) {
              this._nodePicker.destroy();
              this._nodePicker = null;
            }
            this.selection.destroy();
            this.selection = null;

            if (this._netMonitorAPI) {
              this._netMonitorAPI.destroy();
              this._netMonitorAPI = null;
            }

            if (this._sourceMapURLService) {
              await this._sourceMapURLService.waitForSourcesLoading();
              this._sourceMapURLService.destroy();
              this._sourceMapURLService = null;
            }

            this._removeWindowListeners();
            this._removeChromeEventHandlerEvents();

            this._store = null;

            // All Commands need to be destroyed.
            // This is done after other destruction tasks since it may tear down
            // fronts and the debugger transport which earlier destroy methods may
            // require to complete.
            // (i.e. avoid exceptions about closing connection with pending requests)
            //
            // For similar reasons, only destroy the TargetCommand after every
            // other outstanding cleanup is done. Destroying the target list
            // will lead to destroy frame targets which can temporarily make
            // some fronts unresponsive and block the cleanup.
            return this.commands.destroy();
          }, console.error)
          .then(() => {
            this.emit("destroyed");

            // Free _host after the call to destroyed in order to let a chance
            // to destroyed listeners to still query toolbox attributes
            this._host = null;
            this._win = null;
            this._toolPanels.clear();
            this._descriptorFront = null;
            this.resourceCommand = null;
            this.commands = null;

            // Force GC to prevent long GC pauses when running tests and to free up
            // memory in general when the toolbox is closed.
            if (flags.testing) {
              win.windowUtils.garbageCollect();
            }
          })
          .catch(console.error)
      );
    });

    const leakCheckObserver = ({ wrappedJSObject: barrier }) => {
      // Make the leak detector wait until this toolbox is properly destroyed.
      barrier.client.addBlocker(
        "DevTools: Wait until toolbox is destroyed",
        onceDestroyed
      );
    };

    const topic = "shutdown-leaks-before-check";
    Services.obs.addObserver(leakCheckObserver, topic);

    await onceDestroyed;

    Services.obs.removeObserver(leakCheckObserver, topic);
  },

  /**
   * Open the textbox context menu at given coordinates.
   * Panels in the toolbox can call this on contextmenu events with event.screenX/Y
   * instead of having to implement their own copy/paste/selectAll menu.
   * @param {Number} x
   * @param {Number} y
   */
  openTextBoxContextMenu(x, y) {
    const menu = createEditContextMenu(this.topWindow, "toolbox-menu");

    // Fire event for tests
    menu.once("open", () => this.emit("menu-open"));
    menu.once("close", () => this.emit("menu-close"));

    menu.popup(x, y, this.doc);
  },

  /**
   *  Retrieve the current textbox context menu, if available.
   */
  getTextBoxContextMenu() {
    return this.topDoc.getElementById("toolbox-menu");
  },

  /**
   * Reset preferences set by the toolbox.
   */
  async resetPreference() {
    if (
      // No preferences have been changed, so there is nothing to reset.
      !this._preferenceFrontRequest ||
      // Did any pertinent prefs actually change? For autohide and the pseudo-locale,
      // only reset prefs in the Browser Toolbox if it's been toggled in the UI
      // (don't reset the pref if it was already set before opening)
      (!this._autohideHasBeenToggled && !this._pseudoLocaleChanged)
    ) {
      return;
    }

    const preferenceFront = await this.preferenceFront;

    if (this._autohideHasBeenToggled) {
      await preferenceFront.clearUserPref(DISABLE_AUTOHIDE_PREF);
    }
    if (this._pseudoLocaleChanged) {
      await preferenceFront.clearUserPref(PSEUDO_LOCALE_PREF);
    }
  },

  // HAR Automation

  async initHarAutomation() {
    const autoExport = Services.prefs.getBoolPref(
      "devtools.netmonitor.har.enableAutoExportToFile"
    );
    if (autoExport) {
      this.harAutomation = new HarAutomation();
      await this.harAutomation.initialize(this);
    }
  },
  destroyHarAutomation() {
    if (this.harAutomation) {
      this.harAutomation.destroy();
    }
  },

  /**
   * Returns gViewSourceUtils for viewing source.
   */
  get gViewSourceUtils() {
    return this.win.gViewSourceUtils;
  },

  /**
   * Open a CSS file when there is no line or column information available.
   *
   * @param {string} url The URL of the CSS file to open.
   */
  async viewGeneratedSourceInStyleEditor(url) {
    if (typeof url !== "string") {
      console.warn("Failed to open generated source, no url given");
      return false;
    }

    // The style editor hides the generated file if the file has original
    // sources, so we have no choice but to open whichever original file
    // corresponds to the first line of the generated file.
    return viewSource.viewSourceInStyleEditor(this, url, 1);
  },

  /**
   * Given a URL for a stylesheet (generated or original), open in the style
   * editor if possible. Falls back to plain "view-source:".
   * If the stylesheet has a sourcemap, we will attempt to open the original
   * version of the file instead of the generated version.
   */
  async viewSourceInStyleEditorByURL(url, line, column) {
    if (typeof url !== "string") {
      console.warn("Failed to open source, no url given");
      return false;
    }
    if (typeof line !== "number") {
      console.warn(
        "No line given when navigating to source. If you're seeing this, there is a bug."
      );

      // This is a fallback in case of programming errors, but in a perfect
      // world, viewSourceInStyleEditorByURL would always get a line/colum.
      line = 1;
      column = null;
    }

    return viewSource.viewSourceInStyleEditor(this, url, line, column);
  },

  /**
   * Opens source in style editor. Falls back to plain "view-source:".
   * If the stylesheet has a sourcemap, we will attempt to open the original
   * version of the file instead of the generated version.
   */
  async viewSourceInStyleEditorByResource(stylesheetResource, line, column) {
    if (!stylesheetResource || typeof stylesheetResource !== "object") {
      console.warn("Failed to open source, no stylesheet given");
      return false;
    }
    if (typeof line !== "number") {
      console.warn(
        "No line given when navigating to source. If you're seeing this, there is a bug."
      );

      // This is a fallback in case of programming errors, but in a perfect
      // world, viewSourceInStyleEditorByResource would always get a line/colum.
      line = 1;
      column = null;
    }

    return viewSource.viewSourceInStyleEditor(
      this,
      stylesheetResource,
      line,
      column
    );
  },

  async viewElementInInspector(objectGrip, reason) {
    // Open the inspector and select the DOM Element.
    await this.loadTool("inspector");
    const inspector = this.getPanel("inspector");
    const nodeFound = await inspector.inspectNodeActor(objectGrip, reason);
    if (nodeFound) {
      await this.selectTool("inspector", reason);
    }
  },

  /**
   * Open a JS file when there is no line or column information available.
   *
   * @param {string} url The URL of the JS file to open.
   */
  async viewGeneratedSourceInDebugger(url) {
    if (typeof url !== "string") {
      console.warn("Failed to open generated source, no url given");
      return false;
    }

    return viewSource.viewSourceInDebugger(this, url, null, null, null, null);
  },

  /**
   * Opens source in debugger, the sourcemapped location will be selected in
   * the debugger panel, if the given location resolves to a know sourcemapped one.
   *
   * Falls back to plain "view-source:".
   *
   * @see devtools/client/shared/source-utils.js
   */
  async viewSourceInDebugger(
    sourceURL,
    sourceLine,
    sourceColumn,
    sourceId,
    reason
  ) {
    if (typeof sourceURL !== "string" && typeof sourceId !== "string") {
      console.warn("Failed to open generated source, no url/id given");
      return false;
    }
    if (typeof sourceLine !== "number") {
      console.warn(
        "No line given when navigating to source. If you're seeing this, there is a bug."
      );

      // This is a fallback in case of programming errors, but in a perfect
      // world, viewSourceInDebugger would always get a line/colum.
      sourceLine = 1;
      sourceColumn = null;
    }

    return viewSource.viewSourceInDebugger(
      this,
      sourceURL,
      sourceLine,
      sourceColumn,
      sourceId,
      reason
    );
  },

  /**
   * Opens source in plain "view-source:".
   * @see devtools/client/shared/source-utils.js
   */
  viewSource(sourceURL, sourceLine, sourceColumn) {
    return viewSource.viewSource(this, sourceURL, sourceLine, sourceColumn);
  },

  // Support for WebExtensions API (`devtools.network.*`)

  /**
   * Return Netmonitor API object. This object offers Network monitor
   * public API that can be consumed by other panels or WE API.
   */
  async getNetMonitorAPI() {
    const netPanel = this.getPanel("netmonitor");

    // Return Net panel if it exists.
    if (netPanel) {
      return netPanel.panelWin.Netmonitor.api;
    }

    if (this._netMonitorAPI) {
      return this._netMonitorAPI;
    }

    // Create and initialize Network monitor API object.
    // This object is only connected to the backend - not to the UI.
    this._netMonitorAPI = new NetMonitorAPI();
    await this._netMonitorAPI.connect(this);

    return this._netMonitorAPI;
  },

  /**
   * Returns data (HAR) collected by the Network panel.
   */
  async getHARFromNetMonitor() {
    const netMonitor = await this.getNetMonitorAPI();
    let har = await netMonitor.getHar();

    // Return default empty HAR file if needed.
    har = har || buildHarLog(Services.appinfo);

    // Return the log directly to be compatible with
    // Chrome WebExtension API.
    return har.log;
  },

  /**
   * Add listener for `onRequestFinished` events.
   *
   * @param {Object} listener
   *        The listener to be called it's expected to be
   *        a function that takes ({harEntry, requestId})
   *        as first argument.
   */
  async addRequestFinishedListener(listener) {
    const netMonitor = await this.getNetMonitorAPI();
    netMonitor.addRequestFinishedListener(listener);
  },

  async removeRequestFinishedListener(listener) {
    const netMonitor = await this.getNetMonitorAPI();
    netMonitor.removeRequestFinishedListener(listener);

    // Destroy Network monitor API object if the following is true:
    // 1) there is no listener
    // 2) the Net panel doesn't exist/use the API object (if the panel
    //    exists it's also responsible for destroying it,
    //    see `NetMonitorPanel.open` for more details)
    const netPanel = this.getPanel("netmonitor");
    const hasListeners = netMonitor.hasRequestFinishedListeners();
    if (this._netMonitorAPI && !hasListeners && !netPanel) {
      this._netMonitorAPI.destroy();
      this._netMonitorAPI = null;
    }
  },

  /**
   * Used to lazily fetch HTTP response content within
   * `onRequestFinished` event listener.
   *
   * @param {String} requestId
   *        Id of the request for which the response content
   *        should be fetched.
   */
  async fetchResponseContent(requestId) {
    const netMonitor = await this.getNetMonitorAPI();
    return netMonitor.fetchResponseContent(requestId);
  },

  // Support management of installed WebExtensions that provide a devtools_page.

  /**
   * List the subset of the active WebExtensions which have a devtools_page (used by
   * toolbox-options.js to create the list of the tools provided by the enabled
   * WebExtensions).
   * @see devtools/client/framework/toolbox-options.js
   */
  listWebExtensions() {
    // Return the array of the enabled webextensions (we can't use the prefs list here,
    // because some of them may be disabled by the Addon Manager and still have a devtools
    // preference).
    return Array.from(this._webExtensions).map(([uuid, { name, pref }]) => {
      return { uuid, name, pref };
    });
  },

  /**
   * Add a WebExtension to the list of the active extensions (given the extension UUID,
   * a unique id assigned to an extension when it is installed, and its name),
   * and emit a "webextension-registered" event to allow toolbox-options.js
   * to refresh the listed tools accordingly.
   * @see browser/components/extensions/ext-devtools.js
   */
  registerWebExtension(extensionUUID, { name, pref }) {
    // Ensure that an installed extension (active in the AddonManager) which
    // provides a devtools page is going to be listed in the toolbox options
    // (and refresh its name if it was already listed).
    this._webExtensions.set(extensionUUID, { name, pref });
    this.emit("webextension-registered", extensionUUID);
  },

  /**
   * Remove an active WebExtension from the list of the active extensions (given the
   * extension UUID, a unique id assigned to an extension when it is installed, and its
   * name), and emit a "webextension-unregistered" event to allow toolbox-options.js
   * to refresh the listed tools accordingly.
   * @see browser/components/extensions/ext-devtools.js
   */
  unregisterWebExtension(extensionUUID) {
    // Ensure that an extension that has been disabled/uninstalled from the AddonManager
    // is going to be removed from the toolbox options.
    this._webExtensions.delete(extensionUUID);
    this.emit("webextension-unregistered", extensionUUID);
  },

  /**
   * A helper function which returns true if the extension with the given UUID is listed
   * as active for the toolbox and has its related devtools about:config preference set
   * to true.
   * @see browser/components/extensions/ext-devtools.js
   */
  isWebExtensionEnabled(extensionUUID) {
    const extInfo = this._webExtensions.get(extensionUUID);
    return extInfo && Services.prefs.getBoolPref(extInfo.pref, false);
  },

  /**
   * Returns a panel id in the case of built in panels or "other" in the case of
   * third party panels. This is necessary due to limitations in addon id strings,
   * the permitted length of event telemetry property values and what we actually
   * want to see in our telemetry.
   *
   * @param {String} id
   *        The panel id we would like to process.
   */
  getTelemetryPanelNameOrOther(id) {
    if (!this._toolNames) {
      const definitions = gDevTools.getToolDefinitionArray();
      const definitionIds = definitions.map(definition => definition.id);

      this._toolNames = new Set(definitionIds);
    }

    if (!this._toolNames.has(id)) {
      return "other";
    }

    return id;
  },

  /**
   * Sets basic information on the DebugTargetInfo component
   */
  _setDebugTargetData() {
    // Note that local WebExtension are debugged via WINDOW host,
    // but we still want to display target data.
    if (
      this.hostType === Toolbox.HostType.PAGE ||
      this._descriptorFront.isWebExtensionDescriptor
    ) {
      // Displays DebugTargetInfo which shows the basic information of debug target,
      // if `about:devtools-toolbox` URL opens directly.
      // DebugTargetInfo requires this._debugTargetData to be populated
      this.component.setDebugTargetData(this._getDebugTargetData());
    }
  },

  _onResourceAvailable(resources) {
    let errors = this._errorCount || 0;

    const { TYPES } = this.resourceCommand;
    for (const resource of resources) {
      const { resourceType } = resource;
      if (
        resourceType === TYPES.ERROR_MESSAGE &&
        // ERROR_MESSAGE resources can be warnings/info, but here we only want to count errors
        resource.pageError.error
      ) {
        errors++;
        continue;
      }

      if (resourceType === TYPES.CONSOLE_MESSAGE) {
        const { level } = resource.message;
        if (level === "error" || level === "exception" || level === "assert") {
          errors++;
        }

        // Reset the count on console.clear
        if (level === "clear") {
          errors = 0;
        }
      }

      // Only consider top level document, and ignore remote iframes top document
      if (
        resourceType === TYPES.DOCUMENT_EVENT &&
        resource.name === "will-navigate" &&
        resource.targetFront.isTopLevel
      ) {
        this._onWillNavigate({
          isFrameSwitching: resource.isFrameSwitching,
        });
        // While we will call `setErrorCount(0)` from onWillNavigate, we also need to reset
        // `errors` local variable in order to clear previous errors processed in the same
        // throttling bucket as this will-navigate resource.
        errors = 0;
      }

      if (
        resourceType === TYPES.DOCUMENT_EVENT &&
        !resource.isFrameSwitching &&
        // `url` is set on the targetFront when we receive dom-loading, and `title` when
        // `dom-interactive` is received. Here we're only updating the window title in
        // the "newer" event.
        resource.name === "dom-interactive"
      ) {
        // the targetFront title and url are updated on dom-interactive, so delay refreshing
        // the host title a bit in order for the event listener in targetCommand to be
        // executed.
        setTimeout(() => {
          if (resource.targetFront.isDestroyed()) {
            // The resource's target might have been destroyed in between and
            // would no longer have a valid actorID available.
            return;
          }

          this._updateFrames({
            frameData: {
              id: resource.targetFront.actorID,
              url: resource.targetFront.url,
              title: resource.targetFront.title,
            },
          });

          if (resource.targetFront.isTopLevel) {
            this._refreshHostTitle();
            this._setDebugTargetData();
          }
        }, 0);
      }

      if (resourceType == TYPES.THREAD_STATE) {
        this._onThreadStateChanged(resource);
      }
      if (resourceType == TYPES.JSTRACER_STATE) {
        this._onTracingStateChanged(resource);
      }
    }

    this.setErrorCount(errors);
  },

  _onResourceUpdated(resources) {
    let errors = this._errorCount || 0;

    for (const { update } of resources) {
      // In order to match webconsole behaviour, we treat 4xx and 5xx network calls as errors.
      if (
        update.resourceType === this.resourceCommand.TYPES.NETWORK_EVENT &&
        update.resourceUpdates.status &&
        update.resourceUpdates.status.toString().match(REGEX_4XX_5XX)
      ) {
        errors++;
      }
    }

    this.setErrorCount(errors);
  },

  /**
   * Set the number of errors in the toolbar icon.
   *
   * @param {Number} count
   */
  setErrorCount(count) {
    // Don't re-render if the number of errors changed
    if (!this.component || this._errorCount === count) {
      return;
    }

    this._errorCount = count;

    // Update button properties and trigger a render of the toolbox
    this.updateErrorCountButton();
    this._throttledSetToolboxButtons();
  },
};