Bug 1867925 - Mark some storage-access-api tests as intermittent after wpt-sync....
[gecko.git] / toolkit / content / aboutSupport.js
blob95e349e6157c8e0523a45f2904e3b165dc8aa04d
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 "use strict";
7 const { Troubleshoot } = ChromeUtils.importESModule(
8   "resource://gre/modules/Troubleshoot.sys.mjs"
9 );
10 const { ResetProfile } = ChromeUtils.importESModule(
11   "resource://gre/modules/ResetProfile.sys.mjs"
13 const { AppConstants } = ChromeUtils.importESModule(
14   "resource://gre/modules/AppConstants.sys.mjs"
17 ChromeUtils.defineESModuleGetters(this, {
18   DownloadUtils: "resource://gre/modules/DownloadUtils.sys.mjs",
19   PlacesDBUtils: "resource://gre/modules/PlacesDBUtils.sys.mjs",
20   ProcessType: "resource://gre/modules/ProcessType.sys.mjs",
21 });
23 window.addEventListener("load", function onload(event) {
24   try {
25     window.removeEventListener("load", onload);
26     Troubleshoot.snapshot().then(async snapshot => {
27       for (let prop in snapshotFormatters) {
28         try {
29           await snapshotFormatters[prop](snapshot[prop]);
30         } catch (e) {
31           console.error(
32             "stack of snapshot error for about:support: ",
33             e,
34             ": ",
35             e.stack
36           );
37         }
38       }
39       if (location.hash) {
40         scrollToSection();
41       }
42     }, console.error);
43     populateActionBox();
44     setupEventListeners();
46     if (Services.sysinfo.getProperty("isPackagedApp")) {
47       $("update-dir-row").hidden = true;
48       $("update-history-row").hidden = true;
49     }
50   } catch (e) {
51     console.error("stack of load error for about:support: ", e, ": ", e.stack);
52   }
53 });
55 function prefsTable(data) {
56   return sortedArrayFromObject(data).map(function ([name, value]) {
57     return $.new("tr", [
58       $.new("td", name, "pref-name"),
59       // Very long preference values can cause users problems when they
60       // copy and paste them into some text editors.  Long values generally
61       // aren't useful anyway, so truncate them to a reasonable length.
62       $.new("td", String(value).substr(0, 120), "pref-value"),
63     ]);
64   });
67 // Fluent uses lisp-case IDs so this converts
68 // the SentenceCase info IDs to lisp-case.
69 const FLUENT_IDENT_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
70 function toFluentID(str) {
71   if (!FLUENT_IDENT_REGEX.test(str)) {
72     return null;
73   }
74   return str
75     .toString()
76     .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
77     .toLowerCase();
80 // Each property in this object corresponds to a property in Troubleshoot.sys.mjs's
81 // snapshot data.  Each function is passed its property's corresponding data,
82 // and it's the function's job to update the page with it.
83 var snapshotFormatters = {
84   async application(data) {
85     $("application-box").textContent = data.name;
86     $("useragent-box").textContent = data.userAgent;
87     $("os-box").textContent = data.osVersion;
88     if (data.osTheme) {
89       $("os-theme-box").textContent = data.osTheme;
90     } else {
91       $("os-theme-row").hidden = true;
92     }
93     if (AppConstants.platform == "macosx") {
94       $("rosetta-box").textContent = data.rosetta;
95     }
96     if (AppConstants.platform == "win") {
97       const translatedList = await Promise.all(
98         data.pointingDevices.map(deviceName => {
99           return document.l10n.formatValue(deviceName);
100         })
101       );
103       const formatter = new Intl.ListFormat();
105       $("pointing-devices-box").textContent = formatter.format(translatedList);
106     }
107     $("binary-box").textContent = Services.dirsvc.get(
108       "XREExeF",
109       Ci.nsIFile
110     ).path;
111     $("supportLink").href = data.supportURL;
112     let version = AppConstants.MOZ_APP_VERSION_DISPLAY;
113     if (data.vendor) {
114       version += " (" + data.vendor + ")";
115     }
116     $("version-box").textContent = version;
117     $("buildid-box").textContent = data.buildID;
118     $("distributionid-box").textContent = data.distributionID;
119     if (data.updateChannel) {
120       $("updatechannel-box").textContent = data.updateChannel;
121     }
122     if (AppConstants.MOZ_UPDATER && AppConstants.platform != "android") {
123       $("update-dir-box").textContent = Services.dirsvc.get(
124         "UpdRootD",
125         Ci.nsIFile
126       ).path;
127     }
128     $("profile-dir-box").textContent = Services.dirsvc.get(
129       "ProfD",
130       Ci.nsIFile
131     ).path;
133     try {
134       let launcherStatusTextId = "launcher-process-status-unknown";
135       switch (data.launcherProcessState) {
136         case 0:
137         case 1:
138         case 2:
139           launcherStatusTextId =
140             "launcher-process-status-" + data.launcherProcessState;
141           break;
142       }
144       document.l10n.setAttributes(
145         $("launcher-process-box"),
146         launcherStatusTextId
147       );
148     } catch (e) {}
150     const STATUS_STRINGS = {
151       experimentControl: "fission-status-experiment-control",
152       experimentTreatment: "fission-status-experiment-treatment",
153       disabledByE10sEnv: "fission-status-disabled-by-e10s-env",
154       enabledByEnv: "fission-status-enabled-by-env",
155       disabledByEnv: "fission-status-disabled-by-env",
156       enabledByDefault: "fission-status-enabled-by-default",
157       disabledByDefault: "fission-status-disabled-by-default",
158       enabledByUserPref: "fission-status-enabled-by-user-pref",
159       disabledByUserPref: "fission-status-disabled-by-user-pref",
160       disabledByE10sOther: "fission-status-disabled-by-e10s-other",
161       enabledByRollout: "fission-status-enabled-by-rollout",
162     };
164     let statusTextId = STATUS_STRINGS[data.fissionDecisionStatus];
166     document.l10n.setAttributes(
167       $("multiprocess-box-process-count"),
168       "multi-process-windows",
169       {
170         remoteWindows: data.numRemoteWindows,
171         totalWindows: data.numTotalWindows,
172       }
173     );
174     document.l10n.setAttributes(
175       $("fission-box-process-count"),
176       "fission-windows",
177       {
178         fissionWindows: data.numFissionWindows,
179         totalWindows: data.numTotalWindows,
180       }
181     );
182     document.l10n.setAttributes($("fission-box-status"), statusTextId);
184     if (Services.policies) {
185       let policiesStrId = "";
186       let aboutPolicies = "about:policies";
187       switch (data.policiesStatus) {
188         case Services.policies.INACTIVE:
189           policiesStrId = "policies-inactive";
190           break;
192         case Services.policies.ACTIVE:
193           policiesStrId = "policies-active";
194           aboutPolicies += "#active";
195           break;
197         default:
198           policiesStrId = "policies-error";
199           aboutPolicies += "#errors";
200           break;
201       }
203       if (data.policiesStatus != Services.policies.INACTIVE) {
204         let activePolicies = $.new("a", null, null, {
205           href: aboutPolicies,
206         });
207         document.l10n.setAttributes(activePolicies, policiesStrId);
208         $("policies-status").appendChild(activePolicies);
209       } else {
210         document.l10n.setAttributes($("policies-status"), policiesStrId);
211       }
212     } else {
213       $("policies-status-row").hidden = true;
214     }
216     let keyLocationServiceGoogleFound = data.keyLocationServiceGoogleFound
217       ? "found"
218       : "missing";
219     document.l10n.setAttributes(
220       $("key-location-service-google-box"),
221       keyLocationServiceGoogleFound
222     );
224     let keySafebrowsingGoogleFound = data.keySafebrowsingGoogleFound
225       ? "found"
226       : "missing";
227     document.l10n.setAttributes(
228       $("key-safebrowsing-google-box"),
229       keySafebrowsingGoogleFound
230     );
232     let keyMozillaFound = data.keyMozillaFound ? "found" : "missing";
233     document.l10n.setAttributes($("key-mozilla-box"), keyMozillaFound);
235     $("safemode-box").textContent = data.safeMode;
237     const formatHumanReadableBytes = (elem, bytes) => {
238       let size = DownloadUtils.convertByteUnits(bytes);
239       document.l10n.setAttributes(elem, "app-basics-data-size", {
240         value: size[0],
241         unit: size[1],
242       });
243     };
245     formatHumanReadableBytes($("memory-size-box"), data.memorySizeBytes);
246     formatHumanReadableBytes($("disk-available-box"), data.diskAvailableBytes);
247   },
249   async legacyUserStylesheets(legacyUserStylesheets) {
250     $("legacyUserStylesheets-enabled").textContent =
251       legacyUserStylesheets.active;
252     $("legacyUserStylesheets-types").textContent =
253       new Intl.ListFormat(undefined, { style: "short", type: "unit" }).format(
254         legacyUserStylesheets.types
255       ) ||
256       document.l10n.setAttributes(
257         $("legacyUserStylesheets-types"),
258         "legacy-user-stylesheets-no-stylesheets-found"
259       );
260   },
262   crashes(data) {
263     if (!AppConstants.MOZ_CRASHREPORTER) {
264       return;
265     }
267     let daysRange = Troubleshoot.kMaxCrashAge / (24 * 60 * 60 * 1000);
268     document.l10n.setAttributes($("crashes"), "report-crash-for-days", {
269       days: daysRange,
270     });
271     let reportURL;
272     try {
273       reportURL = Services.prefs.getCharPref("breakpad.reportURL");
274       // Ignore any non http/https urls
275       if (!/^https?:/i.test(reportURL)) {
276         reportURL = null;
277       }
278     } catch (e) {}
279     if (!reportURL) {
280       $("crashes-noConfig").style.display = "block";
281       $("crashes-noConfig").classList.remove("no-copy");
282       return;
283     }
284     $("crashes-allReports").style.display = "block";
286     if (data.pending > 0) {
287       document.l10n.setAttributes(
288         $("crashes-allReportsWithPending"),
289         "pending-reports",
290         { reports: data.pending }
291       );
292     }
294     let dateNow = new Date();
295     $.append(
296       $("crashes-tbody"),
297       data.submitted.map(function (crash) {
298         let date = new Date(crash.date);
299         let timePassed = dateNow - date;
300         let formattedDateStrId;
301         let formattedDateStrArgs;
302         if (timePassed >= 24 * 60 * 60 * 1000) {
303           let daysPassed = Math.round(timePassed / (24 * 60 * 60 * 1000));
304           formattedDateStrId = "crashes-time-days";
305           formattedDateStrArgs = { days: daysPassed };
306         } else if (timePassed >= 60 * 60 * 1000) {
307           let hoursPassed = Math.round(timePassed / (60 * 60 * 1000));
308           formattedDateStrId = "crashes-time-hours";
309           formattedDateStrArgs = { hours: hoursPassed };
310         } else {
311           let minutesPassed = Math.max(Math.round(timePassed / (60 * 1000)), 1);
312           formattedDateStrId = "crashes-time-minutes";
313           formattedDateStrArgs = { minutes: minutesPassed };
314         }
315         return $.new("tr", [
316           $.new("td", [
317             $.new("a", crash.id, null, { href: reportURL + crash.id }),
318           ]),
319           $.new("td", null, null, {
320             "data-l10n-id": formattedDateStrId,
321             "data-l10n-args": formattedDateStrArgs,
322           }),
323         ]);
324       })
325     );
326   },
328   addons(data) {
329     $.append(
330       $("addons-tbody"),
331       data.map(function (addon) {
332         return $.new("tr", [
333           $.new("td", addon.name),
334           $.new("td", addon.type),
335           $.new("td", addon.version),
336           $.new("td", addon.isActive),
337           $.new("td", addon.id),
338         ]);
339       })
340     );
341   },
343   securitySoftware(data) {
344     if (AppConstants.platform !== "win") {
345       $("security-software").hidden = true;
346       $("security-software-table").hidden = true;
347       return;
348     }
350     $("security-software-antivirus").textContent = data.registeredAntiVirus;
351     $("security-software-antispyware").textContent = data.registeredAntiSpyware;
352     $("security-software-firewall").textContent = data.registeredFirewall;
353   },
355   features(data) {
356     $.append(
357       $("features-tbody"),
358       data.map(function (feature) {
359         return $.new("tr", [
360           $.new("td", feature.name),
361           $.new("td", feature.version),
362           $.new("td", feature.id),
363         ]);
364       })
365     );
366   },
368   async processes(data) {
369     async function buildEntry(name, value) {
370       const fluentName = ProcessType.fluentNameFromProcessTypeString(name);
371       let entryName = (await document.l10n.formatValue(fluentName)) || name;
372       $("processes-tbody").appendChild(
373         $.new("tr", [$.new("td", entryName), $.new("td", value)])
374       );
375     }
377     let remoteProcessesCount = Object.values(data.remoteTypes).reduce(
378       (a, b) => a + b,
379       0
380     );
381     document.querySelector("#remoteprocesses-row a").textContent =
382       remoteProcessesCount;
384     // Display the regular "web" process type first in the list,
385     // and with special formatting.
386     if (data.remoteTypes.web) {
387       await buildEntry(
388         "web",
389         `${data.remoteTypes.web} / ${data.maxWebContentProcesses}`
390       );
391       delete data.remoteTypes.web;
392     }
394     for (let remoteProcessType in data.remoteTypes) {
395       await buildEntry(remoteProcessType, data.remoteTypes[remoteProcessType]);
396     }
397   },
399   async experimentalFeatures(data) {
400     if (!data) {
401       return;
402     }
403     let titleL10nIds = data.map(([titleL10nId]) => titleL10nId);
404     let titleL10nObjects = await document.l10n.formatMessages(titleL10nIds);
405     if (titleL10nObjects.length != data.length) {
406       throw Error("Missing localized title strings in experimental features");
407     }
408     for (let i = 0; i < titleL10nObjects.length; i++) {
409       let localizedTitle = titleL10nObjects[i].attributes.find(
410         a => a.name == "label"
411       ).value;
412       data[i] = [localizedTitle, data[i][1], data[i][2]];
413     }
415     $.append(
416       $("experimental-features-tbody"),
417       data.map(function ([title, pref, value]) {
418         return $.new("tr", [
419           $.new("td", `${title} (${pref})`, "pref-name"),
420           $.new("td", value, "pref-value"),
421         ]);
422       })
423     );
424   },
426   environmentVariables(data) {
427     if (!data) {
428       return;
429     }
430     $.append(
431       $("environment-variables-tbody"),
432       Object.entries(data).map(([name, value]) => {
433         return $.new("tr", [
434           $.new("td", name, "pref-name"),
435           $.new("td", value, "pref-value"),
436         ]);
437       })
438     );
439   },
441   modifiedPreferences(data) {
442     $.append($("prefs-tbody"), prefsTable(data));
443   },
445   lockedPreferences(data) {
446     $.append($("locked-prefs-tbody"), prefsTable(data));
447   },
449   places(data) {
450     if (!AppConstants.MOZ_PLACES) {
451       return;
452     }
453     const statsBody = $("place-database-stats-tbody");
454     $.append(
455       statsBody,
456       data.map(function (entry) {
457         return $.new("tr", [
458           $.new("td", entry.entity),
459           $.new("td", entry.count),
460           $.new("td", entry.sizeBytes / 1024),
461           $.new("td", entry.sizePerc),
462           $.new("td", entry.efficiencyPerc),
463           $.new("td", entry.sequentialityPerc),
464         ]);
465       })
466     );
467     statsBody.style.display = "none";
468     $("place-database-stats-toggle").addEventListener(
469       "click",
470       function (event) {
471         if (statsBody.style.display === "none") {
472           document.l10n.setAttributes(
473             event.target,
474             "place-database-stats-hide"
475           );
476           statsBody.style.display = "";
477         } else {
478           document.l10n.setAttributes(
479             event.target,
480             "place-database-stats-show"
481           );
482           statsBody.style.display = "none";
483         }
484       }
485     );
486   },
488   printingPreferences(data) {
489     if (AppConstants.platform == "android") {
490       return;
491     }
492     const tbody = $("support-printing-prefs-tbody");
493     $.append(tbody, prefsTable(data));
494     $("support-printing-clear-settings-button").addEventListener(
495       "click",
496       function () {
497         for (let name in data) {
498           Services.prefs.clearUserPref(name);
499         }
500         tbody.textContent = "";
501       }
502     );
503   },
505   async graphics(data) {
506     function localizedMsg(msg) {
507       if (typeof msg == "object" && msg.key) {
508         return document.l10n.formatValue(msg.key, msg.args);
509       }
510       let msgId = toFluentID(msg);
511       if (msgId) {
512         return document.l10n.formatValue(msgId);
513       }
514       return "";
515     }
517     // Read APZ info out of data.info, stripping it out in the process.
518     let apzInfo = [];
519     let formatApzInfo = function (info) {
520       let out = [];
521       for (let type of [
522         "Wheel",
523         "Touch",
524         "Drag",
525         "Keyboard",
526         "Autoscroll",
527         "Zooming",
528       ]) {
529         let key = "Apz" + type + "Input";
531         if (!(key in info)) {
532           continue;
533         }
535         delete info[key];
537         out.push(toFluentID(type.toLowerCase() + "Enabled"));
538       }
540       return out;
541     };
543     // Create a <tr> element with key and value columns.
544     //
545     // @key      Text in the key column. Localized automatically, unless starts with "#".
546     // @value    Fluent ID for text in the value column, or array of children.
547     function buildRow(key, value) {
548       let title = key[0] == "#" ? key.substr(1) : key;
549       let keyStrId = toFluentID(key);
550       let valueStrId = Array.isArray(value) ? null : toFluentID(value);
551       let td = $.new("td", value);
552       td.style["white-space"] = "pre-wrap";
553       if (valueStrId) {
554         document.l10n.setAttributes(td, valueStrId);
555       }
557       let th = $.new("th", title, "column");
558       if (!key.startsWith("#")) {
559         document.l10n.setAttributes(th, keyStrId);
560       }
561       return $.new("tr", [th, td]);
562     }
564     // @where    The name in "graphics-<name>-tbody", of the element to append to.
565     // @trs      Array of row elements.
566     function addRows(where, trs) {
567       $.append($("graphics-" + where + "-tbody"), trs);
568     }
570     // Build and append a row.
571     //
572     // @where    The name in "graphics-<name>-tbody", of the element to append to.
573     function addRow(where, key, value) {
574       addRows(where, [buildRow(key, value)]);
575     }
576     if ("info" in data) {
577       apzInfo = formatApzInfo(data.info);
579       let trs = sortedArrayFromObject(data.info).map(function ([prop, val]) {
580         let td = $.new("td", String(val));
581         td.style["word-break"] = "break-all";
582         return $.new("tr", [$.new("th", prop, "column"), td]);
583       });
584       addRows("diagnostics", trs);
586       delete data.info;
587     }
589     let windowUtils = window.windowUtils;
590     let gpuProcessPid = windowUtils.gpuProcessPid;
592     if (gpuProcessPid != -1) {
593       let gpuProcessKillButton = null;
594       if (AppConstants.NIGHTLY_BUILD || AppConstants.MOZ_DEV_EDITION) {
595         gpuProcessKillButton = $.new("button");
597         gpuProcessKillButton.addEventListener("click", function () {
598           windowUtils.terminateGPUProcess();
599         });
601         document.l10n.setAttributes(
602           gpuProcessKillButton,
603           "gpu-process-kill-button"
604         );
605       }
607       addRow("diagnostics", "gpu-process-pid", [new Text(gpuProcessPid)]);
608       if (gpuProcessKillButton) {
609         addRow("diagnostics", "gpu-process", [gpuProcessKillButton]);
610       }
611     }
613     if (
614       (AppConstants.NIGHTLY_BUILD || AppConstants.MOZ_DEV_EDITION) &&
615       AppConstants.platform != "macosx"
616     ) {
617       let gpuDeviceResetButton = $.new("button");
619       gpuDeviceResetButton.addEventListener("click", function () {
620         windowUtils.triggerDeviceReset();
621       });
623       document.l10n.setAttributes(
624         gpuDeviceResetButton,
625         "gpu-device-reset-button"
626       );
627       addRow("diagnostics", "gpu-device-reset", [gpuDeviceResetButton]);
628     }
630     // graphics-failures-tbody tbody
631     if ("failures" in data) {
632       // If indices is there, it should be the same length as failures,
633       // (see Troubleshoot.sys.mjs) but we check anyway:
634       if ("indices" in data && data.failures.length == data.indices.length) {
635         let combined = [];
636         for (let i = 0; i < data.failures.length; i++) {
637           let assembled = assembleFromGraphicsFailure(i, data);
638           combined.push(assembled);
639         }
640         combined.sort(function (a, b) {
641           if (a.index < b.index) {
642             return -1;
643           }
644           if (a.index > b.index) {
645             return 1;
646           }
647           return 0;
648         });
649         $.append(
650           $("graphics-failures-tbody"),
651           combined.map(function (val) {
652             return $.new("tr", [
653               $.new("th", val.header, "column"),
654               $.new("td", val.message),
655             ]);
656           })
657         );
658         delete data.indices;
659       } else {
660         $.append($("graphics-failures-tbody"), [
661           $.new("tr", [
662             $.new("th", "LogFailure", "column"),
663             $.new(
664               "td",
665               data.failures.map(function (val) {
666                 return $.new("p", val);
667               })
668             ),
669           ]),
670         ]);
671       }
672       delete data.failures;
673     } else {
674       $("graphics-failures-tbody").style.display = "none";
675     }
677     // Add a new row to the table, and take the key (or keys) out of data.
678     //
679     // @where        Table section to add to.
680     // @key          Data key to use.
681     // @colKey       The localization key to use, if different from key.
682     async function addRowFromKey(where, key, colKey) {
683       if (!(key in data)) {
684         return;
685       }
686       colKey = colKey || key;
688       let value;
689       let messageKey = key + "Message";
690       if (messageKey in data) {
691         value = await localizedMsg(data[messageKey]);
692         delete data[messageKey];
693       } else {
694         value = data[key];
695       }
696       delete data[key];
698       if (value) {
699         addRow(where, colKey, [new Text(value)]);
700       }
701     }
703     // graphics-features-tbody
704     let devicePixelRatios = data.graphicsDevicePixelRatios;
705     addRow("features", "graphicsDevicePixelRatios", [
706       new Text(devicePixelRatios),
707     ]);
709     let compositor = "";
710     if (data.windowLayerManagerRemote) {
711       compositor = data.windowLayerManagerType;
712     } else {
713       let noOMTCString = await document.l10n.formatValue("main-thread-no-omtc");
714       compositor = "BasicLayers (" + noOMTCString + ")";
715     }
716     addRow("features", "compositing", [new Text(compositor)]);
717     delete data.windowLayerManagerRemote;
718     delete data.windowLayerManagerType;
719     delete data.numTotalWindows;
720     delete data.numAcceleratedWindows;
721     delete data.numAcceleratedWindowsMessage;
722     delete data.graphicsDevicePixelRatios;
724     addRow(
725       "features",
726       "asyncPanZoom",
727       apzInfo.length
728         ? [
729             new Text(
730               (
731                 await document.l10n.formatValues(
732                   apzInfo.map(id => {
733                     return { id };
734                   })
735                 )
736               ).join("; ")
737             ),
738           ]
739         : "apz-none"
740     );
741     let featureKeys = [
742       "webgl1WSIInfo",
743       "webgl1Renderer",
744       "webgl1Version",
745       "webgl1DriverExtensions",
746       "webgl1Extensions",
747       "webgl2WSIInfo",
748       "webgl2Renderer",
749       "webgl2Version",
750       "webgl2DriverExtensions",
751       "webgl2Extensions",
752       ["supportsHardwareH264", "hardware-h264"],
753       ["direct2DEnabled", "#Direct2D"],
754       ["windowProtocol", "graphics-window-protocol"],
755       ["desktopEnvironment", "graphics-desktop-environment"],
756       "targetFrameRate",
757     ];
758     for (let feature of featureKeys) {
759       if (Array.isArray(feature)) {
760         await addRowFromKey("features", feature[0], feature[1]);
761         continue;
762       }
763       await addRowFromKey("features", feature);
764     }
766     featureKeys = ["webgpuDefaultAdapter", "webgpuFallbackAdapter"];
767     for (let feature of featureKeys) {
768       const obj = data[feature];
769       if (obj) {
770         const str = JSON.stringify(obj, null, "  ");
771         await addRow("features", feature, [new Text(str)]);
772         delete data[feature];
773       }
774     }
776     if ("directWriteEnabled" in data) {
777       let message = data.directWriteEnabled;
778       if ("directWriteVersion" in data) {
779         message += " (" + data.directWriteVersion + ")";
780       }
781       await addRow("features", "#DirectWrite", [new Text(message)]);
782       delete data.directWriteEnabled;
783       delete data.directWriteVersion;
784     }
786     // Adapter tbodies.
787     let adapterKeys = [
788       ["adapterDescription", "gpu-description"],
789       ["adapterVendorID", "gpu-vendor-id"],
790       ["adapterDeviceID", "gpu-device-id"],
791       ["driverVendor", "gpu-driver-vendor"],
792       ["driverVersion", "gpu-driver-version"],
793       ["driverDate", "gpu-driver-date"],
794       ["adapterDrivers", "gpu-drivers"],
795       ["adapterSubsysID", "gpu-subsys-id"],
796       ["adapterRAM", "gpu-ram"],
797     ];
799     function showGpu(id, suffix) {
800       function get(prop) {
801         return data[prop + suffix];
802       }
804       let trs = [];
805       for (let [prop, key] of adapterKeys) {
806         let value = get(prop);
807         if (value === undefined || value === "") {
808           continue;
809         }
810         trs.push(buildRow(key, [new Text(value)]));
811       }
813       if (!trs.length) {
814         $("graphics-" + id + "-tbody").style.display = "none";
815         return;
816       }
818       let active = "yes";
819       if ("isGPU2Active" in data && (suffix == "2") != data.isGPU2Active) {
820         active = "no";
821       }
823       addRow(id, "gpu-active", active);
824       addRows(id, trs);
825     }
826     showGpu("gpu-1", "");
827     showGpu("gpu-2", "2");
829     // Remove adapter keys.
830     for (let [prop /* key */] of adapterKeys) {
831       delete data[prop];
832       delete data[prop + "2"];
833     }
834     delete data.isGPU2Active;
836     let featureLog = data.featureLog;
837     delete data.featureLog;
839     if (featureLog.features.length) {
840       for (let feature of featureLog.features) {
841         let trs = [];
842         for (let entry of feature.log) {
843           let bugNumber;
844           if (entry.hasOwnProperty("failureId")) {
845             // This is a failure ID. See nsIGfxInfo.idl.
846             let m = /BUG_(\d+)/.exec(entry.failureId);
847             if (m) {
848               bugNumber = m[1];
849             }
850           }
852           let failureIdSpan = $.new("span", "");
853           if (bugNumber) {
854             let bugHref = $.new("a");
855             bugHref.href =
856               "https://bugzilla.mozilla.org/show_bug.cgi?id=" + bugNumber;
857             bugHref.setAttribute("data-l10n-name", "bug-link");
858             failureIdSpan.append(bugHref);
859             document.l10n.setAttributes(
860               failureIdSpan,
861               "support-blocklisted-bug",
862               {
863                 bugNumber,
864               }
865             );
866           } else if (
867             entry.hasOwnProperty("failureId") &&
868             entry.failureId.length
869           ) {
870             document.l10n.setAttributes(failureIdSpan, "unknown-failure", {
871               failureCode: entry.failureId,
872             });
873           }
875           let messageSpan = $.new("span", "");
876           if (entry.hasOwnProperty("message") && entry.message.length) {
877             messageSpan.innerText = entry.message;
878           }
880           let typeCol = $.new("td", entry.type);
881           let statusCol = $.new("td", entry.status);
882           let messageCol = $.new("td", "");
883           let failureIdCol = $.new("td", "");
884           typeCol.style.width = "10%";
885           statusCol.style.width = "10%";
886           messageCol.style.width = "30%";
887           messageCol.appendChild(messageSpan);
888           failureIdCol.style.width = "50%";
889           failureIdCol.appendChild(failureIdSpan);
891           trs.push($.new("tr", [typeCol, statusCol, messageCol, failureIdCol]));
892         }
893         addRow("decisions", "#" + feature.name, [$.new("table", trs)]);
894       }
895     } else {
896       $("graphics-decisions-tbody").style.display = "none";
897     }
899     if (featureLog.fallbacks.length) {
900       for (let fallback of featureLog.fallbacks) {
901         addRow("workarounds", "#" + fallback.name, [
902           new Text(fallback.message),
903         ]);
904       }
905     } else {
906       $("graphics-workarounds-tbody").style.display = "none";
907     }
909     let crashGuards = data.crashGuards;
910     delete data.crashGuards;
912     if (crashGuards.length) {
913       for (let guard of crashGuards) {
914         let resetButton = $.new("button");
915         let onClickReset = function () {
916           Services.prefs.setIntPref(guard.prefName, 0);
917           resetButton.removeEventListener("click", onClickReset);
918           resetButton.disabled = true;
919         };
921         document.l10n.setAttributes(resetButton, "reset-on-next-restart");
922         resetButton.addEventListener("click", onClickReset);
924         addRow("crashguards", guard.type + "CrashGuard", [resetButton]);
925       }
926     } else {
927       $("graphics-crashguards-tbody").style.display = "none";
928     }
930     // Now that we're done, grab any remaining keys in data and drop them into
931     // the diagnostics section.
932     for (let key in data) {
933       let value = data[key];
934       addRow("diagnostics", key, [new Text(value)]);
935     }
936   },
938   async media(data) {
939     function insertBasicInfo(key, value) {
940       function createRow(key, value) {
941         let th = $.new("th", null, "column");
942         document.l10n.setAttributes(th, key);
943         let td = $.new("td", value);
944         td.style["white-space"] = "pre-wrap";
945         td.colSpan = 8;
946         return $.new("tr", [th, td]);
947       }
948       $.append($("media-info-tbody"), [createRow(key, value)]);
949     }
951     function createDeviceInfoRow(device) {
952       let deviceInfo = Ci.nsIAudioDeviceInfo;
954       let states = {};
955       states[deviceInfo.STATE_DISABLED] = "Disabled";
956       states[deviceInfo.STATE_UNPLUGGED] = "Unplugged";
957       states[deviceInfo.STATE_ENABLED] = "Enabled";
959       let preferreds = {};
960       preferreds[deviceInfo.PREF_NONE] = "None";
961       preferreds[deviceInfo.PREF_MULTIMEDIA] = "Multimedia";
962       preferreds[deviceInfo.PREF_VOICE] = "Voice";
963       preferreds[deviceInfo.PREF_NOTIFICATION] = "Notification";
964       preferreds[deviceInfo.PREF_ALL] = "All";
966       let formats = {};
967       formats[deviceInfo.FMT_S16LE] = "S16LE";
968       formats[deviceInfo.FMT_S16BE] = "S16BE";
969       formats[deviceInfo.FMT_F32LE] = "F32LE";
970       formats[deviceInfo.FMT_F32BE] = "F32BE";
972       function toPreferredString(preferred) {
973         if (preferred == deviceInfo.PREF_NONE) {
974           return preferreds[deviceInfo.PREF_NONE];
975         } else if (preferred & deviceInfo.PREF_ALL) {
976           return preferreds[deviceInfo.PREF_ALL];
977         }
978         let str = "";
979         for (let pref of [
980           deviceInfo.PREF_MULTIMEDIA,
981           deviceInfo.PREF_VOICE,
982           deviceInfo.PREF_NOTIFICATION,
983         ]) {
984           if (preferred & pref) {
985             str += " " + preferreds[pref];
986           }
987         }
988         return str;
989       }
991       function toFromatString(dev) {
992         let str = "default: " + formats[dev.defaultFormat] + ", support:";
993         for (let fmt of [
994           deviceInfo.FMT_S16LE,
995           deviceInfo.FMT_S16BE,
996           deviceInfo.FMT_F32LE,
997           deviceInfo.FMT_F32BE,
998         ]) {
999           if (dev.supportedFormat & fmt) {
1000             str += " " + formats[fmt];
1001           }
1002         }
1003         return str;
1004       }
1006       function toRateString(dev) {
1007         return (
1008           "default: " +
1009           dev.defaultRate +
1010           ", support: " +
1011           dev.minRate +
1012           " - " +
1013           dev.maxRate
1014         );
1015       }
1017       function toLatencyString(dev) {
1018         return dev.minLatency + " - " + dev.maxLatency;
1019       }
1021       return $.new("tr", [
1022         $.new("td", device.name),
1023         $.new("td", device.groupId),
1024         $.new("td", device.vendor),
1025         $.new("td", states[device.state]),
1026         $.new("td", toPreferredString(device.preferred)),
1027         $.new("td", toFromatString(device)),
1028         $.new("td", device.maxChannels),
1029         $.new("td", toRateString(device)),
1030         $.new("td", toLatencyString(device)),
1031       ]);
1032     }
1034     function insertDeviceInfo(side, devices) {
1035       let rows = [];
1036       for (let dev of devices) {
1037         rows.push(createDeviceInfoRow(dev));
1038       }
1039       $.append($("media-" + side + "-devices-tbody"), rows);
1040     }
1042     function insertEnumerateDatabase() {
1043       if (
1044         !Services.prefs.getBoolPref("media.mediacapabilities.from-database")
1045       ) {
1046         $("media-capabilities-tbody").style.display = "none";
1047         return;
1048       }
1049       let button = $("enumerate-database-button");
1050       if (button) {
1051         button.addEventListener("click", function (event) {
1052           let { KeyValueService } = ChromeUtils.importESModule(
1053             "resource://gre/modules/kvstore.sys.mjs"
1054           );
1055           let currProfDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
1056           currProfDir.append("mediacapabilities");
1057           let path = currProfDir.path;
1059           function enumerateDatabase(name) {
1060             KeyValueService.getOrCreate(path, name)
1061               .then(database => {
1062                 return database.enumerate();
1063               })
1064               .then(enumerator => {
1065                 var logs = [];
1066                 logs.push(`${name}:`);
1067                 while (enumerator.hasMoreElements()) {
1068                   const { key, value } = enumerator.getNext();
1069                   logs.push(`${key}: ${value}`);
1070                 }
1071                 $("enumerate-database-result").textContent +=
1072                   logs.join("\n") + "\n";
1073               })
1074               .catch(err => {
1075                 $("enumerate-database-result").textContent += `${name}:\n`;
1076               });
1077           }
1079           $("enumerate-database-result").style.display = "block";
1080           $("enumerate-database-result").classList.remove("no-copy");
1081           $("enumerate-database-result").textContent = "";
1083           enumerateDatabase("video/av1");
1084           enumerateDatabase("video/vp8");
1085           enumerateDatabase("video/vp9");
1086           enumerateDatabase("video/avc");
1087           enumerateDatabase("video/theora");
1088         });
1089       }
1090     }
1092     function roundtripAudioLatency() {
1093       insertBasicInfo("roundtrip-latency", "...");
1094       window.windowUtils
1095         .defaultDevicesRoundTripLatency()
1096         .then(latency => {
1097           var latencyString = `${(latency[0] * 1000).toFixed(2)}ms (${(
1098             latency[1] * 1000
1099           ).toFixed(2)})`;
1100           data.defaultDevicesRoundTripLatency = latencyString;
1101           document.querySelector(
1102             'th[data-l10n-id="roundtrip-latency"]'
1103           ).nextSibling.textContent = latencyString;
1104         })
1105         .catch(e => {});
1106     }
1108     function createCDMInfoRow(cdmInfo) {
1109       function findElementInArray(array, name) {
1110         const rv = array.find(element => element.includes(name));
1111         return rv ? rv.split("=")[1] : "Unknown";
1112       }
1114       function getAudioRobustness(array) {
1115         return findElementInArray(array, "audio-robustness");
1116       }
1118       function getVideoRobustness(array) {
1119         return findElementInArray(array, "video-robustness");
1120       }
1122       function getSupportedCodecs(array) {
1123         const mp4Content = findElementInArray(array, "MP4");
1124         const webContent = findElementInArray(array, "WEBM");
1126         const mp4DecodingAndDecryptingCodecs = mp4Content
1127           .match(/decoding-and-decrypting:\[([^\]]*)\]/)[1]
1128           .split(",");
1129         const webmDecodingAndDecryptingCodecs = webContent
1130           .match(/decoding-and-decrypting:\[([^\]]*)\]/)[1]
1131           .split(",");
1133         const mp4DecryptingOnlyCodecs = mp4Content
1134           .match(/decrypting-only:\[([^\]]*)\]/)[1]
1135           .split(",");
1136         const webmDecryptingOnlyCodecs = webContent
1137           .match(/decrypting-only:\[([^\]]*)\]/)[1]
1138           .split(",");
1140         // Combine and get unique codecs for decoding-and-decrypting (always)
1141         // and decrypting-only (only set when it's not empty)
1142         let rv = {};
1143         rv.decodingAndDecrypting = [
1144           ...new Set(
1145             [
1146               ...mp4DecodingAndDecryptingCodecs,
1147               ...webmDecodingAndDecryptingCodecs,
1148             ].filter(Boolean)
1149           ),
1150         ];
1151         let temp = [
1152           ...new Set(
1153             [...mp4DecryptingOnlyCodecs, ...webmDecryptingOnlyCodecs].filter(
1154               Boolean
1155             )
1156           ),
1157         ];
1158         if (temp.length) {
1159           rv.decryptingOnly = temp;
1160         }
1161         return rv;
1162       }
1164       function getCapabilities(array) {
1165         let capabilities = {};
1166         capabilities.persistent = findElementInArray(array, "persistent");
1167         capabilities.distinctive = findElementInArray(array, "distinctive");
1168         capabilities.sessionType = findElementInArray(array, "sessionType");
1169         capabilities.scheme = findElementInArray(array, "scheme");
1170         capabilities.codec = getSupportedCodecs(array);
1171         return JSON.stringify(capabilities);
1172       }
1174       const rvArray = cdmInfo.capabilities.split(" ");
1175       return $.new("tr", [
1176         $.new("td", cdmInfo.keySystemName),
1177         $.new("td", getVideoRobustness(rvArray)),
1178         $.new("td", getAudioRobustness(rvArray)),
1179         $.new("td", getCapabilities(rvArray)),
1180         $.new("td", cdmInfo.clearlead ? "Yes" : "No"),
1181       ]);
1182     }
1184     async function insertContentDecryptionModuleInfo() {
1185       let rows = [];
1186       // Retrieve information from GMPCDM
1187       let cdmInfo =
1188         await ChromeUtils.getGMPContentDecryptionModuleInformation();
1189       for (let info of cdmInfo) {
1190         rows.push(createCDMInfoRow(info));
1191       }
1192       // Retrieve information from WMFCDM, only works when MOZ_WMF_CDM is true
1193       if (ChromeUtils.getWMFContentDecryptionModuleInformation !== undefined) {
1194         cdmInfo = await ChromeUtils.getWMFContentDecryptionModuleInformation();
1195         for (let info of cdmInfo) {
1196           rows.push(createCDMInfoRow(info));
1197         }
1198       }
1199       $.append($("media-content-decryption-modules-tbody"), rows);
1200     }
1202     // Basic information
1203     insertBasicInfo("audio-backend", data.currentAudioBackend);
1204     insertBasicInfo("max-audio-channels", data.currentMaxAudioChannels);
1205     insertBasicInfo("sample-rate", data.currentPreferredSampleRate);
1207     if (AppConstants.platform == "macosx") {
1208       var micStatus = {};
1209       let permission = Cc["@mozilla.org/ospermissionrequest;1"].getService(
1210         Ci.nsIOSPermissionRequest
1211       );
1212       permission.getAudioCapturePermissionState(micStatus);
1213       if (micStatus.value == permission.PERMISSION_STATE_AUTHORIZED) {
1214         roundtripAudioLatency();
1215       }
1216     } else {
1217       roundtripAudioLatency();
1218     }
1220     // Output devices information
1221     insertDeviceInfo("output", data.audioOutputDevices);
1223     // Input devices information
1224     insertDeviceInfo("input", data.audioInputDevices);
1226     // Media Capabilitites
1227     insertEnumerateDatabase();
1229     // Create codec support matrix if possible
1230     let supportInfo = null;
1231     if (data.codecSupportInfo.length) {
1232       const [
1233         supportText,
1234         unsupportedText,
1235         codecNameHeaderText,
1236         codecSWDecodeText,
1237         codecHWDecodeText,
1238         lackOfExtensionText,
1239       ] = await document.l10n.formatValues([
1240         "media-codec-support-supported",
1241         "media-codec-support-unsupported",
1242         "media-codec-support-codec-name",
1243         "media-codec-support-sw-decoding",
1244         "media-codec-support-hw-decoding",
1245         "media-codec-support-lack-of-extension",
1246       ]);
1248       function formatCodecRowHeader(a, b, c) {
1249         let h1 = $.new("th", a);
1250         let h2 = $.new("th", b);
1251         let h3 = $.new("th", c);
1252         h1.classList.add("codec-table-name");
1253         h2.classList.add("codec-table-sw");
1254         h3.classList.add("codec-table-hw");
1255         return $.new("tr", [h1, h2, h3]);
1256       }
1258       function formatCodecRow(codec, sw, hw) {
1259         let swCell = $.new("td", sw ? supportText : unsupportedText);
1260         let hwCell = $.new("td", hw ? supportText : unsupportedText);
1261         if (sw) {
1262           swCell.classList.add("supported");
1263         } else {
1264           swCell.classList.add("unsupported");
1265         }
1266         if (hw) {
1267           hwCell.classList.add("supported");
1268         } else {
1269           hwCell.classList.add("unsupported");
1270         }
1271         return $.new("tr", [$.new("td", codec), swCell, hwCell]);
1272       }
1274       function formatCodecRowForLackOfExtension(codec, sw) {
1275         let swCell = $.new("td", sw ? supportText : unsupportedText);
1276         // Link to AV1 extension on MS store.
1277         let hwCell = $.new("td", [
1278           $.new("a", lackOfExtensionText, null, {
1279             href: "ms-windows-store://pdp/?ProductId=9MVZQVXJBQ9V",
1280           }),
1281         ]);
1282         if (sw) {
1283           swCell.classList.add("supported");
1284         } else {
1285           swCell.classList.add("unsupported");
1286         }
1287         hwCell.classList.add("lack-of-extension");
1288         return $.new("tr", [$.new("td", codec), swCell, hwCell]);
1289       }
1291       // Parse codec support string and create dictionary containing
1292       // SW/HW support information for each codec found
1293       let codecs = {};
1294       for (const codec_string of data.codecSupportInfo.split("\n")) {
1295         const s = codec_string.split(" ");
1296         const codec_name = s[0];
1297         const codec_support = s.slice(1);
1299         if (!(codec_name in codecs)) {
1300           codecs[codec_name] = {
1301             name: codec_name,
1302             sw: false,
1303             hw: false,
1304             lackOfExtension: false,
1305           };
1306         }
1308         if (codec_support.includes("SW")) {
1309           codecs[codec_name].sw = true;
1310         }
1311         if (codec_support.includes("HW")) {
1312           codecs[codec_name].hw = true;
1313         }
1314         if (codec_support.includes("LACK_OF_EXTENSION")) {
1315           codecs[codec_name].lackOfExtension = true;
1316         }
1317       }
1319       // Create row in support table for each codec
1320       let codecSupportRows = [];
1321       for (const c in codecs) {
1322         if (!codecs.hasOwnProperty(c)) {
1323           continue;
1324         }
1325         if (codecs[c].lackOfExtension) {
1326           codecSupportRows.push(
1327             formatCodecRowForLackOfExtension(codecs[c].name, codecs[c].sw)
1328           );
1329         } else {
1330           codecSupportRows.push(
1331             formatCodecRow(codecs[c].name, codecs[c].sw, codecs[c].hw)
1332           );
1333         }
1334       }
1336       let codecSupportTable = $.new("table", [
1337         formatCodecRowHeader(
1338           codecNameHeaderText,
1339           codecSWDecodeText,
1340           codecHWDecodeText
1341         ),
1342         $.new("tbody", codecSupportRows),
1343       ]);
1344       codecSupportTable.id = "codec-table";
1345       supportInfo = [codecSupportTable];
1346     } else {
1347       // Don't have access to codec support information
1348       supportInfo = await document.l10n.formatValue(
1349         "media-codec-support-error"
1350       );
1351     }
1352     if (["win", "macosx", "linux", "android"].includes(AppConstants.platform)) {
1353       insertBasicInfo("media-codec-support-info", supportInfo);
1354     }
1356     // CDM info
1357     insertContentDecryptionModuleInfo();
1358   },
1360   remoteAgent(data) {
1361     if (!AppConstants.ENABLE_WEBDRIVER) {
1362       return;
1363     }
1364     $("remote-debugging-accepting-connections").textContent = data.running;
1365     $("remote-debugging-url").textContent = data.url;
1366   },
1368   accessibility(data) {
1369     $("a11y-activated").textContent = data.isActive;
1370     $("a11y-force-disabled").textContent = data.forceDisabled || 0;
1372     let a11yInstantiator = $("a11y-instantiator");
1373     if (a11yInstantiator) {
1374       a11yInstantiator.textContent = data.instantiator;
1375     }
1376   },
1378   startupCache(data) {
1379     $("startup-cache-disk-cache-path").textContent = data.DiskCachePath;
1380     $("startup-cache-ignore-disk-cache").textContent = data.IgnoreDiskCache;
1381     $("startup-cache-found-disk-cache-on-init").textContent =
1382       data.FoundDiskCacheOnInit;
1383     $("startup-cache-wrote-to-disk-cache").textContent = data.WroteToDiskCache;
1384   },
1386   libraryVersions(data) {
1387     let trs = [
1388       $.new("tr", [
1389         $.new("th", ""),
1390         $.new("th", null, null, { "data-l10n-id": "min-lib-versions" }),
1391         $.new("th", null, null, { "data-l10n-id": "loaded-lib-versions" }),
1392       ]),
1393     ];
1394     sortedArrayFromObject(data).forEach(function ([name, val]) {
1395       trs.push(
1396         $.new("tr", [
1397           $.new("td", name),
1398           $.new("td", val.minVersion),
1399           $.new("td", val.version),
1400         ])
1401       );
1402     });
1403     $.append($("libversions-tbody"), trs);
1404   },
1406   userJS(data) {
1407     if (!data.exists) {
1408       return;
1409     }
1410     let userJSFile = Services.dirsvc.get("PrefD", Ci.nsIFile);
1411     userJSFile.append("user.js");
1412     $("prefs-user-js-link").href = Services.io.newFileURI(userJSFile).spec;
1413     $("prefs-user-js-section").style.display = "";
1414     // Clear the no-copy class
1415     $("prefs-user-js-section").className = "";
1416   },
1418   sandbox(data) {
1419     if (!AppConstants.MOZ_SANDBOX) {
1420       return;
1421     }
1423     let tbody = $("sandbox-tbody");
1424     for (let key in data) {
1425       // Simplify the display a little in the common case.
1426       if (
1427         key === "hasPrivilegedUserNamespaces" &&
1428         data[key] === data.hasUserNamespaces
1429       ) {
1430         continue;
1431       }
1432       if (key === "syscallLog") {
1433         // Not in this table.
1434         continue;
1435       }
1436       let keyStrId = toFluentID(key);
1437       let th = $.new("th", null, "column");
1438       document.l10n.setAttributes(th, keyStrId);
1439       tbody.appendChild($.new("tr", [th, $.new("td", data[key])]));
1440     }
1442     if ("syscallLog" in data) {
1443       let syscallBody = $("sandbox-syscalls-tbody");
1444       let argsHead = $("sandbox-syscalls-argshead");
1445       for (let syscall of data.syscallLog) {
1446         if (argsHead.colSpan < syscall.args.length) {
1447           argsHead.colSpan = syscall.args.length;
1448         }
1449         let procTypeStrId = toFluentID(syscall.procType);
1450         let cells = [
1451           $.new("td", syscall.index, "integer"),
1452           $.new("td", syscall.msecAgo / 1000),
1453           $.new("td", syscall.pid, "integer"),
1454           $.new("td", syscall.tid, "integer"),
1455           $.new("td", null, null, {
1456             "data-l10n-id": "sandbox-proc-type-" + procTypeStrId,
1457           }),
1458           $.new("td", syscall.syscall, "integer"),
1459         ];
1460         for (let arg of syscall.args) {
1461           cells.push($.new("td", arg, "integer"));
1462         }
1463         syscallBody.appendChild($.new("tr", cells));
1464       }
1465     }
1466   },
1468   intl(data) {
1469     $("intl-locale-requested").textContent = JSON.stringify(
1470       data.localeService.requested
1471     );
1472     $("intl-locale-available").textContent = JSON.stringify(
1473       data.localeService.available
1474     );
1475     $("intl-locale-supported").textContent = JSON.stringify(
1476       data.localeService.supported
1477     );
1478     $("intl-locale-regionalprefs").textContent = JSON.stringify(
1479       data.localeService.regionalPrefs
1480     );
1481     $("intl-locale-default").textContent = JSON.stringify(
1482       data.localeService.defaultLocale
1483     );
1485     $("intl-osprefs-systemlocales").textContent = JSON.stringify(
1486       data.osPrefs.systemLocales
1487     );
1488     $("intl-osprefs-regionalprefs").textContent = JSON.stringify(
1489       data.osPrefs.regionalPrefsLocales
1490     );
1491   },
1493   normandy(data) {
1494     if (!data) {
1495       return;
1496     }
1498     const {
1499       prefStudies,
1500       addonStudies,
1501       prefRollouts,
1502       nimbusExperiments,
1503       nimbusRollouts,
1504     } = data;
1505     $.append(
1506       $("remote-features-tbody"),
1507       prefRollouts.map(({ slug, state }) =>
1508         $.new("tr", [
1509           $.new("td", [document.createTextNode(slug)]),
1510           $.new("td", [document.createTextNode(state)]),
1511         ])
1512       )
1513     );
1515     $.append(
1516       $("remote-features-tbody"),
1517       nimbusRollouts.map(({ userFacingName, branch }) =>
1518         $.new("tr", [
1519           $.new("td", [document.createTextNode(userFacingName)]),
1520           $.new("td", [document.createTextNode(`(${branch.slug})`)]),
1521         ])
1522       )
1523     );
1524     $.append(
1525       $("remote-experiments-tbody"),
1526       [addonStudies, prefStudies, nimbusExperiments]
1527         .flat()
1528         .map(({ userFacingName, branch }) =>
1529           $.new("tr", [
1530             $.new("td", [document.createTextNode(userFacingName)]),
1531             $.new("td", [document.createTextNode(branch?.slug || branch)]),
1532           ])
1533         )
1534     );
1535   },
1538 var $ = document.getElementById.bind(document);
1540 $.new = function $_new(tag, textContentOrChildren, className, attributes) {
1541   let elt = document.createElement(tag);
1542   if (className) {
1543     elt.className = className;
1544   }
1545   if (attributes) {
1546     if (attributes["data-l10n-id"]) {
1547       let args = attributes.hasOwnProperty("data-l10n-args")
1548         ? attributes["data-l10n-args"]
1549         : undefined;
1550       document.l10n.setAttributes(elt, attributes["data-l10n-id"], args);
1551       delete attributes["data-l10n-id"];
1552       if (args) {
1553         delete attributes["data-l10n-args"];
1554       }
1555     }
1557     for (let attrName in attributes) {
1558       elt.setAttribute(attrName, attributes[attrName]);
1559     }
1560   }
1561   if (Array.isArray(textContentOrChildren)) {
1562     this.append(elt, textContentOrChildren);
1563   } else if (!attributes || !attributes["data-l10n-id"]) {
1564     elt.textContent = String(textContentOrChildren);
1565   }
1566   return elt;
1569 $.append = function $_append(parent, children) {
1570   children.forEach(c => parent.appendChild(c));
1573 function assembleFromGraphicsFailure(i, data) {
1574   // Only cover the cases we have today; for example, we do not have
1575   // log failures that assert and we assume the log level is 1/error.
1576   let message = data.failures[i];
1577   let index = data.indices[i];
1578   let what = "";
1579   if (message.search(/\[GFX1-\]: \(LF\)/) == 0) {
1580     // Non-asserting log failure - the message is substring(14)
1581     what = "LogFailure";
1582     message = message.substring(14);
1583   } else if (message.search(/\[GFX1-\]: /) == 0) {
1584     // Non-asserting - the message is substring(9)
1585     what = "Error";
1586     message = message.substring(9);
1587   } else if (message.search(/\[GFX1\]: /) == 0) {
1588     // Asserting - the message is substring(8)
1589     what = "Assert";
1590     message = message.substring(8);
1591   }
1592   let assembled = {
1593     index,
1594     header: "(#" + index + ") " + what,
1595     message,
1596   };
1597   return assembled;
1600 function sortedArrayFromObject(obj) {
1601   let tuples = [];
1602   for (let prop in obj) {
1603     tuples.push([prop, obj[prop]]);
1604   }
1605   tuples.sort(([prop1, v1], [prop2, v2]) => prop1.localeCompare(prop2));
1606   return tuples;
1609 function copyRawDataToClipboard(button) {
1610   if (button) {
1611     button.disabled = true;
1612   }
1613   Troubleshoot.snapshot().then(
1614     async snapshot => {
1615       if (button) {
1616         button.disabled = false;
1617       }
1618       let str = Cc["@mozilla.org/supports-string;1"].createInstance(
1619         Ci.nsISupportsString
1620       );
1621       str.data = JSON.stringify(snapshot, undefined, 2);
1622       let transferable = Cc[
1623         "@mozilla.org/widget/transferable;1"
1624       ].createInstance(Ci.nsITransferable);
1625       transferable.init(getLoadContext());
1626       transferable.addDataFlavor("text/plain");
1627       transferable.setTransferData("text/plain", str);
1628       Services.clipboard.setData(
1629         transferable,
1630         null,
1631         Ci.nsIClipboard.kGlobalClipboard
1632       );
1633     },
1634     err => {
1635       if (button) {
1636         button.disabled = false;
1637       }
1638       console.error(err);
1639     }
1640   );
1643 function getLoadContext() {
1644   return window.docShell.QueryInterface(Ci.nsILoadContext);
1647 async function copyContentsToClipboard() {
1648   // Get the HTML and text representations for the important part of the page.
1649   let contentsDiv = $("contents").cloneNode(true);
1650   // Remove the items we don't want to copy from the clone:
1651   contentsDiv.querySelectorAll(".no-copy, [hidden]").forEach(n => n.remove());
1652   let dataHtml = contentsDiv.innerHTML;
1653   let dataText = createTextForElement(contentsDiv);
1655   // We can't use plain strings, we have to use nsSupportsString.
1656   let supportsStringClass = Cc["@mozilla.org/supports-string;1"];
1657   let ssHtml = supportsStringClass.createInstance(Ci.nsISupportsString);
1658   let ssText = supportsStringClass.createInstance(Ci.nsISupportsString);
1660   let transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(
1661     Ci.nsITransferable
1662   );
1663   transferable.init(getLoadContext());
1665   // Add the HTML flavor.
1666   transferable.addDataFlavor("text/html");
1667   ssHtml.data = dataHtml;
1668   transferable.setTransferData("text/html", ssHtml);
1670   // Add the plain text flavor.
1671   transferable.addDataFlavor("text/plain");
1672   ssText.data = dataText;
1673   transferable.setTransferData("text/plain", ssText);
1675   // Store the data into the clipboard.
1676   Services.clipboard.setData(
1677     transferable,
1678     null,
1679     Services.clipboard.kGlobalClipboard
1680   );
1683 // Return the plain text representation of an element.  Do a little bit
1684 // of pretty-printing to make it human-readable.
1685 function createTextForElement(elem) {
1686   let serializer = new Serializer();
1687   let text = serializer.serialize(elem);
1689   // Actual CR/LF pairs are needed for some Windows text editors.
1690   if (AppConstants.platform == "win") {
1691     text = text.replace(/\n/g, "\r\n");
1692   }
1694   return text;
1697 function Serializer() {}
1699 Serializer.prototype = {
1700   serialize(rootElem) {
1701     this._lines = [];
1702     this._startNewLine();
1703     this._serializeElement(rootElem);
1704     this._startNewLine();
1705     return this._lines.join("\n").trim() + "\n";
1706   },
1708   // The current line is always the line that writing will start at next.  When
1709   // an element is serialized, the current line is updated to be the line at
1710   // which the next element should be written.
1711   get _currentLine() {
1712     return this._lines.length ? this._lines[this._lines.length - 1] : null;
1713   },
1715   set _currentLine(val) {
1716     this._lines[this._lines.length - 1] = val;
1717   },
1719   _serializeElement(elem) {
1720     // table
1721     if (elem.localName == "table") {
1722       this._serializeTable(elem);
1723       return;
1724     }
1726     // all other elements
1728     let hasText = false;
1729     for (let child of elem.childNodes) {
1730       if (child.nodeType == Node.TEXT_NODE) {
1731         let text = this._nodeText(child);
1732         this._appendText(text);
1733         hasText = hasText || !!text.trim();
1734       } else if (child.nodeType == Node.ELEMENT_NODE) {
1735         this._serializeElement(child);
1736       }
1737     }
1739     // For headings, draw a "line" underneath them so they stand out.
1740     let isHeader = /^h[0-9]+$/.test(elem.localName);
1741     if (isHeader) {
1742       let headerText = (this._currentLine || "").trim();
1743       if (headerText) {
1744         this._startNewLine();
1745         this._appendText("-".repeat(headerText.length));
1746       }
1747     }
1749     // Add a blank line underneath elements but only if they contain text.
1750     if (hasText && (isHeader || "p" == elem.localName)) {
1751       this._startNewLine();
1752       this._startNewLine();
1753     }
1754   },
1756   _startNewLine(lines) {
1757     let currLine = this._currentLine;
1758     if (currLine) {
1759       // The current line is not empty.  Trim it.
1760       this._currentLine = currLine.trim();
1761       if (!this._currentLine) {
1762         // The current line became empty.  Discard it.
1763         this._lines.pop();
1764       }
1765     }
1766     this._lines.push("");
1767   },
1769   _appendText(text, lines) {
1770     this._currentLine += text;
1771   },
1773   _isHiddenSubHeading(th) {
1774     return th.parentNode.parentNode.style.display == "none";
1775   },
1777   _serializeTable(table) {
1778     // Collect the table's column headings if in fact there are any.  First
1779     // check thead.  If there's no thead, check the first tr.
1780     let colHeadings = {};
1781     let tableHeadingElem = table.querySelector("thead");
1782     if (!tableHeadingElem) {
1783       tableHeadingElem = table.querySelector("tr");
1784     }
1785     if (tableHeadingElem) {
1786       let tableHeadingCols = tableHeadingElem.querySelectorAll("th,td");
1787       // If there's a contiguous run of th's in the children starting from the
1788       // rightmost child, then consider them to be column headings.
1789       for (let i = tableHeadingCols.length - 1; i >= 0; i--) {
1790         let col = tableHeadingCols[i];
1791         if (col.localName != "th" || col.classList.contains("title-column")) {
1792           break;
1793         }
1794         colHeadings[i] = this._nodeText(col).trim();
1795       }
1796     }
1797     let hasColHeadings = !!Object.keys(colHeadings).length;
1798     if (!hasColHeadings) {
1799       tableHeadingElem = null;
1800     }
1802     let trs = table.querySelectorAll("table > tr, tbody > tr");
1803     let startRow =
1804       tableHeadingElem && tableHeadingElem.localName == "tr" ? 1 : 0;
1806     if (startRow >= trs.length) {
1807       // The table's empty.
1808       return;
1809     }
1811     if (hasColHeadings) {
1812       // Use column headings.  Print each tr as a multi-line chunk like:
1813       //   Heading 1: Column 1 value
1814       //   Heading 2: Column 2 value
1815       for (let i = startRow; i < trs.length; i++) {
1816         let children = trs[i].querySelectorAll("td");
1817         for (let j = 0; j < children.length; j++) {
1818           let text = "";
1819           if (colHeadings[j]) {
1820             text += colHeadings[j] + ": ";
1821           }
1822           text += this._nodeText(children[j]).trim();
1823           this._appendText(text);
1824           this._startNewLine();
1825         }
1826         this._startNewLine();
1827       }
1828       return;
1829     }
1831     // Don't use column headings.  Assume the table has only two columns and
1832     // print each tr in a single line like:
1833     //   Column 1 value: Column 2 value
1834     for (let i = startRow; i < trs.length; i++) {
1835       let children = trs[i].querySelectorAll("th,td");
1836       let rowHeading = this._nodeText(children[0]).trim();
1837       if (children[0].classList.contains("title-column")) {
1838         if (!this._isHiddenSubHeading(children[0])) {
1839           this._appendText(rowHeading);
1840         }
1841       } else if (children.length == 1) {
1842         // This is a single-cell row.
1843         this._appendText(rowHeading);
1844       } else {
1845         let childTables = trs[i].querySelectorAll("table");
1846         if (childTables.length) {
1847           // If we have child tables, don't use nodeText - its trs are already
1848           // queued up from querySelectorAll earlier.
1849           this._appendText(rowHeading + ": ");
1850         } else {
1851           this._appendText(rowHeading + ": ");
1852           for (let k = 1; k < children.length; k++) {
1853             let l = this._nodeText(children[k]).trim();
1854             if (l == "") {
1855               continue;
1856             }
1857             if (k < children.length - 1) {
1858               l += ", ";
1859             }
1860             this._appendText(l);
1861           }
1862         }
1863       }
1864       this._startNewLine();
1865     }
1866     this._startNewLine();
1867   },
1869   _nodeText(node) {
1870     return node.textContent.replace(/\s+/g, " ");
1871   },
1874 function openProfileDirectory() {
1875   // Get the profile directory.
1876   let currProfD = Services.dirsvc.get("ProfD", Ci.nsIFile);
1877   let profileDir = currProfD.path;
1879   // Show the profile directory.
1880   let nsLocalFile = Components.Constructor(
1881     "@mozilla.org/file/local;1",
1882     "nsIFile",
1883     "initWithPath"
1884   );
1885   new nsLocalFile(profileDir).reveal();
1889  * Profile reset is only supported for the default profile if the appropriate migrator exists.
1890  */
1891 function populateActionBox() {
1892   if (ResetProfile.resetSupported()) {
1893     $("reset-box").style.display = "block";
1894   }
1895   if (!Services.appinfo.inSafeMode && AppConstants.platform !== "android") {
1896     $("safe-mode-box").style.display = "block";
1898     if (Services.policies && !Services.policies.isAllowed("safeMode")) {
1899       $("restart-in-safe-mode-button").setAttribute("disabled", "true");
1900     }
1901   }
1904 // Prompt user to restart the browser in safe mode
1905 function safeModeRestart() {
1906   let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(
1907     Ci.nsISupportsPRBool
1908   );
1909   Services.obs.notifyObservers(
1910     cancelQuit,
1911     "quit-application-requested",
1912     "restart"
1913   );
1915   if (!cancelQuit.data) {
1916     Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit);
1917   }
1920  * Set up event listeners for buttons.
1921  */
1922 function setupEventListeners() {
1923   let button = $("reset-box-button");
1924   if (button) {
1925     button.addEventListener("click", function (event) {
1926       ResetProfile.openConfirmationDialog(window);
1927     });
1928   }
1929   button = $("clear-startup-cache-button");
1930   if (button) {
1931     button.addEventListener("click", async function (event) {
1932       const [promptTitle, promptBody, restartButtonLabel] =
1933         await document.l10n.formatValues([
1934           { id: "startup-cache-dialog-title2" },
1935           { id: "startup-cache-dialog-body2" },
1936           { id: "restart-button-label" },
1937         ]);
1938       const buttonFlags =
1939         Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
1940         Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL +
1941         Services.prompt.BUTTON_POS_0_DEFAULT;
1942       const result = Services.prompt.confirmEx(
1943         window.docShell.chromeEventHandler.ownerGlobal,
1944         promptTitle,
1945         promptBody,
1946         buttonFlags,
1947         restartButtonLabel,
1948         null,
1949         null,
1950         null,
1951         {}
1952       );
1953       if (result !== 0) {
1954         return;
1955       }
1956       Services.appinfo.invalidateCachesOnRestart();
1957       Services.startup.quit(
1958         Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit
1959       );
1960     });
1961   }
1962   button = $("restart-in-safe-mode-button");
1963   if (button) {
1964     button.addEventListener("click", function (event) {
1965       if (
1966         Services.obs
1967           .enumerateObservers("restart-in-safe-mode")
1968           .hasMoreElements()
1969       ) {
1970         Services.obs.notifyObservers(
1971           window.docShell.chromeEventHandler.ownerGlobal,
1972           "restart-in-safe-mode"
1973         );
1974       } else {
1975         safeModeRestart();
1976       }
1977     });
1978   }
1979   if (AppConstants.MOZ_UPDATER) {
1980     button = $("update-dir-button");
1981     if (button) {
1982       button.addEventListener("click", function (event) {
1983         // Get the update directory.
1984         let updateDir = Services.dirsvc.get("UpdRootD", Ci.nsIFile);
1985         if (!updateDir.exists()) {
1986           updateDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
1987         }
1988         let updateDirPath = updateDir.path;
1989         // Show the update directory.
1990         let nsLocalFile = Components.Constructor(
1991           "@mozilla.org/file/local;1",
1992           "nsIFile",
1993           "initWithPath"
1994         );
1995         new nsLocalFile(updateDirPath).reveal();
1996       });
1997     }
1998     button = $("show-update-history-button");
1999     if (button) {
2000       button.addEventListener("click", function (event) {
2001         window.browsingContext.topChromeWindow.openDialog(
2002           "chrome://mozapps/content/update/history.xhtml",
2003           "Update:History",
2004           "centerscreen,resizable=no,titlebar,modal"
2005         );
2006       });
2007     }
2008   }
2009   button = $("verify-place-integrity-button");
2010   if (button) {
2011     button.addEventListener("click", function (event) {
2012       PlacesDBUtils.checkAndFixDatabase().then(tasksStatusMap => {
2013         let logs = [];
2014         for (let [key, value] of tasksStatusMap) {
2015           logs.push(`> Task: ${key}`);
2016           let prefix = value.succeeded ? "+ " : "- ";
2017           logs = logs.concat(value.logs.map(m => `${prefix}${m}`));
2018         }
2019         $("verify-place-result").style.display = "block";
2020         $("verify-place-result").classList.remove("no-copy");
2021         $("verify-place-result").textContent = logs.join("\n");
2022       });
2023     });
2024   }
2026   $("copy-raw-data-to-clipboard").addEventListener("click", function (event) {
2027     copyRawDataToClipboard(this);
2028   });
2029   $("copy-to-clipboard").addEventListener("click", function (event) {
2030     copyContentsToClipboard();
2031   });
2032   $("profile-dir-button").addEventListener("click", function (event) {
2033     openProfileDirectory();
2034   });
2038  * Scroll to section specified by location.hash
2039  */
2040 function scrollToSection() {
2041   const id = location.hash.substr(1);
2042   const elem = $(id);
2044   if (elem) {
2045     elem.scrollIntoView();
2046   }