summaryrefslogtreecommitdiffstats
path: root/toolkit/components/printing/content/print.js
blob: d08d790522a35a3e17ab8903a00e126eaba32363 (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
/* 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/. */

const { PrintUtils, Services, AppConstants } =
  window.docShell.chromeEventHandler.ownerGlobal;

ChromeUtils.defineESModuleGetters(this, {
  DeferredTask: "resource://gre/modules/DeferredTask.sys.mjs",
  DownloadPaths: "resource://gre/modules/DownloadPaths.sys.mjs",
});

const PDF_JS_URI = "resource://pdf.js/web/viewer.html";
const INPUT_DELAY_MS = Cu.isInAutomation ? 100 : 500;
const MM_PER_POINT = 25.4 / 72;
const INCHES_PER_POINT = 1 / 72;
const INCHES_PER_MM = 1 / 25.4;
const ourBrowser = window.docShell.chromeEventHandler;
const PSSVC = Cc["@mozilla.org/gfx/printsettings-service;1"].getService(
  Ci.nsIPrintSettingsService
);

var logger = (function () {
  const getMaxLogLevel = () =>
    Services.prefs.getBoolPref("print.debug", false) ? "all" : "warn";

  let { ConsoleAPI } = ChromeUtils.importESModule(
    "resource://gre/modules/Console.sys.mjs"
  );
  // Create a new instance of the ConsoleAPI so we can control the maxLogLevel with a pref.
  let _logger = new ConsoleAPI({
    prefix: "printUI",
    maxLogLevel: getMaxLogLevel(),
  });

  function onPrefChange() {
    if (_logger) {
      _logger.maxLogLevel = getMaxLogLevel();
    }
  }
  // Watch for pref changes and the maxLogLevel for the logger
  Services.prefs.addObserver("print.debug", onPrefChange);
  window.addEventListener("unload", () => {
    Services.prefs.removeObserver("print.debug", onPrefChange);
  });
  return _logger;
})();

function serializeSettings(settings, logPrefix) {
  let re = /^(k[A-Z]|resolution)/; // accessing settings.resolution throws an exception?
  let types = new Set(["string", "boolean", "number", "undefined"]);
  let nameValues = {};
  for (let key in settings) {
    try {
      if (!re.test(key) && types.has(typeof settings[key])) {
        nameValues[key] = settings[key];
      }
    } catch (e) {
      logger.warn("Exception accessing setting: ", key, e);
    }
  }
  return JSON.stringify(nameValues, null, 2);
}

let printPending = false;
let deferredTasks = [];
function createDeferredTask(fn, timeout) {
  let task = new DeferredTask(fn, timeout);
  deferredTasks.push(task);
  return task;
}

function cancelDeferredTasks() {
  for (let task of deferredTasks) {
    task.disarm();
  }
  PrintEventHandler._updatePrintPreviewTask?.disarm();
  deferredTasks = [];
}

document.addEventListener(
  "DOMContentLoaded",
  e => {
    window._initialized = PrintEventHandler.init().catch(e => console.error(e));
    ourBrowser.setAttribute("flex", "0");
    ourBrowser.setAttribute("constrainpopups", "false");
    ourBrowser.classList.add("printSettingsBrowser");
    ourBrowser.closest(".dialogBox")?.classList.add("printDialogBox");
  },
  { once: true }
);

window.addEventListener("dialogclosing", () => {
  cancelDeferredTasks();
});

window.addEventListener(
  "unload",
  e => {
    document.textContent = "";
  },
  { once: true }
);

var PrintEventHandler = {
  settings: null,
  defaultSettings: null,
  allPaperSizes: {},
  previewIsEmpty: false,
  _delayedChanges: {},
  _userChangedSettings: {},
  settingFlags: {
    margins: Ci.nsIPrintSettings.kInitSaveMargins,
    customMargins: Ci.nsIPrintSettings.kInitSaveMargins,
    orientation: Ci.nsIPrintSettings.kInitSaveOrientation,
    paperId:
      Ci.nsIPrintSettings.kInitSavePaperSize |
      Ci.nsIPrintSettings.kInitSaveUnwriteableMargins,
    printInColor: Ci.nsIPrintSettings.kInitSaveInColor,
    scaling: Ci.nsIPrintSettings.kInitSaveScaling,
    shrinkToFit: Ci.nsIPrintSettings.kInitSaveShrinkToFit,
    printDuplex: Ci.nsIPrintSettings.kInitSaveDuplex,
    printFootersHeaders:
      Ci.nsIPrintSettings.kInitSaveHeaderLeft |
      Ci.nsIPrintSettings.kInitSaveHeaderCenter |
      Ci.nsIPrintSettings.kInitSaveHeaderRight |
      Ci.nsIPrintSettings.kInitSaveFooterLeft |
      Ci.nsIPrintSettings.kInitSaveFooterCenter |
      Ci.nsIPrintSettings.kInitSaveFooterRight,
    printBackgrounds:
      Ci.nsIPrintSettings.kInitSaveBGColors |
      Ci.nsIPrintSettings.kInitSaveBGImages,
  },

  topContentTitle: null,
  topCurrentURI: null,
  activeContentTitle: null,
  activeCurrentURI: null,

  get activeURI() {
    return this.viewSettings.sourceVersion == "selection"
      ? this.activeCurrentURI
      : this.topCurrentURI;
  },
  get activeTitle() {
    return this.viewSettings.sourceVersion == "selection"
      ? this.activeContentTitle
      : this.topContentTitle;
  },

  // These settings do not have an associated pref value or flag, but
  // changing them requires us to update the print preview.
  _nonFlaggedUpdatePreviewSettings: new Set([
    "pageRanges",
    "numPagesPerSheet",
    "sourceVersion",
  ]),
  _noPreviewUpdateSettings: new Set(["numCopies", "printDuplex"]),

  async init() {
    Services.telemetry.scalarAdd("printing.preview_opened_tm", 1);

    this.printPreviewEl =
      ourBrowser.parentElement.querySelector("print-preview");

    // Do not keep a reference to source browser, it may mutate after printing
    // is initiated and the print preview clone must be a snapshot from the
    // time that the print was started.
    let sourceBrowsingContext = this.printPreviewEl.getSourceBrowsingContext();

    let args = window.arguments[0];
    this.printFrameOnly = args.getProperty("printFrameOnly");
    this.printSelectionOnly = args.getProperty("printSelectionOnly");
    this.isArticle = args.getProperty("isArticle");
    this.hasSelection = await PrintUtils.checkForSelection(
      sourceBrowsingContext
    );

    let sourcePrincipal =
      sourceBrowsingContext.currentWindowGlobal.documentPrincipal;
    let sourceIsPdf =
      !sourcePrincipal.isNullPrincipal && sourcePrincipal.spec == PDF_JS_URI;
    this.activeContentTitle =
      sourceBrowsingContext.currentWindowContext.documentTitle;
    this.activeCurrentURI =
      sourceBrowsingContext.currentWindowContext.documentURI.spec;
    let topWindowContext = sourceBrowsingContext.top.currentWindowContext;
    this.topContentTitle = topWindowContext.documentTitle;
    this.topCurrentURI = topWindowContext.documentURI.spec;
    this.isReader = this.topCurrentURI.startsWith("about:reader");

    let canSimplify = !this.isReader && this.isArticle;
    if (!this.hasSelection && !canSimplify) {
      document.getElementById("source-version-section").hidden = true;
    } else {
      document.getElementById("source-version-selection").hidden =
        !this.hasSelection;
      document.getElementById("source-version-simplified").hidden =
        !canSimplify;
    }

    // We don't need the sourceBrowsingContext anymore, get rid of it.
    sourceBrowsingContext = undefined;

    this.printProgressIndicator = document.getElementById("print-progress");
    this.printForm = document.getElementById("print");
    if (sourceIsPdf) {
      this.printForm.removeNonPdfSettings();
    }

    // Let the dialog appear before doing any potential main thread work.
    await ourBrowser._dialogReady;

    // First check the available destinations to ensure we get settings for an
    // accessible printer.
    let destinations,
      defaultSystemPrinter,
      fallbackPaperList,
      selectedPrinter,
      printersByName;
    try {
      ({
        destinations,
        defaultSystemPrinter,
        fallbackPaperList,
        selectedPrinter,
        printersByName,
      } = await this.getPrintDestinations());
    } catch (e) {
      this.reportPrintingError("PRINT_DESTINATIONS");
      throw e;
    }
    PrintSettingsViewProxy.availablePrinters = printersByName;
    PrintSettingsViewProxy.fallbackPaperList = fallbackPaperList;
    PrintSettingsViewProxy.defaultSystemPrinter = defaultSystemPrinter;
    PrintSettingsViewProxy._sourceVersion =
      this.hasSelection && this.printSelectionOnly ? "selection" : "source";

    logger.debug("availablePrinters: ", Object.keys(printersByName));
    logger.debug("defaultSystemPrinter: ", defaultSystemPrinter);

    document.addEventListener("print", async () => {
      let cancelButton = document.getElementById("cancel-button");
      document.l10n.setAttributes(
        cancelButton,
        cancelButton.dataset.closeL10nId
      );
      let didPrint = await this.print();
      if (!didPrint) {
        // Re-enable elements of the form if the user cancels saving or
        // if a deferred task rendered the page invalid.
        this.printForm.enable();
      }
      // Reset the cancel button regardless of the outcome.
      document.l10n.setAttributes(
        cancelButton,
        cancelButton.dataset.cancelL10nId
      );
    });
    this._createDelayedSettingsChangeTask();
    document.addEventListener("update-print-settings", e => {
      this.handleSettingsChange(e.detail);
    });
    document.addEventListener("cancel-print-settings", e => {
      this._delayedSettingsChangeTask.disarm();
      for (let setting of Object.keys(e.detail)) {
        delete this._delayedChanges[setting];
      }
    });
    document.addEventListener("cancel-print", () => this.cancelPrint());
    document.addEventListener("open-system-dialog", async () => {
      // This file in only used if pref print.always_print_silent is false, so
      // no need to check that here.

      // Hide the dialog box before opening system dialog
      // We cannot close the window yet because the browsing context for the
      // print preview browser is needed to print the page.
      let sourceBrowser =
        this.printPreviewEl.getSourceBrowsingContext().top.embedderElement;
      let dialogBoxManager =
        PrintUtils.getTabDialogBox(sourceBrowser).getTabDialogManager();
      dialogBoxManager.hideDialog(sourceBrowser);

      // Use our settings to prepopulate the system dialog.
      // The system print dialog won't recognize our internal save-to-pdf
      // pseudo-printer.  We need to pass it a settings object from any
      // system recognized printer.
      let settings =
        this.settings.printerName == PrintUtils.SAVE_TO_PDF_PRINTER
          ? PrintUtils.getPrintSettings(this.viewSettings.defaultSystemPrinter)
          : this.settings.clone();
      // We set the title so that if the user chooses save-to-PDF from the
      // system dialog the title will be used to generate the prepopulated
      // filename in the file picker.
      settings.title = this.activeTitle;
      Services.telemetry.scalarAdd("printing.dialog_opened_via_preview_tm", 1);
      const doPrint = await this._showPrintDialog(
        window,
        this.hasSelection,
        settings
      );
      if (!doPrint) {
        Services.telemetry.scalarAdd(
          "printing.dialog_via_preview_cancelled_tm",
          1
        );
        window.close();
        return;
      }
      await this.print(settings);
    });

    let originalError;
    const printersByPriority = [
      selectedPrinter.value,
      ...Object.getOwnPropertyNames(printersByName).filter(
        name => name != selectedPrinter.value
      ),
    ];

    // Try to update settings, falling back to any available printer
    for (const printerName of printersByPriority) {
      try {
        let settingsToChange = await this.refreshSettings(printerName);
        await this.updateSettings(settingsToChange, true);
        originalError = null;
        break;
      } catch (e) {
        if (!originalError) {
          originalError = e;
          // Report on how often fetching the last used printer settings fails.
          this.reportPrintingError("PRINTER_SETTINGS_LAST_USED");
        }
      }
    }

    // Only throw original error if no fallback was possible
    if (originalError) {
      this.reportPrintingError("PRINTER_SETTINGS");
      throw originalError;
    }

    let initialPreviewDone = this._updatePrintPreview();

    // Use a DeferredTask for updating the preview. This will ensure that we
    // only have one update running at a time.
    this._createUpdatePrintPreviewTask(initialPreviewDone);

    document.dispatchEvent(
      new CustomEvent("available-destinations", {
        detail: destinations,
      })
    );

    document.dispatchEvent(
      new CustomEvent("print-settings", {
        detail: this.viewSettings,
      })
    );

    document.body.removeAttribute("loading");

    await new Promise(resolve => window.requestAnimationFrame(resolve));

    // Now that we're showing the form, select the destination select.
    document.getElementById("printer-picker").focus({ focusVisible: true });

    await initialPreviewDone;
  },

  async print(systemDialogSettings) {
    // Disable the form when a print is in progress
    this.printForm.disable();

    if (Object.keys(this._delayedChanges).length) {
      // Make sure any pending changes get saved.
      let task = this._delayedSettingsChangeTask;
      this._createDelayedSettingsChangeTask();
      await task.finalize();
    }

    if (this.settings.pageRanges.length) {
      // Finish any running previews to verify the range is still valid.
      let task = this._updatePrintPreviewTask;
      this._createUpdatePrintPreviewTask();
      await task.finalize();
    }

    if (!this.printForm.checkValidity() || this.previewIsEmpty) {
      return false;
    }

    let settings = systemDialogSettings || this.settings;

    if (settings.printerName == PrintUtils.SAVE_TO_PDF_PRINTER) {
      try {
        settings.toFileName = await pickFileName(
          this.activeTitle,
          this.activeURI
        );
      } catch (e) {
        return false;
      }
    }

    await window._initialized;

    // This seems like it should be handled automatically but it isn't.
    PSSVC.maybeSaveLastUsedPrinterNameToPrefs(settings.printerName);

    try {
      // We'll provide our own progress indicator.
      let l10nId =
        settings.printerName == PrintUtils.SAVE_TO_PDF_PRINTER
          ? "printui-print-progress-indicator-saving"
          : "printui-print-progress-indicator";
      document.l10n.setAttributes(this.printProgressIndicator, l10nId);
      this.printProgressIndicator.hidden = false;
      let bc = this.printPreviewEl.currentBrowsingContext;
      await this._doPrint(bc, settings);
    } catch (e) {
      console.error(e);
    }

    if (settings.printerName == PrintUtils.SAVE_TO_PDF_PRINTER) {
      // Clear the file name from the preference value since it may potentially
      // contain sensitive information from the page title (Bug 1675965)
      let prefName =
        "print.printer_" +
        settings.printerName.replace(/ /g, "_") +
        ".print_to_filename";
      Services.prefs.clearUserPref(prefName);
    }

    window.close();
    return true;
  },

  /**
   * Prints the window. This method has been abstracted into a helper for
   * testing purposes.
   */
  _doPrint(aBrowsingContext, aSettings) {
    return aBrowsingContext.print(aSettings);
  },

  cancelPrint() {
    Services.telemetry.scalarAdd("printing.preview_cancelled_tm", 1);
    window.close();
  },

  async refreshSettings(printerName) {
    this.currentPrinterName = printerName;
    let currentPrinter;
    try {
      currentPrinter = await PrintSettingsViewProxy.resolvePropertiesForPrinter(
        printerName
      );
    } catch (e) {
      this.reportPrintingError("PRINTER_PROPERTIES");
      throw e;
    }
    if (this.currentPrinterName != printerName) {
      // Refresh settings could take a while, if the destination has changed
      // then we don't want to update the settings after all.
      return {};
    }

    this.settings = currentPrinter.settings;
    this.defaultSettings = currentPrinter.defaultSettings;

    this.settings.printSelectionOnly = this.printSelectionOnly;

    logger.debug("currentPrinter name: ", printerName);
    logger.debug("settings:", serializeSettings(this.settings));

    // Some settings are only used by the UI
    // assigning new values should update the underlying settings
    this.viewSettings = new Proxy(this.settings, PrintSettingsViewProxy);
    return this.getSettingsToUpdate();
  },

  getSettingsToUpdate() {
    // Get the previously-changed settings we want to try to use on this printer
    let settingsToUpdate = Object.assign({}, this._userChangedSettings);

    // Ensure the color option is correct, if either of the supportsX flags are
    // false then the user cannot change the value through the UI.
    if (!this.viewSettings.supportsColor) {
      settingsToUpdate.printInColor = false;
    } else if (!this.viewSettings.supportsMonochrome) {
      settingsToUpdate.printInColor = true;
    }

    if (settingsToUpdate.sourceVersion == "simplified") {
      if (this.viewSettings.printBackgrounds) {
        // Remember that this was true before so it gets restored if the
        // format is changed to something else.
        this._userChangedSettings.printBackgrounds = true;
      }
      // Backgrounds are removed in simplified mode and this setting changes
      // the output subtly to be less legible.
      settingsToUpdate.printBackgrounds = false;
    }

    if (
      settingsToUpdate.printInColor != this._userChangedSettings.printInColor
    ) {
      delete this._userChangedSettings.printInColor;
    }

    // See if the paperId needs to change.
    let paperId = settingsToUpdate.paperId || this.viewSettings.paperId;

    logger.debug("Using paperId: ", paperId);
    logger.debug(
      "Available paper sizes: ",
      PrintSettingsViewProxy.availablePaperSizes
    );
    let matchedPaper =
      paperId && PrintSettingsViewProxy.availablePaperSizes[paperId];
    if (!matchedPaper) {
      let paperWidth, paperHeight, paperSizeUnit;
      if (settingsToUpdate.paperId) {
        // The user changed paperId in this instance and session,
        // We should have details on the paper size from the previous printer
        paperId = settingsToUpdate.paperId;
        let cachedPaperWrapper = this.allPaperSizes[paperId];
        // for the purposes of finding a best-size match, we'll use mm
        paperWidth = cachedPaperWrapper.paper.width * MM_PER_POINT;
        paperHeight = cachedPaperWrapper.paper.height * MM_PER_POINT;
        paperSizeUnit = PrintEventHandler.settings.kPaperSizeMillimeters;
      } else {
        paperId = this.viewSettings.paperId;
        logger.debug(
          "No paperId or matchedPaper, get a new default from viewSettings:",
          paperId
        );
        paperWidth = this.viewSettings.paperWidth;
        paperHeight = this.viewSettings.paperHeight;
        paperSizeUnit = this.viewSettings.paperSizeUnit;
      }
      matchedPaper = PrintSettingsViewProxy.getBestPaperMatch(
        paperWidth,
        paperHeight,
        paperSizeUnit
      );
    }
    if (!matchedPaper) {
      // We didn't find a good match. Take the first paper size
      matchedPaper = Object.values(
        PrintSettingsViewProxy.availablePaperSizes
      )[0];
      delete this._userChangedSettings.paperId;
    }
    if (matchedPaper.id !== paperId) {
      // The exact paper id doesn't exist for this printer
      logger.log(
        `Requested paperId: "${paperId}" missing on this printer, using: ${matchedPaper.id} instead`
      );
      delete this._userChangedSettings.paperId;
    }
    // Always write paper details back to settings
    settingsToUpdate.paperId = matchedPaper.id;

    return settingsToUpdate;
  },

  _createDelayedSettingsChangeTask() {
    this._delayedSettingsChangeTask = createDeferredTask(async () => {
      if (Object.keys(this._delayedChanges).length) {
        let changes = this._delayedChanges;
        this._delayedChanges = {};
        await this.onUserSettingsChange(changes);
      }
    }, INPUT_DELAY_MS);
  },

  _createUpdatePrintPreviewTask(initialPreviewDone = null) {
    this._updatePrintPreviewTask = new DeferredTask(async () => {
      await initialPreviewDone;
      await this._updatePrintPreview();
      document.dispatchEvent(new CustomEvent("preview-updated"));
    }, 0);
  },

  _scheduleDelayedSettingsChange(changes) {
    Object.assign(this._delayedChanges, changes);
    this._delayedSettingsChangeTask.disarm();
    this._delayedSettingsChangeTask.arm();
  },

  handleSettingsChange(changedSettings = {}) {
    let delayedChanges = {};
    let instantChanges = {};
    for (let [setting, value] of Object.entries(changedSettings)) {
      switch (setting) {
        case "pageRanges":
        case "scaling":
          delayedChanges[setting] = value;
          break;
        case "customMargins":
          delete this._delayedChanges.margins;
          changedSettings.margins == "custom"
            ? (delayedChanges[setting] = value)
            : (instantChanges[setting] = value);
          break;
        default:
          instantChanges[setting] = value;
          break;
      }
    }
    if (Object.keys(delayedChanges).length) {
      this._scheduleDelayedSettingsChange(delayedChanges);
    }
    if (Object.keys(instantChanges).length) {
      this.onUserSettingsChange(instantChanges);
    }
  },

  async onUserSettingsChange(changedSettings = {}) {
    let previewableChange = false;
    for (let [setting, value] of Object.entries(changedSettings)) {
      Services.telemetry.keyedScalarAdd(
        "printing.settings_changed",
        setting,
        1
      );
      // Update the list of user-changed settings, which we attempt to maintain
      // across printer changes.
      this._userChangedSettings[setting] = value;
      if (!this._noPreviewUpdateSettings.has(setting)) {
        previewableChange = true;
      }
    }
    if (changedSettings.printerName) {
      logger.debug(
        "onUserSettingsChange, changing to printerName:",
        changedSettings.printerName
      );
      this.printForm.printerChanging = true;
      this.printForm.disable(el => el.id != "printer-picker");
      let { printerName } = changedSettings;
      // Treat a printerName change separately, because it involves a settings
      // object switch and we don't want to set the new name on the old settings.
      changedSettings = await this.refreshSettings(printerName);
      if (printerName != this.currentPrinterName) {
        // Don't continue this update if the printer changed again.
        return;
      }
      this.printForm.printerChanging = false;
      this.printForm.enable();
    } else {
      changedSettings = this.getSettingsToUpdate();
    }

    let shouldPreviewUpdate =
      (await this.updateSettings(
        changedSettings,
        !!changedSettings.printerName
      )) && previewableChange;

    if (shouldPreviewUpdate && !printPending) {
      // We do not need to arm the preview task if the user has already printed
      // and finalized any deferred tasks.
      this.updatePrintPreview();
    }
    document.dispatchEvent(
      new CustomEvent("print-settings", {
        detail: this.viewSettings,
      })
    );
  },

  async updateSettings(changedSettings = {}, printerChanged = false) {
    let updatePreviewWithoutFlag = false;
    let flags = 0;
    logger.debug("updateSettings ", changedSettings, printerChanged);

    if (printerChanged || changedSettings.paperId) {
      // The paper's margin properties are async,
      // so resolve those now before we update the settings
      try {
        let paperWrapper = await PrintSettingsViewProxy.fetchPaperMargins(
          changedSettings.paperId || this.viewSettings.paperId
        );

        // See if we also need to change the custom margin values

        let paperHeightInInches = paperWrapper.paper.height * INCHES_PER_POINT;
        let paperWidthInInches = paperWrapper.paper.width * INCHES_PER_POINT;
        let height =
          (changedSettings.orientation || this.viewSettings.orientation) == 0
            ? paperHeightInInches
            : paperWidthInInches;
        let width =
          (changedSettings.orientation || this.viewSettings.orientation) == 0
            ? paperWidthInInches
            : paperHeightInInches;

        function verticalMarginsInvalid(margins) {
          return (
            parseFloat(margins.marginTop) + parseFloat(margins.marginBottom) >
            height -
              paperWrapper.unwriteableMarginTop -
              paperWrapper.unwriteableMarginBottom
          );
        }

        function horizontalMarginsInvalid(margins) {
          return (
            parseFloat(margins.marginRight) + parseFloat(margins.marginLeft) >
            width -
              paperWrapper.unwriteableMarginRight -
              paperWrapper.unwriteableMarginLeft
          );
        }

        let unwriteableMarginsInvalid = false;
        if (
          verticalMarginsInvalid(this.viewSettings.customMargins) ||
          this.viewSettings.customMargins.marginTop < 0 ||
          this.viewSettings.customMargins.marginBottom < 0
        ) {
          let { marginTop, marginBottom } = this.viewSettings.defaultMargins;
          if (verticalMarginsInvalid(this.viewSettings.defaultMargins)) {
            let marginsNone = this.getMarginPresets("none");
            marginTop = marginsNone.marginTop;
            marginBottom = marginsNone.marginBottom;
            unwriteableMarginsInvalid = true;
          }
          changedSettings.marginTop = changedSettings.customMarginTop =
            marginTop;
          changedSettings.marginBottom = changedSettings.customMarginBottom =
            marginBottom;
          delete this._userChangedSettings.customMargins;
        }

        if (
          horizontalMarginsInvalid(this.viewSettings.customMargins) ||
          this.viewSettings.customMargins.marginLeft < 0 ||
          this.viewSettings.customMargins.marginRight < 0
        ) {
          let { marginLeft, marginRight } = this.viewSettings.defaultMargins;
          if (horizontalMarginsInvalid(this.viewSettings.defaultMargins)) {
            let marginsNone = this.getMarginPresets("none");
            marginLeft = marginsNone.marginLeft;
            marginRight = marginsNone.marginRight;
            unwriteableMarginsInvalid = true;
          }
          changedSettings.marginLeft = changedSettings.customMarginLeft =
            marginLeft;
          changedSettings.marginRight = changedSettings.customMarginRight =
            marginRight;
          delete this._userChangedSettings.customMargins;
        }

        if (unwriteableMarginsInvalid) {
          changedSettings.ignoreUnwriteableMargins = true;
        }
      } catch (e) {
        this.reportPrintingError("PAPER_MARGINS");
        throw e;
      }
    }

    for (let [setting, value] of Object.entries(changedSettings)) {
      // Always write paper changes back to settings as pref-derived values could be bad
      if (
        this.viewSettings[setting] != value ||
        (printerChanged && setting == "paperId")
      ) {
        if (setting == "pageRanges") {
          // The page range is kept as an array. If the user switches between all
          // and custom with no specified range input (which is represented as an
          // empty array), we do not want to send an update.
          if (!this.viewSettings[setting].length && !value.length) {
            continue;
          }
        }
        this.viewSettings[setting] = value;

        if (
          setting in this.settingFlags &&
          setting in this._userChangedSettings
        ) {
          flags |= this.settingFlags[setting];
        }
        updatePreviewWithoutFlag |=
          this._nonFlaggedUpdatePreviewSettings.has(setting);
      }
    }

    let shouldPreviewUpdate =
      flags || printerChanged || updatePreviewWithoutFlag;
    logger.debug(
      "updateSettings, calculated flags:",
      flags,
      "shouldPreviewUpdate:",
      shouldPreviewUpdate
    );
    if (flags) {
      this.saveSettingsToPrefs(flags);
    }
    return shouldPreviewUpdate;
  },

  saveSettingsToPrefs(flags) {
    PSSVC.maybeSavePrintSettingsToPrefs(this.settings, flags);
  },

  /**
   * Queue a task to update the print preview. It will start immediately or when
   * the in progress update completes.
   */
  async updatePrintPreview() {
    // Make sure the rendering state is set so we don't visibly update the
    // sheet count with incomplete data.
    this._updatePrintPreviewTask.arm();
  },

  /**
   * Creates a print preview or refreshes the preview with new settings when omitted.
   *
   * @return {Promise} Resolves when the preview has been updated.
   */
  async _updatePrintPreview() {
    let { settings } = this;

    const isFirstCall = !this.printInitiationTime;
    if (isFirstCall) {
      let params = new URLSearchParams(location.search);
      this.printInitiationTime = parseInt(
        params.get("printInitiationTime"),
        10
      );
      const elapsed = Date.now() - this.printInitiationTime;
      Services.telemetry
        .getHistogramById("PRINT_INIT_TO_PLATFORM_SENT_SETTINGS_MS")
        .add(elapsed);
    }

    let totalPageCount, sheetCount, isEmpty, orientation, pageWidth, pageHeight;
    try {
      // This resolves with a PrintPreviewSuccessInfo dictionary.
      let { sourceVersion } = this.viewSettings;
      let sourceURI = this.activeURI;
      this._lastPrintPreviewSettings = settings;
      ({
        totalPageCount,
        sheetCount,
        isEmpty,
        orientation,
        pageWidth,
        pageHeight,
      } = await this.printPreviewEl.printPreview(settings, {
        sourceVersion,
        sourceURI,
      }));
    } catch (e) {
      this.reportPrintingError("PRINT_PREVIEW");
      console.error(e);
      throw e;
    }

    // If there is a set orientation, update the settings to use it. In this
    // case, the document will already have used this orientation to create
    // the print preview.
    if (orientation != "unspecified") {
      const kIPrintSettings = Ci.nsIPrintSettings;
      settings.orientation =
        orientation == "landscape"
          ? kIPrintSettings.kLandscapeOrientation
          : kIPrintSettings.kPortraitOrientation;
      document.dispatchEvent(new CustomEvent("hide-orientation"));
    }

    // If the page size is set, check whether we should use it as our paper size.
    let isUsingPageRuleSizeAsPaperSize =
      settings.usePageRuleSizeAsPaperSize &&
      pageWidth !== null &&
      pageHeight !== null;
    if (isUsingPageRuleSizeAsPaperSize) {
      // We canonically represent paper sizes using the width/height of a portrait-oriented sheet,
      // with landscape-orientation applied as a supplemental rotation.
      // If the page-size is landscape oriented, we flip the pageWidth / pageHeight here
      // in order to pass a canonical representation into the paper-size settings.
      if (orientation == "landscape") {
        [pageHeight, pageWidth] = [pageWidth, pageHeight];
      }

      let matchedPaper = PrintSettingsViewProxy.getBestPaperMatch(
        pageWidth,
        pageHeight,
        settings.kPaperSizeInches
      );
      if (matchedPaper) {
        settings.paperId = matchedPaper.id;
      }

      settings.paperWidth = pageWidth;
      settings.paperHeight = pageHeight;
      settings.paperSizeUnit = settings.kPaperSizeInches;
      document.dispatchEvent(new CustomEvent("hide-paper-size"));
    }

    this.previewIsEmpty = isEmpty;
    // If the preview is empty, we know our range is greater than the number of pages.
    // We have to send a pageRange update to display a non-empty page.
    if (this.previewIsEmpty) {
      this.viewSettings.pageRanges = [];
      this.updatePrintPreview();
    }

    document.dispatchEvent(
      new CustomEvent("page-count", {
        detail: { sheetCount, totalPages: totalPageCount },
      })
    );

    if (isFirstCall) {
      const elapsed = Date.now() - this.printInitiationTime;
      Services.telemetry
        .getHistogramById("PRINT_INIT_TO_PREVIEW_DOC_SHOWN_MS")
        .add(elapsed);
    }
  },

  async getPrintDestinations() {
    const printerList = Cc["@mozilla.org/gfx/printerlist;1"].createInstance(
      Ci.nsIPrinterList
    );
    let printers;

    if (Cu.isInAutomation) {
      printers = window._mockPrinters || [];
    } else {
      try {
        printers = await printerList.printers;
      } catch (e) {
        this.reportPrintingError("PRINTER_LIST");
        throw e;
      }
    }

    let fallbackPaperList;
    try {
      fallbackPaperList = await printerList.fallbackPaperList;
    } catch (e) {
      this.reportPrintingError("FALLBACK_PAPER_LIST");
      throw e;
    }

    let lastUsedPrinterName;
    try {
      lastUsedPrinterName = PSSVC.lastUsedPrinterName;
    } catch (e) {
      this.reportPrintingError("LAST_USED_PRINTER");
      throw e;
    }
    const defaultPrinterName = printerList.systemDefaultPrinterName;
    const printersByName = {};

    let lastUsedPrinter;
    let defaultSystemPrinter;

    let saveToPdfPrinter = {
      nameId: "printui-destination-pdf-label",
      value: PrintUtils.SAVE_TO_PDF_PRINTER,
    };
    printersByName[PrintUtils.SAVE_TO_PDF_PRINTER] = {
      supportsColor: true,
      supportsMonochrome: false,
      name: PrintUtils.SAVE_TO_PDF_PRINTER,
    };

    if (lastUsedPrinterName == PrintUtils.SAVE_TO_PDF_PRINTER) {
      lastUsedPrinter = saveToPdfPrinter;
    }

    let destinations = [
      saveToPdfPrinter,
      ...printers.map(printer => {
        printer.QueryInterface(Ci.nsIPrinter);
        const { name } = printer;
        printersByName[printer.name] = { printer };
        const destination = { name, value: name };

        if (name == lastUsedPrinterName) {
          lastUsedPrinter = destination;
        }
        if (name == defaultPrinterName) {
          defaultSystemPrinter = destination;
        }

        return destination;
      }),
    ];

    let selectedPrinter =
      lastUsedPrinter || defaultSystemPrinter || saveToPdfPrinter;

    return {
      destinations,
      fallbackPaperList,
      selectedPrinter,
      printersByName,
      defaultSystemPrinter,
    };
  },

  getMarginPresets(marginSize, paperWrapper) {
    switch (marginSize) {
      case "minimum": {
        let marginSource = paperWrapper || this.defaultSettings;
        return {
          marginTop: marginSource.unwriteableMarginTop,
          marginRight: marginSource.unwriteableMarginRight,
          marginBottom: marginSource.unwriteableMarginBottom,
          marginLeft: marginSource.unwriteableMarginLeft,
        };
      }
      case "none":
        return {
          marginTop: 0,
          marginLeft: 0,
          marginBottom: 0,
          marginRight: 0,
        };
      case "custom":
        return {
          marginTop:
            PrintSettingsViewProxy._lastCustomMarginValues.marginTop ??
            this.settings.marginTop,
          marginBottom:
            PrintSettingsViewProxy._lastCustomMarginValues.marginBottom ??
            this.settings.marginBottom,
          marginLeft:
            PrintSettingsViewProxy._lastCustomMarginValues.marginLeft ??
            this.settings.marginLeft,
          marginRight:
            PrintSettingsViewProxy._lastCustomMarginValues.marginRight ??
            this.settings.marginRight,
        };
      default: {
        let minimum = this.getMarginPresets("minimum", paperWrapper);
        return {
          marginTop: !isNaN(minimum.marginTop)
            ? Math.max(minimum.marginTop, this.defaultSettings.marginTop)
            : this.defaultSettings.marginTop,
          marginRight: !isNaN(minimum.marginRight)
            ? Math.max(minimum.marginRight, this.defaultSettings.marginRight)
            : this.defaultSettings.marginRight,
          marginBottom: !isNaN(minimum.marginBottom)
            ? Math.max(minimum.marginBottom, this.defaultSettings.marginBottom)
            : this.defaultSettings.marginBottom,
          marginLeft: !isNaN(minimum.marginLeft)
            ? Math.max(minimum.marginLeft, this.defaultSettings.marginLeft)
            : this.defaultSettings.marginLeft,
        };
      }
    }
  },

  reportPrintingError(aMessage) {
    logger.debug("reportPrintingError:", aMessage);
    Services.telemetry.keyedScalarAdd("printing.error", aMessage, 1);
  },

  /**
   * Shows the system dialog. This method has been abstracted into a helper for
   * testing purposes. The showPrintDialog() call blocks until the dialog is
   * closed, so we mark it as async to allow us to reject from the test.
   */
  async _showPrintDialog(aWindow, aHaveSelection, aSettings) {
    return PrintUtils.handleSystemPrintDialog(
      aWindow,
      aHaveSelection,
      aSettings
    );
  },
};

var PrintSettingsViewProxy = {
  get defaultHeadersAndFooterValues() {
    const defaultBranch = Services.prefs.getDefaultBranch("");
    let settingValues = {};
    for (let [name, pref] of Object.entries(this.headerFooterSettingsPrefs)) {
      settingValues[name] = defaultBranch.getStringPref(pref);
    }
    // We only need to retrieve these defaults once and they will not change
    Object.defineProperty(this, "defaultHeadersAndFooterValues", {
      value: settingValues,
    });
    return settingValues;
  },

  headerFooterSettingsPrefs: {
    footerStrCenter: "print.print_footercenter",
    footerStrLeft: "print.print_footerleft",
    footerStrRight: "print.print_footerright",
    headerStrCenter: "print.print_headercenter",
    headerStrLeft: "print.print_headerleft",
    headerStrRight: "print.print_headerright",
  },

  // Custom margins are not saved by a pref, so we need to keep track of them
  // in order to save the value.
  _lastCustomMarginValues: {
    marginTop: null,
    marginBottom: null,
    marginLeft: null,
    marginRight: null,
  },

  // This list was taken from nsDeviceContextSpecWin.cpp which records telemetry on print target type
  knownSaveToFilePrinters: new Set([
    "Microsoft Print to PDF",
    "Adobe PDF",
    "Bullzip PDF Printer",
    "CutePDF Writer",
    "doPDF",
    "Foxit Reader PDF Printer",
    "Nitro PDF Creator",
    "novaPDF",
    "PDF-XChange",
    "PDF24 PDF",
    "PDFCreator",
    "PrimoPDF",
    "Soda PDF",
    "Solid PDF Creator",
    "Universal Document Converter",
    "Microsoft XPS Document Writer",
  ]),

  getBestPaperMatch(paperWidth, paperHeight, paperSizeUnit) {
    let paperSizes = Object.values(this.availablePaperSizes);
    if (!(paperWidth && paperHeight)) {
      return null;
    }
    // first try to match on the paper dimensions using the current units
    let unitsPerPoint;
    let altUnitsPerPoint;
    if (paperSizeUnit == PrintEventHandler.settings.kPaperSizeMillimeters) {
      unitsPerPoint = MM_PER_POINT;
      altUnitsPerPoint = INCHES_PER_POINT;
    } else {
      unitsPerPoint = INCHES_PER_POINT;
      altUnitsPerPoint = MM_PER_POINT;
    }
    // equality to 1pt.
    const equal = (a, b) => Math.abs(a - b) < 1;
    const findMatch = (widthPts, heightPts) =>
      paperSizes.find(paperWrapper => {
        // the dimensions on the nsIPaper object are in points
        let result =
          equal(widthPts, paperWrapper.paper.width) &&
          equal(heightPts, paperWrapper.paper.height);
        return result;
      });
    // Look for a paper with matching dimensions, using the current printer's
    // paper size unit, then the alternate unit
    let matchedPaper =
      findMatch(paperWidth / unitsPerPoint, paperHeight / unitsPerPoint) ||
      findMatch(paperWidth / altUnitsPerPoint, paperHeight / altUnitsPerPoint);

    if (matchedPaper) {
      return matchedPaper;
    }
    return null;
  },

  async fetchPaperMargins(paperId) {
    // resolve any async and computed properties we need on the paper
    let paperWrapper = this.availablePaperSizes[paperId];
    if (!paperWrapper) {
      throw new Error("Can't fetchPaperMargins: " + paperId);
    }
    if (paperWrapper._resolved) {
      // We've already resolved and calculated these values
      return paperWrapper;
    }
    let margins;
    try {
      margins = await paperWrapper.paper.unwriteableMargin;
    } catch (e) {
      this.reportPrintingError("UNWRITEABLE_MARGIN");
      throw e;
    }
    margins.QueryInterface(Ci.nsIPaperMargin);

    // margin dimensions are given on the paper in points, setting values need to be in inches
    paperWrapper.unwriteableMarginTop = margins.top * INCHES_PER_POINT;
    paperWrapper.unwriteableMarginRight = margins.right * INCHES_PER_POINT;
    paperWrapper.unwriteableMarginBottom = margins.bottom * INCHES_PER_POINT;
    paperWrapper.unwriteableMarginLeft = margins.left * INCHES_PER_POINT;
    // No need to re-resolve static properties
    paperWrapper._resolved = true;
    return paperWrapper;
  },

  async resolvePropertiesForPrinter(printerName) {
    // resolve any async properties we need on the printer
    let printerInfo = this.availablePrinters[printerName];
    if (printerInfo._resolved) {
      // Store a convenience reference
      this.availablePaperSizes = printerInfo.availablePaperSizes;
      return printerInfo;
    }

    // Await the async printer data.
    if (printerInfo.printer) {
      let basePrinterInfo;
      try {
        [
          printerInfo.supportsDuplex,
          printerInfo.supportsColor,
          printerInfo.supportsMonochrome,
          basePrinterInfo,
        ] = await Promise.all([
          printerInfo.printer.supportsDuplex,
          printerInfo.printer.supportsColor,
          printerInfo.printer.supportsMonochrome,
          printerInfo.printer.printerInfo,
        ]);
      } catch (e) {
        this.reportPrintingError("PRINTER_SETTINGS");
        throw e;
      }
      basePrinterInfo.QueryInterface(Ci.nsIPrinterInfo);
      basePrinterInfo.defaultSettings.QueryInterface(Ci.nsIPrintSettings);

      printerInfo.paperList = basePrinterInfo.paperList;
      printerInfo.defaultSettings = basePrinterInfo.defaultSettings;
    } else if (printerName == PrintUtils.SAVE_TO_PDF_PRINTER) {
      // The Mozilla PDF pseudo-printer has no actual nsIPrinter implementation
      printerInfo.defaultSettings = PSSVC.createNewPrintSettings();
      printerInfo.defaultSettings.printerName = printerName;
      printerInfo.defaultSettings.toFileName = "";
      printerInfo.defaultSettings.outputFormat =
        Ci.nsIPrintSettings.kOutputFormatPDF;
      printerInfo.defaultSettings.outputDestination =
        Ci.nsIPrintSettings.kOutputDestinationFile;
      printerInfo.defaultSettings.usePageRuleSizeAsPaperSize =
        Services.prefs.getBoolPref(
          "print.save_as_pdf.use_page_rule_size_as_paper_size.enabled",
          false
        );
      printerInfo.paperList = this.fallbackPaperList;
    }
    printerInfo.settings = printerInfo.defaultSettings.clone();
    // Apply any previously persisted user values
    // Don't apply kInitSavePrintToFile though, that should only be true for
    // the PDF printer.
    printerInfo.settings.outputDestination =
      printerName == PrintUtils.SAVE_TO_PDF_PRINTER
        ? Ci.nsIPrintSettings.kOutputDestinationFile
        : Ci.nsIPrintSettings.kOutputDestinationPrinter;
    let flags =
      printerInfo.settings.kInitSaveAll ^
      printerInfo.settings.kInitSavePrintToFile;
    PSSVC.initPrintSettingsFromPrefs(printerInfo.settings, true, flags);
    // We set `isInitializedFromPrinter` to make sure that that's set on the
    // SAVE_TO_PDF_PRINTER settings.  The naming is poor, but that tells the
    // platform code that the settings object is complete.
    printerInfo.settings.isInitializedFromPrinter = true;

    printerInfo.settings.toFileName = "";

    // prepare the available paper sizes for this printer
    if (!printerInfo.paperList?.length) {
      logger.warn(
        "Printer has empty paperList: ",
        printerInfo.printer.id,
        "using fallbackPaperList"
      );
      printerInfo.paperList = this.fallbackPaperList;
    }
    // don't trust the settings to provide valid paperSizeUnit values
    let sizeUnit =
      printerInfo.settings.paperSizeUnit ==
      printerInfo.settings.kPaperSizeMillimeters
        ? printerInfo.settings.kPaperSizeMillimeters
        : printerInfo.settings.kPaperSizeInches;
    let papersById = (printerInfo.availablePaperSizes = {});
    // Store a convenience reference
    this.availablePaperSizes = papersById;

    for (let paper of printerInfo.paperList) {
      paper.QueryInterface(Ci.nsIPaper);
      // Bug 1662239: I'm seeing multiple duplicate entries for each paper size
      // so ensure we have one entry per name
      if (!papersById[paper.id]) {
        papersById[paper.id] = {
          paper,
          id: paper.id,
          name: paper.name,
          // XXXsfoster: Eventually we want to get the unit from the nsIPaper object
          sizeUnit,
        };
      }
    }
    // Update our cache of all the paper sizes by name
    Object.assign(PrintEventHandler.allPaperSizes, papersById);

    // The printer properties don't change, mark this as resolved for next time
    printerInfo._resolved = true;
    logger.debug("Resolved printerInfo:", printerInfo);
    return printerInfo;
  },

  get(target, name) {
    switch (name) {
      case "currentPaper": {
        let paperId = this.get(target, "paperId");
        return paperId && this.availablePaperSizes[paperId];
      }

      case "marginPresets":
        let paperWrapper = this.get(target, "currentPaper");
        return {
          none: PrintEventHandler.getMarginPresets("none", paperWrapper),
          minimum: PrintEventHandler.getMarginPresets("minimum", paperWrapper),
          default: PrintEventHandler.getMarginPresets("default", paperWrapper),
          custom: PrintEventHandler.getMarginPresets("custom", paperWrapper),
        };

      case "marginOptions": {
        let allMarginPresets = this.get(target, "marginPresets");
        let uniqueMargins = new Set();
        let marginsEnabled = {};
        for (let name of ["none", "default", "minimum", "custom"]) {
          let { marginTop, marginLeft, marginBottom, marginRight } =
            allMarginPresets[name];
          let key = [marginTop, marginLeft, marginBottom, marginRight].join(
            ","
          );
          // Custom margins are initialized to default margins
          marginsEnabled[name] = !uniqueMargins.has(key) || name == "custom";
          uniqueMargins.add(key);
        }
        return marginsEnabled;
      }

      case "margins":
        let marginSettings = {
          marginTop: target.marginTop,
          marginLeft: target.marginLeft,
          marginBottom: target.marginBottom,
          marginRight: target.marginRight,
        };
        // see if they match the none, minimum, or default margin values
        let allMarginPresets = this.get(target, "marginPresets");
        const marginsMatch = function (lhs, rhs) {
          return Object.keys(marginSettings).every(
            name => lhs[name].toFixed(2) == rhs[name].toFixed(2)
          );
        };
        const potentialPresets = (function () {
          let presets = [];
          const minimumIsNone = marginsMatch(
            allMarginPresets.none,
            allMarginPresets.minimum
          );
          // We only attempt to match the serialized values against the "none"
          // preset if the unwriteable margins are being ignored or are zero.
          if (target.ignoreUnwriteableMargins || minimumIsNone) {
            presets.push("none");
          }
          if (!minimumIsNone) {
            presets.push("minimum");
          }
          presets.push("default");
          return presets;
        })();
        for (let presetName of potentialPresets) {
          let marginPresets = allMarginPresets[presetName];
          if (marginsMatch(marginSettings, marginPresets)) {
            return presetName;
          }
        }

        // Fall back to custom for other values
        return "custom";

      case "defaultMargins":
        return PrintEventHandler.getMarginPresets(
          "default",
          this.get(target, "currentPaper")
        );

      case "customMargins":
        return PrintEventHandler.getMarginPresets(
          "custom",
          this.get(target, "currentPaper")
        );

      case "paperSizes":
        return Object.values(this.availablePaperSizes)
          .sort((a, b) => a.name.localeCompare(b.name))
          .map(paper => {
            return {
              name: paper.name,
              value: paper.id,
            };
          });

      case "supportsDuplex":
        return this.availablePrinters[target.printerName].supportsDuplex;

      case "printDuplex":
        switch (target.duplex) {
          case Ci.nsIPrintSettings.kDuplexNone:
            break;
          case Ci.nsIPrintSettings.kDuplexFlipOnLongEdge:
            return "long-edge";
          case Ci.nsIPrintSettings.kDuplexFlipOnShortEdge:
            return "short-edge";
          default:
            logger.warn("Unexpected duplex value: ", target.duplex);
        }
        return "off";
      case "printBackgrounds":
        return target.printBGImages || target.printBGColors;

      case "printFootersHeaders":
        // if any of the footer and headers settings have a non-empty string value
        // we consider that "enabled"
        return Object.keys(this.headerFooterSettingsPrefs).some(
          name => !!target[name]
        );

      case "supportsColor":
        return this.availablePrinters[target.printerName].supportsColor;

      case "willSaveToFile":
        return (
          target.outputFormat == Ci.nsIPrintSettings.kOutputFormatPDF ||
          this.knownSaveToFilePrinters.has(target.printerName)
        );
      case "supportsMonochrome":
        return this.availablePrinters[target.printerName].supportsMonochrome;
      case "defaultSystemPrinter":
        return (
          this.defaultSystemPrinter?.value ||
          Object.getOwnPropertyNames(this.availablePrinters).find(
            name => name != PrintUtils.SAVE_TO_PDF_PRINTER
          )
        );

      case "numCopies":
        return this.get(target, "willSaveToFile") ? 1 : target.numCopies;
      case "sourceVersion":
        return this._sourceVersion;
    }
    return target[name];
  },

  set(target, name, value) {
    switch (name) {
      case "margins":
        if (!["default", "minimum", "none", "custom"].includes(value)) {
          logger.warn("Unexpected margin preset name: ", value);
          value = "default";
        }
        let paperWrapper = this.get(target, "currentPaper");
        let marginPresets = PrintEventHandler.getMarginPresets(
          value,
          paperWrapper
        );
        for (let [settingName, presetValue] of Object.entries(marginPresets)) {
          target[settingName] = presetValue;
        }
        target.honorPageRuleMargins = value == "default";
        target.ignoreUnwriteableMargins = value == "none";
        break;

      case "paperId": {
        let paperId = value;
        let paperWrapper = this.availablePaperSizes[paperId];
        // Dimensions on the paper object are in pts.
        // We convert to the printer's specified unit when updating settings
        let unitsPerPoint =
          paperWrapper.sizeUnit == target.kPaperSizeMillimeters
            ? MM_PER_POINT
            : INCHES_PER_POINT;
        // paperWidth and paperHeight are calculated values that we always treat as suspect and
        // re-calculate whenever the paperId changes
        target.paperSizeUnit = paperWrapper.sizeUnit;
        target.paperWidth = paperWrapper.paper.width * unitsPerPoint;
        target.paperHeight = paperWrapper.paper.height * unitsPerPoint;
        // Unwriteable margins were pre-calculated from their async values when the paper size
        // was selected. They are always in inches
        target.unwriteableMarginTop = paperWrapper.unwriteableMarginTop;
        target.unwriteableMarginRight = paperWrapper.unwriteableMarginRight;
        target.unwriteableMarginBottom = paperWrapper.unwriteableMarginBottom;
        target.unwriteableMarginLeft = paperWrapper.unwriteableMarginLeft;
        target.paperId = paperWrapper.paper.id;
        // pull new margin values for the new paper size
        this.set(target, "margins", this.get(target, "margins"));
        break;
      }

      case "printerName":
        // Can't set printerName, settings objects belong to a specific printer.
        break;

      case "printBackgrounds":
        target.printBGImages = value;
        target.printBGColors = value;
        break;

      case "printDuplex": {
        let duplex = (function () {
          switch (value) {
            case "off":
              break;
            case "long-edge":
              return Ci.nsIPrintSettings.kDuplexFlipOnLongEdge;
            case "short-edge":
              return Ci.nsIPrintSettings.kDuplexFlipOnShortEdge;
            default:
              logger.warn("Unexpected duplex name: ", value);
          }
          return Ci.nsIPrintSettings.kDuplexNone;
        })();

        target.duplex = duplex;
        break;
      }

      case "printFootersHeaders":
        // To disable header & footers, set them all to empty.
        // To enable, restore default values for each of the header & footer settings.
        for (let [settingName, defaultValue] of Object.entries(
          this.defaultHeadersAndFooterValues
        )) {
          target[settingName] = value ? defaultValue : "";
        }
        break;

      case "customMargins":
        if (value != null) {
          for (let [settingName, newVal] of Object.entries(value)) {
            target[settingName] = newVal;
            this._lastCustomMarginValues[settingName] = newVal;
          }
        }
        break;

      case "customMarginTop":
      case "customMarginBottom":
      case "customMarginLeft":
      case "customMarginRight":
        let customMarginName = "margin" + name.substring(12);
        this.set(
          target,
          "customMargins",
          Object.assign({}, this.get(target, "customMargins"), {
            [customMarginName]: value,
          })
        );
        break;

      case "sourceVersion":
        this._sourceVersion = value;
        this.set(target, "printSelectionOnly", value == "selection");
        if (value == "simplified") {
          this.set(target, "printBackgrounds", false);
        }
        break;

      default:
        target[name] = value;
    }
  },
};

/*
 * Custom elements ----------------------------------------------------
 */

function PrintUIControlMixin(superClass) {
  return class PrintUIControl extends superClass {
    connectedCallback() {
      this.setAttribute("autocomplete", "off");
      this.initialize();
      this.render();
    }

    initialize() {
      if (this._initialized) {
        return;
      }
      this._initialized = true;
      if (this.templateId) {
        let template = this.ownerDocument.getElementById(this.templateId);
        let templateContent = template.content;
        this.appendChild(templateContent.cloneNode(true));
      }

      document.addEventListener("print-settings", ({ detail: settings }) => {
        this.update(settings);
      });

      this.addEventListener("input", this);
    }

    render() {}

    update(settings) {}

    dispatchSettingsChange(changedSettings) {
      this.dispatchEvent(
        new CustomEvent("update-print-settings", {
          bubbles: true,
          detail: changedSettings,
        })
      );
    }

    cancelSettingsChange(changedSettings) {
      this.dispatchEvent(
        new CustomEvent("cancel-print-settings", {
          bubbles: true,
          detail: changedSettings,
        })
      );
    }

    handleEvent(event) {}
  };
}

class PrintUIForm extends PrintUIControlMixin(HTMLFormElement) {
  initialize() {
    super.initialize();

    this.addEventListener("submit", this);
    this.addEventListener("click", this);
    this.addEventListener("revalidate", this);

    this._printerDestination = this.querySelector("#destination");
    this.printButton = this.querySelector("#print-button");
  }

  removeNonPdfSettings() {
    let selectors = ["#backgrounds", "#source-version-selection"];
    for (let selector of selectors) {
      this.querySelector(selector).remove();
    }
    let moreSettings = this.querySelector("#more-settings-options");
    if (moreSettings.children.length <= 1) {
      moreSettings.remove();
    }
  }

  requestPrint() {
    this.requestSubmit(this.printButton);
  }

  update(settings) {
    // If there are no default system printers available and we are not on mac,
    // we should hide the system dialog because it won't be populated with
    // the correct settings. Mac and Gtk support save to pdf functionality
    // in the native dialog, so it can be shown regardless.
    this.querySelector("#system-print").hidden =
      AppConstants.platform === "win" && !settings.defaultSystemPrinter;

    this.querySelector("#two-sided-printing").hidden = !settings.supportsDuplex;
  }

  enable() {
    let isValid = this.checkValidity();
    document.body.toggleAttribute("invalid", !isValid);
    if (isValid) {
      for (let element of this.elements) {
        if (!element.hasAttribute("disallowed")) {
          element.disabled = false;
        }
      }
      // aria-describedby will usually cause the first value to be reported.
      // Unfortunately, screen readers don't pick up description changes from
      // dialogs, so we must use a live region. To avoid double reporting of
      // the first value, we don't set aria-live initially. We only set it for
      // subsequent updates.
      // aria-live is set on the parent because sheetCount itself might be
      // hidden and then shown, and updates are only reported for live
      // regions that were already visible.
      document
        .querySelector("#sheet-count")
        .parentNode.setAttribute("aria-live", "polite");
    } else {
      // Find the invalid element
      let invalidElement;
      for (let element of this.elements) {
        if (!element.checkValidity()) {
          invalidElement = element;
          break;
        }
      }
      let section = invalidElement.closest(".section-block");
      document.body.toggleAttribute("invalid", !isValid);
      // We're hiding the sheet count and aria-describedby includes the
      // content of hidden elements, so remove aria-describedby.
      document.body.removeAttribute("aria-describedby");
      for (let element of this.elements) {
        // If we're valid, enable all inputs.
        // Otherwise, disable the valid inputs other than the cancel button and the elements
        // in the invalid section.
        element.disabled =
          element.hasAttribute("disallowed") ||
          (!isValid &&
            element.validity.valid &&
            element.name != "cancel" &&
            element.closest(".section-block") != this._printerDestination &&
            element.closest(".section-block") != section);
      }
    }
  }

  disable(filterFn) {
    for (let element of this.elements) {
      if (filterFn && !filterFn(element)) {
        continue;
      }
      element.disabled = element.name != "cancel";
    }
  }

  handleEvent(e) {
    if (e.target.id == "open-dialog-link") {
      this.dispatchEvent(new Event("open-system-dialog", { bubbles: true }));
      return;
    }

    if (e.type == "submit") {
      e.preventDefault();
      if (e.submitter.name == "print" && this.checkValidity()) {
        this.dispatchEvent(new Event("print", { bubbles: true }));
      }
    } else if (
      (e.type == "input" || e.type == "revalidate") &&
      !this.printerChanging
    ) {
      this.enable();
    }
  }
}
customElements.define("print-form", PrintUIForm, { extends: "form" });

class PrintSettingSelect extends PrintUIControlMixin(HTMLSelectElement) {
  initialize() {
    super.initialize();
    this.addEventListener("keypress", this);
  }

  connectedCallback() {
    this.settingName = this.dataset.settingName;
    super.connectedCallback();
  }

  setOptions(optionValues = []) {
    this.textContent = "";
    for (let optionData of optionValues) {
      let opt = new Option(
        optionData.name,
        "value" in optionData ? optionData.value : optionData.name
      );
      if (optionData.nameId) {
        document.l10n.setAttributes(opt, optionData.nameId);
      }
      // option selectedness is set via update() and assignment to this.value
      this.options.add(opt);
    }
  }

  update(settings) {
    if (this.settingName) {
      this.value = settings[this.settingName];
    }
  }

  handleEvent(e) {
    if (e.type == "input" && this.settingName) {
      this.dispatchSettingsChange({
        [this.settingName]: e.target.value,
      });
    } else if (e.type == "keypress") {
      if (
        e.key == "Enter" &&
        (!e.metaKey || AppConstants.platform == "macosx")
      ) {
        this.form.requestPrint();
      }
    }
  }
}
customElements.define("setting-select", PrintSettingSelect, {
  extends: "select",
});

class PrintSettingNumber extends PrintUIControlMixin(HTMLInputElement) {
  initialize() {
    super.initialize();
    this.addEventListener("beforeinput", e => this.preventWhitespaceEntry(e));
    this.addEventListener("paste", e => this.pasteWithoutWhitespace(e));
  }

  connectedCallback() {
    this.type = "number";
    this.settingName = this.dataset.settingName;
    super.connectedCallback();
  }

  update(settings) {
    if (this.settingName) {
      this.value = settings[this.settingName];
    }
  }

  preventWhitespaceEntry(e) {
    if (e.data && !e.data.trim().length) {
      e.preventDefault();
    }
  }

  pasteWithoutWhitespace(e) {
    // Prevent original value from being pasted
    e.preventDefault();

    // Manually update input's value with sanitized clipboard data
    let paste = (e.clipboardData || window.clipboardData)
      .getData("text")
      .trim();
    this.value = paste;
  }

  handleEvent(e) {
    switch (e.type) {
      case "input":
        if (this.settingName && this.checkValidity()) {
          this.dispatchSettingsChange({
            [this.settingName]: this.value,
          });
        }
        break;
    }
  }
}
customElements.define("setting-number", PrintSettingNumber, {
  extends: "input",
});

class PrintSettingCheckbox extends PrintUIControlMixin(HTMLInputElement) {
  connectedCallback() {
    this.type = "checkbox";
    this.settingName = this.dataset.settingName;
    super.connectedCallback();
  }

  update(settings) {
    this.checked = settings[this.settingName];
  }

  handleEvent(e) {
    this.dispatchSettingsChange({
      [this.settingName]: this.checked,
    });
  }
}
customElements.define("setting-checkbox", PrintSettingCheckbox, {
  extends: "input",
});

class PrintSettingRadio extends PrintUIControlMixin(HTMLInputElement) {
  connectedCallback() {
    this.type = "radio";
    this.settingName = this.dataset.settingName;
    super.connectedCallback();
  }

  update(settings) {
    this.checked = settings[this.settingName] == this.value;
  }

  handleEvent(e) {
    this.dispatchSettingsChange({
      [this.settingName]: this.value,
    });
  }
}
customElements.define("setting-radio", PrintSettingRadio, {
  extends: "input",
});

class DestinationPicker extends PrintSettingSelect {
  initialize() {
    super.initialize();
    document.addEventListener("available-destinations", this);
  }

  update(settings) {
    super.update(settings);
    let isPdf = settings.outputFormat == Ci.nsIPrintSettings.kOutputFormatPDF;
    this.setAttribute("output", isPdf ? "pdf" : "paper");
  }

  handleEvent(e) {
    super.handleEvent(e);

    if (e.type == "available-destinations") {
      this.setOptions(e.detail);
    }
  }
}
customElements.define("destination-picker", DestinationPicker, {
  extends: "select",
});

class ColorModePicker extends PrintSettingSelect {
  update(settings) {
    this.value = settings[this.settingName] ? "color" : "bw";
    let canSwitch = settings.supportsColor && settings.supportsMonochrome;
    if (this.disablePicker != canSwitch) {
      this.toggleAttribute("disallowed", !canSwitch);
      this.disabled = !canSwitch;
    }
    this.disablePicker = canSwitch;
  }

  handleEvent(e) {
    if (e.type == "input") {
      // turn our string value into the expected boolean
      this.dispatchSettingsChange({
        [this.settingName]: this.value == "color",
      });
    }
  }
}
customElements.define("color-mode-select", ColorModePicker, {
  extends: "select",
});

class PaperSizePicker extends PrintSettingSelect {
  initialize() {
    super.initialize();
    this._printerName = null;
    this._section = this.closest(".section-block");
    document.addEventListener("hide-paper-size", this);
  }

  update(settings) {
    if (settings.printerName !== this._printerName) {
      this._printerName = settings.printerName;
      this.setOptions(settings.paperSizes);
    }
    this.value = settings.paperId;

    // Unhide the paper-size picker, if we've stopped using the page size as paper-size.
    if (this._section.hidden && !settings.usePageRuleSizeAsPaperSize) {
      this._section.hidden = false;
    }
  }

  handleEvent(e) {
    super.handleEvent(e);
    const { type } = e;
    if (type == "hide-paper-size") {
      this._section.hidden = true;
    }
  }
}
customElements.define("paper-size-select", PaperSizePicker, {
  extends: "select",
});

class OrientationInput extends PrintUIControlMixin(HTMLElement) {
  initialize() {
    super.initialize();
    document.addEventListener("hide-orientation", this);
  }

  get templateId() {
    return "orientation-template";
  }

  update(settings) {
    for (let input of this.querySelectorAll("input")) {
      input.checked = settings.orientation == input.value;
    }
  }

  handleEvent(e) {
    if (e.type == "hide-orientation") {
      document.getElementById("orientation").hidden = true;
      return;
    }
    this.dispatchSettingsChange({
      orientation: e.target.value,
    });
  }
}
customElements.define("orientation-input", OrientationInput);

class CopiesInput extends PrintUIControlMixin(HTMLElement) {
  get templateId() {
    return "copy-template";
  }

  initialize() {
    super.initialize();
    this._copiesSection = this.closest(".section-block");
    this._copiesInput = this.querySelector("#copies-count");
    this._copiesError = this.querySelector("#error-invalid-copies");
  }

  update(settings) {
    this._copiesSection.hidden = settings.willSaveToFile;
    this._copiesError.hidden = true;
  }

  handleEvent(e) {
    this._copiesError.hidden = this._copiesInput.checkValidity();
  }
}
customElements.define("copy-count-input", CopiesInput);

class ScaleInput extends PrintUIControlMixin(HTMLElement) {
  get templateId() {
    return "scale-template";
  }

  initialize() {
    super.initialize();

    this._percentScale = this.querySelector("#percent-scale");
    this._shrinkToFitChoice = this.querySelector("#fit-choice");
    this._scaleChoice = this.querySelector("#percent-scale-choice");
    this._scaleError = this.querySelector("#error-invalid-scale");
  }

  updateScale() {
    this.dispatchSettingsChange({
      scaling: Number(this._percentScale.value / 100),
    });
  }

  update(settings) {
    let { scaling, shrinkToFit, printerName } = settings;
    this._shrinkToFitChoice.checked = shrinkToFit;
    this._scaleChoice.checked = !shrinkToFit;
    if (this.disableScale != shrinkToFit) {
      this._percentScale.disabled = shrinkToFit;
      this._percentScale.toggleAttribute("disallowed", shrinkToFit);
    }
    this.disableScale = shrinkToFit;
    if (!this.printerName) {
      this.printerName = printerName;
    }

    // If the user had an invalid input and switches back to "fit to page",
    // we repopulate the scale field with the stored, valid scaling value.
    let isValid = this._percentScale.checkValidity();
    if (
      !this._percentScale.value ||
      (this._shrinkToFitChoice.checked && !isValid) ||
      (this.printerName != printerName && !isValid)
    ) {
      // Only allow whole numbers. 0.14 * 100 would have decimal places, etc.
      this._percentScale.value = parseInt(scaling * 100, 10);
      this.printerName = printerName;
      if (!isValid) {
        this.dispatchEvent(new Event("revalidate", { bubbles: true }));
        this._scaleError.hidden = true;
      }
    }
  }

  handleEvent(e) {
    if (e.target == this._shrinkToFitChoice || e.target == this._scaleChoice) {
      if (!this._percentScale.checkValidity()) {
        this._percentScale.value = 100;
      }
      let scale =
        e.target == this._shrinkToFitChoice
          ? 1
          : Number(this._percentScale.value / 100);
      this.dispatchSettingsChange({
        shrinkToFit: this._shrinkToFitChoice.checked,
        scaling: scale,
      });
      this._scaleError.hidden = true;
    } else if (e.type == "input") {
      if (this._percentScale.checkValidity()) {
        this.updateScale();
      }
    }

    window.clearTimeout(this.showErrorTimeoutId);
    if (this._percentScale.validity.valid) {
      this._scaleError.hidden = true;
    } else {
      this.cancelSettingsChange({ scaling: true });
      this.showErrorTimeoutId = window.setTimeout(() => {
        this._scaleError.hidden = false;
      }, INPUT_DELAY_MS);
    }
  }
}
customElements.define("scale-input", ScaleInput);

class PageRangeInput extends PrintUIControlMixin(HTMLElement) {
  initialize() {
    super.initialize();

    this._rangeInput = this.querySelector("#custom-range");
    this._rangeInput.title = "";
    this._rangePicker = this.querySelector("#range-picker");
    this._rangePickerEvenOption = this._rangePicker.namedItem("even");
    this._rangeError = this.querySelector("#error-invalid-range");
    this._startRangeOverflowError = this.querySelector(
      "#error-invalid-start-range-overflow"
    );

    this._pagesSet = new Set();

    this.addEventListener("keypress", this);
    this.addEventListener("paste", this);
    document.addEventListener("page-count", this);
  }

  get templateId() {
    return "page-range-template";
  }

  updatePageRange() {
    let isCustom = this._rangePicker.value == "custom";
    let isCurrent = this._rangePicker.value == "current";

    if (!isCurrent) {
      this._currentPage = null;
    }

    if (isCustom) {
      this.validateRangeInput();
    } else if (isCurrent) {
      this._currentPage = this._rangeInput.value =
        this._currentPage || this.getCurrentVisiblePageNumber();
      this.validateRangeInput();
    } else {
      this._pagesSet.clear();

      if (this._rangePicker.value == "odd") {
        for (let i = 1; i <= this._numPages; i += 2) {
          this._pagesSet.add(i);
        }
      } else if (this._rangePicker.value == "even") {
        for (let i = 2; i <= this._numPages; i += 2) {
          this._pagesSet.add(i);
        }
      }

      if (!this._rangeInput.checkValidity()) {
        this._rangeInput.setCustomValidity("");
        this._rangeInput.value = "";
      }
    }

    this.dispatchEvent(new Event("revalidate", { bubbles: true }));

    document.l10n.setAttributes(
      this._rangeError,
      "printui-error-invalid-range",
      {
        numPages: this._numPages,
      }
    );

    // If it's valid, update the page range and hide the error messages.
    // Otherwise, set the appropriate error message
    if (this._rangeInput.validity.valid || !isCustom) {
      window.clearTimeout(this.showErrorTimeoutId);
      this._startRangeOverflowError.hidden = this._rangeError.hidden = true;
    } else {
      this._rangeInput.focus();
    }
  }

  dispatchPageRange(shouldCancel = true) {
    window.clearTimeout(this.showErrorTimeoutId);
    if (
      this._rangeInput.validity.valid ||
      this._rangePicker.value != "custom"
    ) {
      this.dispatchSettingsChange({
        pageRanges: this.formatPageRange(),
      });
    } else {
      if (shouldCancel) {
        this.cancelSettingsChange({ pageRanges: true });
      }
      this.showErrorTimeoutId = window.setTimeout(() => {
        this._rangeError.hidden =
          this._rangeInput.validationMessage != "invalid";
        this._startRangeOverflowError.hidden =
          this._rangeInput.validationMessage != "startRangeOverflow";
      }, INPUT_DELAY_MS);
    }
  }

  // The platform expects pageRanges to be an array of
  // ranges represented by ints.
  // Ex: Printing pages 1-3 would return [1,3]
  // Ex: Printing page 1 would return [1,1]
  // Ex: Printing pages 1-2,4 would return [1,2,4,4]
  formatPageRange() {
    if (
      this._pagesSet.size == 0 ||
      (this._rangePicker.value == "custom" && this._rangeInput.value == "") ||
      this._rangePicker.value == "all"
    ) {
      // Show all pages.
      return [];
    }
    let pages = Array.from(this._pagesSet).sort((a, b) => a - b);

    let formattedRanges = [];
    let startRange = pages[0];
    let endRange = pages[0];
    formattedRanges.push(startRange);

    for (let i = 1; i < pages.length; i++) {
      let currentPage = pages[i - 1];
      let nextPage = pages[i];
      if (nextPage > currentPage + 1) {
        formattedRanges.push(endRange);
        startRange = endRange = nextPage;
        formattedRanges.push(startRange);
      } else {
        endRange = nextPage;
      }
    }
    formattedRanges.push(endRange);

    return formattedRanges;
  }

  update(settings) {
    let { pageRanges, printerName } = settings;

    this.toggleAttribute("all-pages", !pageRanges.length);
    if (!this.printerName) {
      this.printerName = printerName;
    }

    let isValid = this._rangeInput.checkValidity();

    if (this.printerName != printerName && !isValid) {
      this.printerName = printerName;
      this._rangeInput.value = "";
      this.updatePageRange();
      this.dispatchPageRange();
    }
  }

  handleKeypress(e) {
    let char = String.fromCharCode(e.charCode);
    let acceptedChar = char.match(/^[0-9,-]$/);
    if (!acceptedChar && !char.match("\x00") && !e.ctrlKey && !e.metaKey) {
      e.preventDefault();
    }
  }

  handlePaste(e) {
    let paste = (e.clipboardData || window.clipboardData)
      .getData("text")
      .trim();
    if (!paste.match(/^[0-9,-]*$/)) {
      e.preventDefault();
    }
  }

  // This method has been abstracted into a helper for testing purposes
  _validateRangeInput(value, numPages) {
    this._pagesSet.clear();
    var ranges = value.split(",");

    for (let range of ranges) {
      let rangeParts = range.split("-");
      if (rangeParts.length > 2) {
        this._rangeInput.setCustomValidity("invalid");
        this._rangeInput.title = "";
        this._pagesSet.clear();
        return;
      }
      let startRange = parseInt(rangeParts[0], 10);
      let endRange = parseInt(
        rangeParts.length == 2 ? rangeParts[1] : rangeParts[0],
        10
      );

      if (isNaN(startRange) && isNaN(endRange)) {
        continue;
      }

      // If the startRange was not specified, then we infer this
      // to be 1.
      if (isNaN(startRange) && rangeParts[0] == "") {
        startRange = 1;
      }
      // If the end range was not specified, then we infer this
      // to be the total number of pages.
      if (isNaN(endRange) && rangeParts[1] == "") {
        endRange = numPages;
      }

      // Check the range for errors
      if (endRange < startRange) {
        this._rangeInput.setCustomValidity("startRangeOverflow");
        this._pagesSet.clear();
        return;
      } else if (
        startRange > numPages ||
        endRange > numPages ||
        startRange == 0
      ) {
        this._rangeInput.setCustomValidity("invalid");
        this._rangeInput.title = "";
        this._pagesSet.clear();
        return;
      }

      for (let i = startRange; i <= endRange; i++) {
        this._pagesSet.add(i);
      }
    }

    this._rangeInput.setCustomValidity("");
  }

  validateRangeInput() {
    let value = ["custom", "current"].includes(this._rangePicker.value)
      ? this._rangeInput.value
      : "";
    this._validateRangeInput(value, this._numPages);
  }

  getCurrentVisiblePageNumber() {
    let pageNum = parseInt(
      PrintEventHandler.printPreviewEl.lastPreviewBrowser.getAttribute(
        "current-page"
      )
    );
    return isNaN(pageNum) ? 1 : pageNum;
  }

  handleEvent(e) {
    if (e.type == "keypress") {
      if (e.target == this._rangeInput) {
        this.handleKeypress(e);
      }
      return;
    }

    if (e.type === "paste" && e.target == this._rangeInput) {
      this.handlePaste(e);
      return;
    }

    if (e.type == "page-count") {
      let { totalPages } = e.detail;
      // This means we have already handled the page count event
      // and do not need to dispatch another event.
      if (this._numPages == totalPages) {
        return;
      }

      this._numPages = totalPages;
      this._rangeInput.disabled = false;
      this._rangePickerEvenOption.disabled = this._numPages < 2;

      let prevPages = Array.from(this._pagesSet);
      this.updatePageRange();
      if (
        prevPages.length != this._pagesSet.size ||
        !prevPages.every(page => this._pagesSet.has(page))
      ) {
        // If the calculated set of pages has changed then we need to dispatch
        // a new pageRanges setting :(
        // Ideally this would be resolved in the settings code since it should
        // only happen for the "N-" case where pages N through the end of the
        // document are in the range.
        this.dispatchPageRange(false);
      }

      return;
    }

    if (e.target == this._rangePicker) {
      this._rangeInput.hidden = e.target.value != "custom";
      this.updatePageRange();
      this.dispatchPageRange();
      if (!this._rangeInput.hidden) {
        this._rangeInput.select();
      }
    } else if (e.target == this._rangeInput) {
      this._rangeInput.focus();
      if (this._numPages) {
        this.updatePageRange();
        this.dispatchPageRange();
      }
    }
  }
}
customElements.define("page-range-input", PageRangeInput);

class MarginsPicker extends PrintUIControlMixin(HTMLElement) {
  initialize() {
    super.initialize();

    this._marginPicker = this.querySelector("#margins-picker");
    this._customTopMargin = this.querySelector("#custom-margin-top");
    this._customBottomMargin = this.querySelector("#custom-margin-bottom");
    this._customLeftMargin = this.querySelector("#custom-margin-left");
    this._customRightMargin = this.querySelector("#custom-margin-right");
    this._marginError = this.querySelector("#error-invalid-margin");
    this._sizeUnit = null;
    this._toInchesMultiplier = 1;
  }

  get templateId() {
    return "margins-template";
  }

  updateCustomMargins() {
    let newMargins = {
      marginTop: this.toInchValue(this._customTopMargin.value),
      marginBottom: this.toInchValue(this._customBottomMargin.value),
      marginLeft: this.toInchValue(this._customLeftMargin.value),
      marginRight: this.toInchValue(this._customRightMargin.value),
    };

    this.dispatchSettingsChange({
      margins: "custom",
      customMargins: newMargins,
    });
    this._marginError.hidden = true;
  }

  updateMaxValues() {
    let maxWidth = this.toCurrentUnitValue(this._maxWidth);
    let maxHeight = this.toCurrentUnitValue(this._maxHeight);
    this._customTopMargin.max = this.formatMaxAttr(
      maxHeight - this._customBottomMargin.value
    );
    this._customBottomMargin.max = this.formatMaxAttr(
      maxHeight - this._customTopMargin.value
    );
    this._customLeftMargin.max = this.formatMaxAttr(
      maxWidth - this._customRightMargin.value
    );
    this._customRightMargin.max = this.formatMaxAttr(
      maxWidth - this._customLeftMargin.value
    );
  }

  truncateTwoDecimals(val) {
    if (val.split(".")[1].length > 2) {
      let dotIndex = val.indexOf(".");
      return val.slice(0, dotIndex + 3);
    }
    return val;
  }

  formatMaxAttr(val) {
    const strVal = val.toString();
    if (strVal.includes(".")) {
      return this.truncateTwoDecimals(strVal);
    }
    return val;
  }

  formatMargin(target) {
    if (target.value.includes(".")) {
      target.value = this.truncateTwoDecimals(target.value);
    }
  }

  toCurrentUnitValue(val) {
    if (typeof val == "string") {
      val = parseFloat(val);
    }
    return val / this._toInchesMultiplier;
  }

  toInchValue(val) {
    if (typeof val == "string") {
      val = parseFloat(val);
    }
    return val * this._toInchesMultiplier;
  }

  setAllMarginValues(settings) {
    this._customTopMargin.value = this.toCurrentUnitValue(
      settings.customMargins.marginTop
    ).toFixed(2);
    this._customBottomMargin.value = this.toCurrentUnitValue(
      settings.customMargins.marginBottom
    ).toFixed(2);
    this._customLeftMargin.value = this.toCurrentUnitValue(
      settings.customMargins.marginLeft
    ).toFixed(2);
    this._customRightMargin.value = this.toCurrentUnitValue(
      settings.customMargins.marginRight
    ).toFixed(2);
  }

  update(settings) {
    // Re-evaluate which margin options should be enabled whenever the printer or paper changes
    this._toInchesMultiplier =
      settings.paperSizeUnit == settings.kPaperSizeMillimeters
        ? INCHES_PER_MM
        : 1;
    if (
      settings.paperId !== this._paperId ||
      settings.printerName !== this._printerName ||
      settings.orientation !== this._orientation
    ) {
      let enabledMargins = settings.marginOptions;
      for (let option of this._marginPicker.options) {
        option.hidden = !enabledMargins[option.value];
      }
      this._paperId = settings.paperId;
      this._printerName = settings.printerName;
      this._orientation = settings.orientation;

      // Paper dimensions are in the paperSizeUnit. As the margin values are in inches
      // we'll normalize to that when storing max dimensions
      let height =
        this._orientation == 0 ? settings.paperHeight : settings.paperWidth;
      let width =
        this._orientation == 0 ? settings.paperWidth : settings.paperHeight;
      let heightInches =
        Math.round(this._toInchesMultiplier * height * 100) / 100;
      let widthInches =
        Math.round(this._toInchesMultiplier * width * 100) / 100;

      this._maxHeight =
        heightInches -
        settings.unwriteableMarginTop -
        settings.unwriteableMarginBottom;
      this._maxWidth =
        widthInches -
        settings.unwriteableMarginLeft -
        settings.unwriteableMarginRight;

      // The values in custom fields should be initialized to custom margin values
      // and must be overriden if they are no longer valid.
      this.setAllMarginValues(settings);
      this.updateMaxValues();
      this.dispatchEvent(new Event("revalidate", { bubbles: true }));
      this._marginError.hidden = true;
    }

    if (settings.paperSizeUnit !== this._sizeUnit) {
      this._sizeUnit = settings.paperSizeUnit;
      let unitStr =
        this._sizeUnit == settings.kPaperSizeMillimeters ? "mm" : "inches";
      for (let elem of this.querySelectorAll("[data-unit-prefix-l10n-id]")) {
        let l10nId = elem.getAttribute("data-unit-prefix-l10n-id") + unitStr;
        document.l10n.setAttributes(elem, l10nId);
      }
    }

    // We need to ensure we don't override the value if the value should be custom.
    if (this._marginPicker.value != "custom") {
      // Reset the custom margin values if they are not valid and revalidate the form
      if (
        !this._customTopMargin.checkValidity() ||
        !this._customBottomMargin.checkValidity() ||
        !this._customLeftMargin.checkValidity() ||
        !this._customRightMargin.checkValidity()
      ) {
        window.clearTimeout(this.showErrorTimeoutId);
        this.setAllMarginValues(settings);
        this.updateMaxValues();
        this.dispatchEvent(new Event("revalidate", { bubbles: true }));
        this._marginError.hidden = true;
      }
      if (settings.margins == "custom") {
        // Ensure that we display the custom margin boxes
        this.querySelector(".margin-group").hidden = false;
      }
      this._marginPicker.value = settings.margins;
    }
  }

  handleEvent(e) {
    if (e.target == this._marginPicker) {
      let customMargin = e.target.value == "custom";
      this.querySelector(".margin-group").hidden = !customMargin;
      if (customMargin) {
        // Update the custom margin values to ensure consistency
        this.updateCustomMargins();
        return;
      }

      this.dispatchSettingsChange({
        margins: e.target.value,
        customMargins: null,
      });
    }

    if (
      e.target == this._customTopMargin ||
      e.target == this._customBottomMargin ||
      e.target == this._customLeftMargin ||
      e.target == this._customRightMargin
    ) {
      if (e.target.checkValidity()) {
        this.updateMaxValues();
      }
      if (
        this._customTopMargin.validity.valid &&
        this._customBottomMargin.validity.valid &&
        this._customLeftMargin.validity.valid &&
        this._customRightMargin.validity.valid
      ) {
        this.formatMargin(e.target);
        this.updateCustomMargins();
      } else if (e.target.validity.stepMismatch) {
        // If this is the third digit after the decimal point, we should
        // truncate the string.
        this.formatMargin(e.target);
      }
    }

    window.clearTimeout(this.showErrorTimeoutId);
    if (
      this._customTopMargin.validity.valid &&
      this._customBottomMargin.validity.valid &&
      this._customLeftMargin.validity.valid &&
      this._customRightMargin.validity.valid
    ) {
      this._marginError.hidden = true;
    } else {
      this.cancelSettingsChange({ customMargins: true, margins: true });
      this.showErrorTimeoutId = window.setTimeout(() => {
        this._marginError.hidden = false;
      }, INPUT_DELAY_MS);
    }
  }
}
customElements.define("margins-select", MarginsPicker);

class TwistySummary extends PrintUIControlMixin(HTMLElement) {
  get isOpen() {
    return this.closest("details")?.hasAttribute("open");
  }

  get templateId() {
    return "twisty-summary-template";
  }

  initialize() {
    if (this._initialized) {
      return;
    }
    super.initialize();
    this.label = this.querySelector(".label");

    this.addEventListener("click", this);
    let shouldOpen = Services.prefs.getBoolPref(
      "print.more-settings.open",
      false
    );
    this.closest("details").open = shouldOpen;
    this.updateSummary(shouldOpen);
  }

  handleEvent(e) {
    let willOpen = !this.isOpen;
    Services.prefs.setBoolPref("print.more-settings.open", willOpen);
    this.updateSummary(willOpen);
  }

  updateSummary(open) {
    document.l10n.setAttributes(
      this.label,
      open
        ? this.getAttribute("data-open-l10n-id")
        : this.getAttribute("data-closed-l10n-id")
    );
  }
}
customElements.define("twisty-summary", TwistySummary);

class PageCount extends PrintUIControlMixin(HTMLElement) {
  initialize() {
    super.initialize();
    document.addEventListener("page-count", this);
  }

  update(settings) {
    this.numCopies = settings.numCopies;
    this.duplex = settings.duplex;
    this.outputDestination = settings.outputDestination;
    this.render();
  }

  render() {
    if (!this.numCopies || !this.sheetCount) {
      return;
    }

    let sheetCount = this.sheetCount;

    // When printing to a printer (not to a file) update
    // the sheet count to account for duplex printing.
    if (
      this.outputDestination == Ci.nsIPrintSettings.kOutputDestinationPrinter &&
      this.duplex != Ci.nsIPrintSettings.kDuplexNone
    ) {
      sheetCount = Math.ceil(sheetCount / 2);
    }

    sheetCount *= this.numCopies;

    document.l10n.setAttributes(this, "printui-sheets-count", {
      sheetCount,
    });

    // The loading attribute must be removed on first render
    if (this.hasAttribute("loading")) {
      this.removeAttribute("loading");
    }

    if (this.id) {
      // We're showing the sheet count, so let it describe the dialog.
      document.body.setAttribute("aria-describedby", this.id);
    }
  }

  handleEvent(e) {
    this.sheetCount = e.detail.sheetCount;
    this.render();
  }
}
customElements.define("page-count", PageCount);

class PrintBackgrounds extends PrintSettingCheckbox {
  update(settings) {
    super.update(settings);
    let isSimplified = settings.sourceVersion == "simplified";
    this.disabled = isSimplified;
    this.toggleAttribute("disallowed", isSimplified);
    this.checked = !isSimplified && settings.printBackgrounds;
  }
}
customElements.define("print-backgrounds", PrintBackgrounds, {
  extends: "input",
});

class PrintButton extends PrintUIControlMixin(HTMLButtonElement) {
  update(settings) {
    let l10nId =
      settings.printerName == PrintUtils.SAVE_TO_PDF_PRINTER
        ? "printui-primary-button-save"
        : "printui-primary-button";
    document.l10n.setAttributes(this, l10nId);
  }
}
customElements.define("print-button", PrintButton, { extends: "button" });

class CancelButton extends HTMLButtonElement {
  constructor() {
    super();
    this.addEventListener("click", () => {
      this.dispatchEvent(new Event("cancel-print", { bubbles: true }));
    });
  }
}
customElements.define("cancel-button", CancelButton, { extends: "button" });

async function pickFileName(contentTitle, currentURI) {
  let picker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
  let [title] = await document.l10n.formatMessages([
    { id: "printui-save-to-pdf-title" },
  ]);
  title = title.value;

  let filename;
  if (contentTitle != "") {
    filename = contentTitle;
  } else {
    let url = new URL(currentURI);
    let path = decodeURIComponent(url.pathname);
    path = path.replace(/\/$/, "");
    filename = path.split("/").pop();
    if (filename == "") {
      filename = url.hostname;
    }
  }
  if (!filename.endsWith(".pdf")) {
    // macOS and linux don't set the extension based on the default extension.
    // Windows won't add the extension a second time, fortunately.
    // If it already ends with .pdf though, adding it again isn't needed.
    filename += ".pdf";
  }
  filename = DownloadPaths.sanitize(filename);

  picker.init(
    window.docShell.chromeEventHandler.ownerGlobal,
    title,
    Ci.nsIFilePicker.modeSave
  );
  picker.appendFilter("PDF", "*.pdf");
  picker.defaultExtension = "pdf";
  picker.defaultString = filename;

  let retval = await new Promise(resolve => picker.open(resolve));

  if (retval == 1) {
    throw new Error({ reason: "cancelled" });
  } else {
    // OK clicked (retval == 0) or replace confirmed (retval == 2)

    // Workaround: When trying to replace an existing file that is open in another application (i.e. a locked file),
    // the print progress listener is never called. This workaround ensures that a correct status is always returned.
    try {
      let fstream = Cc[
        "@mozilla.org/network/file-output-stream;1"
      ].createInstance(Ci.nsIFileOutputStream);
      fstream.init(picker.file, 0x2a, 0o666, 0); // ioflags = write|create|truncate, file permissions = rw-rw-rw-
      fstream.close();

      // Remove the file to reduce the likelihood of the user opening an empty or damaged fle when the
      // preview is loading
      await IOUtils.remove(picker.file.path);
    } catch (e) {
      throw new Error({ reason: retval == 0 ? "not_saved" : "not_replaced" });
    }
  }

  return picker.file.path;
}