Merge mozilla-central to autoland. a=merge CLOSED TREE
[gecko.git] / browser / components / BrowserGlue.sys.mjs
blob8cd39042437e7c7aac96d72cdf62e8b2c5c38ca1
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 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
6 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
8 const lazy = {};
10 ChromeUtils.defineESModuleGetters(lazy, {
11   AboutNewTab: "resource:///modules/AboutNewTab.sys.mjs",
12   AWToolbarButton: "resource:///modules/aboutwelcome/AWToolbarUtils.sys.mjs",
13   ASRouter: "resource:///modules/asrouter/ASRouter.sys.mjs",
14   ASRouterDefaultConfig:
15     "resource:///modules/asrouter/ASRouterDefaultConfig.sys.mjs",
16   ASRouterNewTabHook: "resource:///modules/asrouter/ASRouterNewTabHook.sys.mjs",
17   ActorManagerParent: "resource://gre/modules/ActorManagerParent.sys.mjs",
18   AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
19   AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.sys.mjs",
20   AsyncShutdown: "resource://gre/modules/AsyncShutdown.sys.mjs",
21   BackupService: "resource:///modules/backup/BackupService.sys.mjs",
22   Blocklist: "resource://gre/modules/Blocklist.sys.mjs",
23   BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.sys.mjs",
24   BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.sys.mjs",
25   BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.sys.mjs",
26   BrowserUIUtils: "resource:///modules/BrowserUIUtils.sys.mjs",
27   BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.sys.mjs",
28   BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
29   BuiltInThemes: "resource:///modules/BuiltInThemes.sys.mjs",
30   ContextualIdentityService:
31     "resource://gre/modules/ContextualIdentityService.sys.mjs",
32   Corroborate: "resource://gre/modules/Corroborate.sys.mjs",
33   DAPTelemetrySender: "resource://gre/modules/DAPTelemetrySender.sys.mjs",
34   DeferredTask: "resource://gre/modules/DeferredTask.sys.mjs",
35   Discovery: "resource:///modules/Discovery.sys.mjs",
36   DoHController: "resource:///modules/DoHController.sys.mjs",
37   DownloadsViewableInternally:
38     "resource:///modules/DownloadsViewableInternally.sys.mjs",
39   E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
40   ExtensionsUI: "resource:///modules/ExtensionsUI.sys.mjs",
41   FeatureGate: "resource://featuregates/FeatureGate.sys.mjs",
42   FirefoxBridgeExtensionUtils:
43     "resource:///modules/FirefoxBridgeExtensionUtils.sys.mjs",
44   FxAccounts: "resource://gre/modules/FxAccounts.sys.mjs",
45   HomePage: "resource:///modules/HomePage.sys.mjs",
46   Integration: "resource://gre/modules/Integration.sys.mjs",
47   Interactions: "resource:///modules/Interactions.sys.mjs",
48   LoginBreaches: "resource:///modules/LoginBreaches.sys.mjs",
49   MigrationUtils: "resource:///modules/MigrationUtils.sys.mjs",
50   NetUtil: "resource://gre/modules/NetUtil.sys.mjs",
51   NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
52   NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
53   Normandy: "resource://normandy/Normandy.sys.mjs",
54   OnboardingMessageProvider:
55     "resource:///modules/asrouter/OnboardingMessageProvider.sys.mjs",
56   OsEnvironment: "resource://gre/modules/OsEnvironment.sys.mjs",
57   PageActions: "resource:///modules/PageActions.sys.mjs",
58   PageDataService: "resource:///modules/pagedata/PageDataService.sys.mjs",
59   PageThumbs: "resource://gre/modules/PageThumbs.sys.mjs",
60   PdfJs: "resource://pdf.js/PdfJs.sys.mjs",
61   PermissionUI: "resource:///modules/PermissionUI.sys.mjs",
62   PlacesBackups: "resource://gre/modules/PlacesBackups.sys.mjs",
63   PlacesDBUtils: "resource://gre/modules/PlacesDBUtils.sys.mjs",
64   PlacesUIUtils: "resource:///modules/PlacesUIUtils.sys.mjs",
65   PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
66   // PluginManager is used by listeners object below.
67   // eslint-disable-next-line mozilla/valid-lazy
68   PluginManager: "resource:///actors/PluginParent.sys.mjs",
69   PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
70   ProcessHangMonitor: "resource:///modules/ProcessHangMonitor.sys.mjs",
71   PublicSuffixList:
72     "resource://gre/modules/netwerk-dns/PublicSuffixList.sys.mjs",
73   QuickSuggest: "resource:///modules/QuickSuggest.sys.mjs",
74   RFPHelper: "resource://gre/modules/RFPHelper.sys.mjs",
75   RemoteSecuritySettings:
76     "resource://gre/modules/psm/RemoteSecuritySettings.sys.mjs",
77   RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
78   ResetPBMPanel: "resource:///modules/ResetPBMPanel.sys.mjs",
79   SafeBrowsing: "resource://gre/modules/SafeBrowsing.sys.mjs",
80   Sanitizer: "resource:///modules/Sanitizer.sys.mjs",
81   SaveToPocket: "chrome://pocket/content/SaveToPocket.sys.mjs",
82   ScreenshotsUtils: "resource:///modules/ScreenshotsUtils.sys.mjs",
83   SearchSERPDomainToCategoriesMap:
84     "resource:///modules/SearchSERPTelemetry.sys.mjs",
85   SearchSERPTelemetry: "resource:///modules/SearchSERPTelemetry.sys.mjs",
86   SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
87   SessionStore: "resource:///modules/sessionstore/SessionStore.sys.mjs",
88   ShellService: "resource:///modules/ShellService.sys.mjs",
89   ShortcutUtils: "resource://gre/modules/ShortcutUtils.sys.mjs",
90   ShoppingUtils: "resource:///modules/ShoppingUtils.sys.mjs",
91   SpecialMessageActions:
92     "resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
93   TRRRacer: "resource:///modules/TRRPerformance.sys.mjs",
94   TabCrashHandler: "resource:///modules/ContentCrashHandlers.sys.mjs",
95   TabUnloader: "resource:///modules/TabUnloader.sys.mjs",
96   TelemetryUtils: "resource://gre/modules/TelemetryUtils.sys.mjs",
97   UIState: "resource://services-sync/UIState.sys.mjs",
98   UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
99   WebChannel: "resource://gre/modules/WebChannel.sys.mjs",
100   WindowsLaunchOnLogin: "resource://gre/modules/WindowsLaunchOnLogin.sys.mjs",
101   WindowsRegistry: "resource://gre/modules/WindowsRegistry.sys.mjs",
102   WindowsGPOParser: "resource://gre/modules/policies/WindowsGPOParser.sys.mjs",
103   clearTimeout: "resource://gre/modules/Timer.sys.mjs",
104   setTimeout: "resource://gre/modules/Timer.sys.mjs",
107 if (AppConstants.MOZ_UPDATER) {
108   ChromeUtils.defineESModuleGetters(lazy, {
109     UpdateListener: "resource://gre/modules/UpdateListener.sys.mjs",
110   });
112 if (AppConstants.MOZ_UPDATE_AGENT) {
113   ChromeUtils.defineESModuleGetters(lazy, {
114     BackgroundUpdate: "resource://gre/modules/BackgroundUpdate.sys.mjs",
115   });
118 // PluginManager is used in the listeners object below.
119 XPCOMUtils.defineLazyServiceGetters(lazy, {
120   BrowserHandler: ["@mozilla.org/browser/clh;1", "nsIBrowserHandler"],
121   PushService: ["@mozilla.org/push/Service;1", "nsIPushService"],
124 ChromeUtils.defineLazyGetter(
125   lazy,
126   "accountsL10n",
127   () =>
128     new Localization(
129       ["browser/accounts.ftl", "toolkit/branding/accounts.ftl"],
130       true
131     )
134 if (AppConstants.ENABLE_WEBDRIVER) {
135   XPCOMUtils.defineLazyServiceGetter(
136     lazy,
137     "Marionette",
138     "@mozilla.org/remote/marionette;1",
139     "nsIMarionette"
140   );
142   XPCOMUtils.defineLazyServiceGetter(
143     lazy,
144     "RemoteAgent",
145     "@mozilla.org/remote/agent;1",
146     "nsIRemoteAgent"
147   );
148 } else {
149   lazy.Marionette = { running: false };
150   lazy.RemoteAgent = { running: false };
153 const PREF_PDFJS_ISDEFAULT_CACHE_STATE = "pdfjs.enabledCache.state";
155 const PRIVATE_BROWSING_BINARY = "private_browsing.exe";
156 // Index of Private Browsing icon in private_browsing.exe
157 // Must line up with IDI_PBICON_PB_PB_EXE in nsNativeAppSupportWin.h.
158 const PRIVATE_BROWSING_EXE_ICON_INDEX = 1;
159 const PREF_PRIVATE_BROWSING_SHORTCUT_CREATED =
160   "browser.privacySegmentation.createdShortcut";
161 // Whether this launch was initiated by the OS.  A launch-on-login will contain
162 // the "os-autostart" flag in the initial launch command line.
163 let gThisInstanceIsLaunchOnLogin = false;
164 // Whether this launch was initiated by a taskbar tab shortcut. A launch from
165 // a taskbar tab shortcut will contain the "taskbar-tab" flag.
166 let gThisInstanceIsTaskbarTab = false;
169  * Fission-compatible JSProcess implementations.
170  * Each actor options object takes the form of a ProcessActorOptions dictionary.
171  * Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
172  * available at https://firefox-source-docs.mozilla.org/dom/ipc/jsactors.html
173  */
174 let JSPROCESSACTORS = {
175   // Miscellaneous stuff that needs to be initialized per process.
176   BrowserProcess: {
177     child: {
178       esModuleURI: "resource:///actors/BrowserProcessChild.sys.mjs",
179       observers: [
180         // WebRTC related notifications. They are here to avoid loading WebRTC
181         // components when not needed.
182         "getUserMedia:request",
183         "recording-device-stopped",
184         "PeerConnection:request",
185         "recording-device-events",
186         "recording-window-ended",
187       ],
188     },
189   },
191   RefreshBlockerObserver: {
192     child: {
193       esModuleURI: "resource:///actors/RefreshBlockerChild.sys.mjs",
194       observers: [
195         "webnavigation-create",
196         "chrome-webnavigation-create",
197         "webnavigation-destroy",
198         "chrome-webnavigation-destroy",
199       ],
200     },
202     enablePreference: "accessibility.blockautorefresh",
203     onPreferenceChanged: (prefName, prevValue, isEnabled) => {
204       lazy.BrowserWindowTracker.orderedWindows.forEach(win => {
205         for (let browser of win.gBrowser.browsers) {
206           try {
207             browser.sendMessageToActor(
208               "PreferenceChanged",
209               { isEnabled },
210               "RefreshBlocker",
211               "all"
212             );
213           } catch (ex) {}
214         }
215       });
216     },
217   },
221  * Fission-compatible JSWindowActor implementations.
222  * Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
223  * available at https://firefox-source-docs.mozilla.org/dom/ipc/jsactors.html
224  */
225 let JSWINDOWACTORS = {
226   AboutLogins: {
227     parent: {
228       esModuleURI: "resource:///actors/AboutLoginsParent.sys.mjs",
229     },
230     child: {
231       esModuleURI: "resource:///actors/AboutLoginsChild.sys.mjs",
232       events: {
233         AboutLoginsCopyLoginDetail: { wantUntrusted: true },
234         AboutLoginsCreateLogin: { wantUntrusted: true },
235         AboutLoginsDeleteLogin: { wantUntrusted: true },
236         AboutLoginsDismissBreachAlert: { wantUntrusted: true },
237         AboutLoginsImportFromBrowser: { wantUntrusted: true },
238         AboutLoginsImportFromFile: { wantUntrusted: true },
239         AboutLoginsImportReportInit: { wantUntrusted: true },
240         AboutLoginsImportReportReady: { wantUntrusted: true },
241         AboutLoginsInit: { wantUntrusted: true },
242         AboutLoginsGetHelp: { wantUntrusted: true },
243         AboutLoginsOpenPreferences: { wantUntrusted: true },
244         AboutLoginsOpenSite: { wantUntrusted: true },
245         AboutLoginsRecordTelemetryEvent: { wantUntrusted: true },
246         AboutLoginsRemoveAllLogins: { wantUntrusted: true },
247         AboutLoginsSortChanged: { wantUntrusted: true },
248         AboutLoginsSyncEnable: { wantUntrusted: true },
249         AboutLoginsSyncOptions: { wantUntrusted: true },
250         AboutLoginsUpdateLogin: { wantUntrusted: true },
251         AboutLoginsExportPasswords: { wantUntrusted: true },
252       },
253     },
254     matches: ["about:logins", "about:logins?*", "about:loginsimportreport"],
255     allFrames: true,
256     remoteTypes: ["privilegedabout"],
257   },
259   AboutMessagePreview: {
260     parent: {
261       esModuleURI: "resource:///actors/AboutMessagePreviewParent.sys.mjs",
262     },
263     child: {
264       esModuleURI: "resource:///actors/AboutMessagePreviewChild.sys.mjs",
265       events: {
266         DOMDocElementInserted: { capture: true },
267       },
268     },
269     matches: ["about:messagepreview", "about:messagepreview?*"],
270   },
272   AboutNewTab: {
273     parent: {
274       esModuleURI: "resource:///actors/AboutNewTabParent.sys.mjs",
275     },
276     child: {
277       esModuleURI: "resource:///actors/AboutNewTabChild.sys.mjs",
278       events: {
279         DOMDocElementInserted: {},
280         DOMContentLoaded: {},
281         load: { capture: true },
282         unload: { capture: true },
283         pageshow: {},
284         visibilitychange: {},
285       },
286     },
287     // The wildcard on about:newtab is for the # parameter
288     // that is used for the newtab devtools. The wildcard for about:home
289     // is similar, and also allows for falling back to loading the
290     // about:home document dynamically if an attempt is made to load
291     // about:home?jscache from the AboutHomeStartupCache as a top-level
292     // load.
293     matches: ["about:home*", "about:welcome", "about:newtab*"],
294     remoteTypes: ["privilegedabout"],
295   },
297   AboutPocket: {
298     parent: {
299       esModuleURI: "resource:///actors/AboutPocketParent.sys.mjs",
300     },
301     child: {
302       esModuleURI: "resource:///actors/AboutPocketChild.sys.mjs",
304       events: {
305         DOMDocElementInserted: { capture: true },
306       },
307     },
309     remoteTypes: ["privilegedabout"],
310     matches: [
311       "about:pocket-saved*",
312       "about:pocket-signup*",
313       "about:pocket-home*",
314       "about:pocket-style-guide*",
315     ],
316   },
318   AboutPrivateBrowsing: {
319     parent: {
320       esModuleURI: "resource:///actors/AboutPrivateBrowsingParent.sys.mjs",
321     },
322     child: {
323       esModuleURI: "resource:///actors/AboutPrivateBrowsingChild.sys.mjs",
325       events: {
326         DOMDocElementInserted: { capture: true },
327       },
328     },
330     matches: ["about:privatebrowsing*"],
331   },
333   AboutProtections: {
334     parent: {
335       esModuleURI: "resource:///actors/AboutProtectionsParent.sys.mjs",
336     },
337     child: {
338       esModuleURI: "resource:///actors/AboutProtectionsChild.sys.mjs",
340       events: {
341         DOMDocElementInserted: { capture: true },
342       },
343     },
345     matches: ["about:protections", "about:protections?*"],
346   },
348   AboutReader: {
349     parent: {
350       esModuleURI: "resource:///actors/AboutReaderParent.sys.mjs",
351     },
352     child: {
353       esModuleURI: "resource:///actors/AboutReaderChild.sys.mjs",
354       events: {
355         DOMContentLoaded: {},
356         pageshow: { mozSystemGroup: true },
357         // Don't try to create the actor if only the pagehide event fires.
358         // This can happen with the initial about:blank documents.
359         pagehide: { mozSystemGroup: true, createActor: false },
360       },
361     },
362     messageManagerGroups: ["browsers"],
363   },
365   AboutTabCrashed: {
366     parent: {
367       esModuleURI: "resource:///actors/AboutTabCrashedParent.sys.mjs",
368     },
369     child: {
370       esModuleURI: "resource:///actors/AboutTabCrashedChild.sys.mjs",
371       events: {
372         DOMDocElementInserted: { capture: true },
373       },
374     },
376     matches: ["about:tabcrashed*"],
377   },
379   AboutWelcomeShopping: {
380     parent: {
381       esModuleURI: "resource:///actors/AboutWelcomeParent.sys.mjs",
382     },
383     child: {
384       esModuleURI: "resource:///actors/AboutWelcomeChild.sys.mjs",
385       events: {
386         Update: {},
387       },
388     },
389     matches: ["about:shoppingsidebar"],
390     remoteTypes: ["privilegedabout"],
391   },
393   AboutWelcome: {
394     parent: {
395       esModuleURI: "resource:///actors/AboutWelcomeParent.sys.mjs",
396     },
397     child: {
398       esModuleURI: "resource:///actors/AboutWelcomeChild.sys.mjs",
399       events: {
400         // This is added so the actor instantiates immediately and makes
401         // methods available to the page js on load.
402         DOMDocElementInserted: {},
403       },
404     },
405     matches: ["about:welcome"],
406     remoteTypes: ["privilegedabout"],
408     // See Bug 1618306
409     // Remove this preference check when we turn on separate about:welcome for all users.
410     enablePreference: "browser.aboutwelcome.enabled",
411   },
413   BlockedSite: {
414     parent: {
415       esModuleURI: "resource:///actors/BlockedSiteParent.sys.mjs",
416     },
417     child: {
418       esModuleURI: "resource:///actors/BlockedSiteChild.sys.mjs",
419       events: {
420         AboutBlockedLoaded: { wantUntrusted: true },
421         click: {},
422       },
423     },
424     matches: ["about:blocked?*"],
425     allFrames: true,
426   },
428   BrowserTab: {
429     child: {
430       esModuleURI: "resource:///actors/BrowserTabChild.sys.mjs",
431     },
433     messageManagerGroups: ["browsers"],
434   },
436   ClickHandler: {
437     parent: {
438       esModuleURI: "resource:///actors/ClickHandlerParent.sys.mjs",
439     },
440     child: {
441       esModuleURI: "resource:///actors/ClickHandlerChild.sys.mjs",
442       events: {
443         chromelinkclick: { capture: true, mozSystemGroup: true },
444       },
445     },
447     allFrames: true,
448   },
450   /* Note: this uses the same JSMs as ClickHandler, but because it
451    * relies on "normal" click events anywhere on the page (not just
452    * links) and is expensive, and only does something for the
453    * small group of people who have the feature enabled, it is its
454    * own actor which is only registered if the pref is enabled.
455    */
456   MiddleMousePasteHandler: {
457     parent: {
458       esModuleURI: "resource:///actors/ClickHandlerParent.sys.mjs",
459     },
460     child: {
461       esModuleURI: "resource:///actors/ClickHandlerChild.sys.mjs",
462       events: {
463         auxclick: { capture: true, mozSystemGroup: true },
464       },
465     },
466     enablePreference: "middlemouse.contentLoadURL",
468     allFrames: true,
469   },
471   ContentSearch: {
472     parent: {
473       esModuleURI: "resource:///actors/ContentSearchParent.sys.mjs",
474     },
475     child: {
476       esModuleURI: "resource:///actors/ContentSearchChild.sys.mjs",
477       events: {
478         ContentSearchClient: { capture: true, wantUntrusted: true },
479       },
480     },
481     matches: [
482       "about:home",
483       "about:welcome",
484       "about:newtab",
485       "about:privatebrowsing",
486       "about:test-about-content-search-ui",
487     ],
488     remoteTypes: ["privilegedabout"],
489   },
491   ContextMenu: {
492     parent: {
493       esModuleURI: "resource:///actors/ContextMenuParent.sys.mjs",
494     },
496     child: {
497       esModuleURI: "resource:///actors/ContextMenuChild.sys.mjs",
498       events: {
499         contextmenu: { mozSystemGroup: true },
500       },
501     },
503     allFrames: true,
504   },
506   DecoderDoctor: {
507     parent: {
508       esModuleURI: "resource:///actors/DecoderDoctorParent.sys.mjs",
509     },
511     child: {
512       esModuleURI: "resource:///actors/DecoderDoctorChild.sys.mjs",
513       observers: ["decoder-doctor-notification"],
514     },
516     messageManagerGroups: ["browsers"],
517     allFrames: true,
518   },
520   DOMFullscreen: {
521     parent: {
522       esModuleURI: "resource:///actors/DOMFullscreenParent.sys.mjs",
523     },
525     child: {
526       esModuleURI: "resource:///actors/DOMFullscreenChild.sys.mjs",
527       events: {
528         "MozDOMFullscreen:Request": {},
529         "MozDOMFullscreen:Entered": {},
530         "MozDOMFullscreen:NewOrigin": {},
531         "MozDOMFullscreen:Exit": {},
532         "MozDOMFullscreen:Exited": {},
533       },
534     },
536     messageManagerGroups: ["browsers"],
537     allFrames: true,
538   },
540   EncryptedMedia: {
541     parent: {
542       esModuleURI: "resource:///actors/EncryptedMediaParent.sys.mjs",
543     },
545     child: {
546       esModuleURI: "resource:///actors/EncryptedMediaChild.sys.mjs",
547       observers: ["mediakeys-request"],
548     },
550     messageManagerGroups: ["browsers"],
551     allFrames: true,
552   },
554   FormValidation: {
555     parent: {
556       esModuleURI: "resource:///actors/FormValidationParent.sys.mjs",
557     },
559     child: {
560       esModuleURI: "resource:///actors/FormValidationChild.sys.mjs",
561       events: {
562         MozInvalidForm: {},
563         // Listening to â€˜pageshow’ event is only relevant if an invalid form
564         // popup was open, so don't create the actor when fired.
565         pageshow: { createActor: false },
566       },
567     },
569     allFrames: true,
570   },
572   LightweightTheme: {
573     child: {
574       esModuleURI: "resource:///actors/LightweightThemeChild.sys.mjs",
575       events: {
576         pageshow: { mozSystemGroup: true },
577         DOMContentLoaded: {},
578       },
579     },
580     includeChrome: true,
581     allFrames: true,
582     matches: [
583       "about:asrouter",
584       "about:home",
585       "about:newtab",
586       "about:welcome",
587       "chrome://browser/content/syncedtabs/sidebar.xhtml",
588       "chrome://browser/content/places/historySidebar.xhtml",
589       "chrome://browser/content/places/bookmarksSidebar.xhtml",
590       "about:firefoxview",
591     ],
592   },
594   LinkHandler: {
595     parent: {
596       esModuleURI: "resource:///actors/LinkHandlerParent.sys.mjs",
597     },
598     child: {
599       esModuleURI: "resource:///actors/LinkHandlerChild.sys.mjs",
600       events: {
601         DOMHeadElementParsed: {},
602         DOMLinkAdded: {},
603         DOMLinkChanged: {},
604         pageshow: {},
605         // The `pagehide` event is only used to clean up state which will not be
606         // present if the actor hasn't been created.
607         pagehide: { createActor: false },
608       },
609     },
611     messageManagerGroups: ["browsers"],
612   },
614   PageInfo: {
615     child: {
616       esModuleURI: "resource:///actors/PageInfoChild.sys.mjs",
617     },
619     allFrames: true,
620   },
622   PageStyle: {
623     parent: {
624       esModuleURI: "resource:///actors/PageStyleParent.sys.mjs",
625     },
626     child: {
627       esModuleURI: "resource:///actors/PageStyleChild.sys.mjs",
628       events: {
629         pageshow: { createActor: false },
630       },
631     },
633     messageManagerGroups: ["browsers"],
634     allFrames: true,
635   },
637   Pdfjs: {
638     parent: {
639       esModuleURI: "resource://pdf.js/PdfjsParent.sys.mjs",
640     },
641     child: {
642       esModuleURI: "resource://pdf.js/PdfjsChild.sys.mjs",
643     },
644     allFrames: true,
645   },
647   // GMP crash reporting
648   Plugin: {
649     parent: {
650       esModuleURI: "resource:///actors/PluginParent.sys.mjs",
651     },
652     child: {
653       esModuleURI: "resource:///actors/PluginChild.sys.mjs",
654       events: {
655         PluginCrashed: { capture: true },
656       },
657     },
659     allFrames: true,
660   },
662   PointerLock: {
663     parent: {
664       esModuleURI: "resource:///actors/PointerLockParent.sys.mjs",
665     },
666     child: {
667       esModuleURI: "resource:///actors/PointerLockChild.sys.mjs",
668       events: {
669         "MozDOMPointerLock:Entered": {},
670         "MozDOMPointerLock:Exited": {},
671       },
672     },
674     messageManagerGroups: ["browsers"],
675     allFrames: true,
676   },
678   Profiles: {
679     parent: {
680       esModuleURI: "resource:///actors/ProfilesParent.sys.mjs",
681     },
682     child: {
683       esModuleURI: "resource:///actors/ProfilesChild.sys.mjs",
684     },
685     matches: ["about:profilemanager"],
686     enablePreference: "browser.profiles.enabled",
687   },
689   Prompt: {
690     parent: {
691       esModuleURI: "resource:///actors/PromptParent.sys.mjs",
692     },
693     includeChrome: true,
694     allFrames: true,
695   },
697   RefreshBlocker: {
698     parent: {
699       esModuleURI: "resource:///actors/RefreshBlockerParent.sys.mjs",
700     },
701     child: {
702       esModuleURI: "resource:///actors/RefreshBlockerChild.sys.mjs",
703     },
705     messageManagerGroups: ["browsers"],
706     enablePreference: "accessibility.blockautorefresh",
707   },
709   ScreenshotsComponent: {
710     parent: {
711       esModuleURI: "resource:///modules/ScreenshotsUtils.sys.mjs",
712     },
713     child: {
714       esModuleURI: "resource:///actors/ScreenshotsComponentChild.sys.mjs",
715       events: {
716         "Screenshots:Close": {},
717         "Screenshots:Copy": {},
718         "Screenshots:Download": {},
719         "Screenshots:HidePanel": {},
720         "Screenshots:OverlaySelection": {},
721         "Screenshots:RecordEvent": {},
722         "Screenshots:ShowPanel": {},
723       },
724     },
725     enablePreference: "screenshots.browser.component.enabled",
726   },
728   ScreenshotsHelper: {
729     parent: {
730       esModuleURI: "resource:///modules/ScreenshotsUtils.sys.mjs",
731     },
732     child: {
733       esModuleURI: "resource:///modules/ScreenshotsHelperChild.sys.mjs",
734     },
735     allFrames: true,
736     enablePreference: "screenshots.browser.component.enabled",
737   },
739   SearchSERPTelemetry: {
740     parent: {
741       esModuleURI: "resource:///actors/SearchSERPTelemetryParent.sys.mjs",
742     },
743     child: {
744       esModuleURI: "resource:///actors/SearchSERPTelemetryChild.sys.mjs",
745       events: {
746         DOMContentLoaded: {},
747         pageshow: { mozSystemGroup: true },
748         // The 'pagehide' event is only used to clean up state, and should not
749         // force actor creation.
750         pagehide: { createActor: false },
751         load: { mozSystemGroup: true, capture: true },
752       },
753     },
754     matches: ["https://*/*"],
755   },
757   ShieldFrame: {
758     parent: {
759       esModuleURI: "resource://normandy-content/ShieldFrameParent.sys.mjs",
760     },
761     child: {
762       esModuleURI: "resource://normandy-content/ShieldFrameChild.sys.mjs",
763       events: {
764         pageshow: {},
765         pagehide: {},
766         ShieldPageEvent: { wantUntrusted: true },
767       },
768     },
769     matches: ["about:studies*"],
770   },
772   ShoppingSidebar: {
773     parent: {
774       esModuleURI: "resource:///actors/ShoppingSidebarParent.sys.mjs",
775     },
776     child: {
777       esModuleURI: "resource:///actors/ShoppingSidebarChild.sys.mjs",
778       events: {
779         ContentReady: { wantUntrusted: true },
780         PolledRequestMade: { wantUntrusted: true },
781         // This is added so the actor instantiates immediately and makes
782         // methods available to the page js on load.
783         DOMDocElementInserted: {},
784         ReportProductAvailable: { wantUntrusted: true },
785         AdClicked: { wantUntrusted: true },
786         AdImpression: { wantUntrusted: true },
787         DisableShopping: { wantUntrusted: true },
788       },
789     },
790     matches: ["about:shoppingsidebar"],
791     remoteTypes: ["privilegedabout"],
792   },
794   SpeechDispatcher: {
795     parent: {
796       esModuleURI: "resource:///actors/SpeechDispatcherParent.sys.mjs",
797     },
799     child: {
800       esModuleURI: "resource:///actors/SpeechDispatcherChild.sys.mjs",
801       observers: ["chrome-synth-voices-error"],
802     },
804     messageManagerGroups: ["browsers"],
805     allFrames: true,
806   },
808   ASRouter: {
809     parent: {
810       esModuleURI: "resource:///actors/ASRouterParent.sys.mjs",
811     },
812     child: {
813       esModuleURI: "resource:///actors/ASRouterChild.sys.mjs",
814       events: {
815         // This is added so the actor instantiates immediately and makes
816         // methods available to the page js on load.
817         DOMDocElementInserted: {},
818       },
819     },
820     matches: [
821       "about:asrouter*",
822       "about:home*",
823       "about:newtab*",
824       "about:welcome*",
825       "about:privatebrowsing*",
826     ],
827     remoteTypes: ["privilegedabout"],
828   },
830   SwitchDocumentDirection: {
831     child: {
832       esModuleURI: "resource:///actors/SwitchDocumentDirectionChild.sys.mjs",
833     },
835     allFrames: true,
836   },
838   UITour: {
839     parent: {
840       esModuleURI: "resource:///modules/UITourParent.sys.mjs",
841     },
842     child: {
843       esModuleURI: "resource:///modules/UITourChild.sys.mjs",
844       events: {
845         mozUITour: { wantUntrusted: true },
846       },
847     },
849     messageManagerGroups: ["browsers"],
850   },
852   WebRTC: {
853     parent: {
854       esModuleURI: "resource:///actors/WebRTCParent.sys.mjs",
855     },
856     child: {
857       esModuleURI: "resource:///actors/WebRTCChild.sys.mjs",
858     },
860     allFrames: true,
861   },
864 ChromeUtils.defineLazyGetter(
865   lazy,
866   "WeaveService",
867   () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
870 if (AppConstants.MOZ_CRASHREPORTER) {
871   ChromeUtils.defineESModuleGetters(lazy, {
872     UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.sys.mjs",
873   });
876 ChromeUtils.defineLazyGetter(lazy, "gBrandBundle", function () {
877   return Services.strings.createBundle(
878     "chrome://branding/locale/brand.properties"
879   );
882 ChromeUtils.defineLazyGetter(lazy, "gBrowserBundle", function () {
883   return Services.strings.createBundle(
884     "chrome://browser/locale/browser.properties"
885   );
888 ChromeUtils.defineLazyGetter(lazy, "log", () => {
889   let { ConsoleAPI } = ChromeUtils.importESModule(
890     "resource://gre/modules/Console.sys.mjs"
891   );
892   let consoleOptions = {
893     // tip: set maxLogLevel to "debug" and use lazy.log.debug() to create
894     // detailed messages during development. See LOG_LEVELS in Console.sys.mjs
895     // for details.
896     maxLogLevel: "error",
897     maxLogLevelPref: "browser.policies.loglevel",
898     prefix: "BrowserGlue.sys.mjs",
899   };
900   return new ConsoleAPI(consoleOptions);
903 const listeners = {
904   observers: {
905     "gmp-plugin-crash": ["PluginManager"],
906     "plugin-crashed": ["PluginManager"],
907   },
909   observe(subject, topic, data) {
910     for (let module of this.observers[topic]) {
911       try {
912         lazy[module].observe(subject, topic, data);
913       } catch (e) {
914         console.error(e);
915       }
916     }
917   },
919   init() {
920     for (let observer of Object.keys(this.observers)) {
921       Services.obs.addObserver(this, observer);
922     }
923   },
925 if (AppConstants.MOZ_UPDATER) {
926   listeners.observers["update-downloading"] = ["UpdateListener"];
927   listeners.observers["update-staged"] = ["UpdateListener"];
928   listeners.observers["update-downloaded"] = ["UpdateListener"];
929   listeners.observers["update-available"] = ["UpdateListener"];
930   listeners.observers["update-error"] = ["UpdateListener"];
931   listeners.observers["update-swap"] = ["UpdateListener"];
934 // Seconds of idle before trying to create a bookmarks backup.
935 const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
936 // Minimum interval between backups.  We try to not create more than one backup
937 // per interval.
938 const BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS = 1;
939 // Seconds of idle time before the late idle tasks will be scheduled.
940 const LATE_TASKS_IDLE_TIME_SEC = 20;
941 // Time after we stop tracking startup crashes.
942 const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
945  * OS X has the concept of zero-window sessions and therefore ignores the
946  * browser-lastwindow-close-* topics.
947  */
948 const OBSERVE_LASTWINDOW_CLOSE_TOPICS = AppConstants.platform != "macosx";
950 export let BrowserInitState = {};
951 BrowserInitState.startupIdleTaskPromise = new Promise(resolve => {
952   BrowserInitState._resolveStartupIdleTask = resolve;
955 export function BrowserGlue() {
956   XPCOMUtils.defineLazyServiceGetter(
957     this,
958     "_userIdleService",
959     "@mozilla.org/widget/useridleservice;1",
960     "nsIUserIdleService"
961   );
963   ChromeUtils.defineLazyGetter(this, "_distributionCustomizer", function () {
964     const { DistributionCustomizer } = ChromeUtils.importESModule(
965       "resource:///modules/distribution.sys.mjs"
966     );
967     return new DistributionCustomizer();
968   });
970   XPCOMUtils.defineLazyServiceGetter(
971     this,
972     "AlertsService",
973     "@mozilla.org/alerts-service;1",
974     "nsIAlertsService"
975   );
977   this._init();
980 function WindowsRegPoliciesGetter(wrk, root, regLocation) {
981   wrk.open(root, regLocation, wrk.ACCESS_READ);
982   let policies;
983   if (wrk.hasChild("Mozilla\\" + Services.appinfo.name)) {
984     policies = lazy.WindowsGPOParser.readPolicies(wrk, policies);
985   }
986   wrk.close();
987   return policies;
990 function isPrivateBrowsingAllowedInRegistry() {
991   // If there is an attempt to open Private Browsing before
992   // EnterprisePolicies are initialized the Windows registry
993   // can be checked to determine if it is enabled
994   if (Services.policies.status > Ci.nsIEnterprisePolicies.UNINITIALIZED) {
995     // Yield to policies engine if initialized
996     let privateAllowed = Services.policies.isAllowed("privatebrowsing");
997     lazy.log.debug(
998       `Yield to initialized policies engine: Private Browsing Allowed = ${privateAllowed}`
999     );
1000     return privateAllowed;
1001   }
1002   if (AppConstants.platform !== "win") {
1003     // Not using Windows so no registry, return true
1004     lazy.log.debug(
1005       "AppConstants.platform is not 'win': Private Browsing allowed"
1006     );
1007     return true;
1008   }
1009   // If all other checks fail only then do we check registry
1010   let wrk = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
1011     Ci.nsIWindowsRegKey
1012   );
1013   let regLocation = "SOFTWARE\\Policies";
1014   let userPolicies, machinePolicies;
1015   // Only check HKEY_LOCAL_MACHINE if not in testing
1016   if (!Cu.isInAutomation) {
1017     machinePolicies = WindowsRegPoliciesGetter(
1018       wrk,
1019       wrk.ROOT_KEY_LOCAL_MACHINE,
1020       regLocation
1021     );
1022   }
1023   // Check machine policies before checking user policies
1024   // HKEY_LOCAL_MACHINE supersedes HKEY_CURRENT_USER so only check
1025   // HKEY_CURRENT_USER if the registry key is not present in
1026   // HKEY_LOCAL_MACHINE at all
1027   if (machinePolicies && "DisablePrivateBrowsing" in machinePolicies) {
1028     lazy.log.debug(
1029       `DisablePrivateBrowsing in HKEY_LOCAL_MACHINE is ${machinePolicies.DisablePrivateBrowsing}`
1030     );
1031     return !(machinePolicies.DisablePrivateBrowsing === 1);
1032   }
1033   userPolicies = WindowsRegPoliciesGetter(
1034     wrk,
1035     wrk.ROOT_KEY_CURRENT_USER,
1036     regLocation
1037   );
1038   if (userPolicies && "DisablePrivateBrowsing" in userPolicies) {
1039     lazy.log.debug(
1040       `DisablePrivateBrowsing in HKEY_CURRENT_USER is ${userPolicies.DisablePrivateBrowsing}`
1041     );
1042     return !(userPolicies.DisablePrivateBrowsing === 1);
1043   }
1044   // Private browsing allowed if no registry entry exists
1045   lazy.log.debug(
1046     "No DisablePrivateBrowsing registry entry: Private Browsing allowed"
1047   );
1048   return true;
1051 BrowserGlue.prototype = {
1052   _saveSession: false,
1053   _migrationImportsDefaultBookmarks: false,
1054   _placesBrowserInitComplete: false,
1055   _isNewProfile: undefined,
1056   _defaultCookieBehaviorAtStartup: null,
1058   _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
1059     if (!this._saveSession && !aForce) {
1060       return;
1061     }
1063     if (!lazy.PrivateBrowsingUtils.permanentPrivateBrowsing) {
1064       Services.prefs.setBoolPref(
1065         "browser.sessionstore.resume_session_once",
1066         true
1067       );
1068     }
1070     // This method can be called via [NSApplication terminate:] on Mac, which
1071     // ends up causing prefs not to be flushed to disk, so we need to do that
1072     // explicitly here. See bug 497652.
1073     Services.prefs.savePrefFile(null);
1074   },
1076   // nsIObserver implementation
1077   observe: async function BG_observe(subject, topic, data) {
1078     switch (topic) {
1079       case "notifications-open-settings":
1080         this._openPreferences("privacy-permissions");
1081         break;
1082       case "final-ui-startup":
1083         this._beforeUIStartup();
1084         break;
1085       case "browser-delayed-startup-finished":
1086         this._onFirstWindowLoaded(subject);
1087         Services.obs.removeObserver(this, "browser-delayed-startup-finished");
1088         break;
1089       case "sessionstore-windows-restored":
1090         this._onWindowsRestored();
1091         break;
1092       case "browser:purge-session-history":
1093         // reset the console service's error buffer
1094         Services.console.logStringMessage(null); // clear the console (in case it's open)
1095         Services.console.reset();
1096         break;
1097       case "restart-in-safe-mode":
1098         this._onSafeModeRestart(subject);
1099         break;
1100       case "quit-application-requested":
1101         this._onQuitRequest(subject, data);
1102         break;
1103       case "quit-application-granted":
1104         this._onQuitApplicationGranted();
1105         break;
1106       case "browser-lastwindow-close-requested":
1107         if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1108           // The application is not actually quitting, but the last full browser
1109           // window is about to be closed.
1110           this._onQuitRequest(subject, "lastwindow");
1111         }
1112         break;
1113       case "browser-lastwindow-close-granted":
1114         if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1115           this._setPrefToSaveSession();
1116         }
1117         break;
1118       case "fxaccounts:onverified":
1119         this._onThisDeviceConnected();
1120         break;
1121       case "fxaccounts:device_connected":
1122         this._onDeviceConnected(data);
1123         break;
1124       case "fxaccounts:verify_login":
1125         this._onVerifyLoginNotification(JSON.parse(data));
1126         break;
1127       case "fxaccounts:device_disconnected":
1128         data = JSON.parse(data);
1129         if (data.isLocalDevice) {
1130           this._onDeviceDisconnected();
1131         }
1132         break;
1133       case "fxaccounts:commands:open-uri":
1134         this._onDisplaySyncURIs(subject);
1135         break;
1136       case "session-save":
1137         this._setPrefToSaveSession(true);
1138         subject.QueryInterface(Ci.nsISupportsPRBool);
1139         subject.data = true;
1140         break;
1141       case "places-init-complete":
1142         Services.obs.removeObserver(this, "places-init-complete");
1143         if (!this._migrationImportsDefaultBookmarks) {
1144           this._initPlaces(false);
1145         }
1146         break;
1147       case "idle":
1148         this._backupBookmarks();
1149         break;
1150       case "distribution-customization-complete":
1151         Services.obs.removeObserver(
1152           this,
1153           "distribution-customization-complete"
1154         );
1155         // Customization has finished, we don't need the customizer anymore.
1156         delete this._distributionCustomizer;
1157         break;
1158       case "browser-glue-test": // used by tests
1159         if (data == "force-ui-migration") {
1160           this._migrateUI();
1161         } else if (data == "force-distribution-customization") {
1162           this._distributionCustomizer.applyCustomizations();
1163           // To apply distribution bookmarks use "places-init-complete".
1164         } else if (data == "test-force-places-init") {
1165           this._placesInitialized = false;
1166           this._initPlaces(false);
1167         } else if (data == "mock-alerts-service") {
1168           Object.defineProperty(this, "AlertsService", {
1169             value: subject.wrappedJSObject,
1170           });
1171         } else if (data == "places-browser-init-complete") {
1172           if (this._placesBrowserInitComplete) {
1173             Services.obs.notifyObservers(null, "places-browser-init-complete");
1174           }
1175         } else if (data == "add-breaches-sync-handler") {
1176           this._addBreachesSyncHandler();
1177         }
1178         break;
1179       case "initial-migration-will-import-default-bookmarks":
1180         this._migrationImportsDefaultBookmarks = true;
1181         break;
1182       case "initial-migration-did-import-default-bookmarks":
1183         this._initPlaces(true);
1184         break;
1185       case "handle-xul-text-link":
1186         let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
1187         if (!linkHandled.data) {
1188           let win = lazy.BrowserWindowTracker.getTopWindow();
1189           if (win) {
1190             data = JSON.parse(data);
1191             let where = win.whereToOpenLink(data);
1192             // Preserve legacy behavior of non-modifier left-clicks
1193             // opening in a new selected tab.
1194             if (where == "current") {
1195               where = "tab";
1196             }
1197             win.openTrustedLinkIn(data.href, where);
1198             linkHandled.data = true;
1199           }
1200         }
1201         break;
1202       case "profile-before-change":
1203         // Any component depending on Places should be finalized in
1204         // _onPlacesShutdown.  Any component that doesn't need to act after
1205         // the UI has gone should be finalized in _onQuitApplicationGranted.
1206         this._dispose();
1207         break;
1208       case "keyword-search":
1209         // This notification is broadcast by the docshell when it "fixes up" a
1210         // URI that it's been asked to load into a keyword search.
1211         let engine = null;
1212         try {
1213           engine = Services.search.getEngineByName(
1214             subject.QueryInterface(Ci.nsISupportsString).data
1215           );
1216         } catch (ex) {
1217           console.error(ex);
1218         }
1219         let win = lazy.BrowserWindowTracker.getTopWindow();
1220         lazy.BrowserSearchTelemetry.recordSearch(
1221           win.gBrowser.selectedBrowser,
1222           engine,
1223           "urlbar"
1224         );
1225         break;
1226       case "xpi-signature-changed":
1227         let disabledAddons = JSON.parse(data).disabled;
1228         let addons = await lazy.AddonManager.getAddonsByIDs(disabledAddons);
1229         if (addons.some(addon => addon)) {
1230           this._notifyUnsignedAddonsDisabled();
1231         }
1232         break;
1233       case "sync-ui-state:update":
1234         this._updateFxaBadges(lazy.BrowserWindowTracker.getTopWindow());
1235         break;
1236       case "handlersvc-store-initialized":
1237         // Initialize PdfJs when running in-process and remote. This only
1238         // happens once since PdfJs registers global hooks. If the PdfJs
1239         // extension is installed the init method below will be overridden
1240         // leaving initialization to the extension.
1241         // parent only: configure default prefs, set up pref observers, register
1242         // pdf content handler, and initializes parent side message manager
1243         // shim for privileged api access.
1244         lazy.PdfJs.init(this._isNewProfile);
1246         // Allow certain viewable internally types to be opened from downloads.
1247         lazy.DownloadsViewableInternally.register();
1249         break;
1250       case "app-startup":
1251         this._earlyBlankFirstPaint(subject);
1252         gThisInstanceIsTaskbarTab = subject.handleFlag("taskbar-tab", false);
1253         gThisInstanceIsLaunchOnLogin = subject.handleFlag(
1254           "os-autostart",
1255           false
1256         );
1257         let launchOnLoginPref = "browser.startup.windowsLaunchOnLogin.enabled";
1258         let profileSvc = Cc[
1259           "@mozilla.org/toolkit/profile-service;1"
1260         ].getService(Ci.nsIToolkitProfileService);
1261         if (
1262           AppConstants.platform == "win" &&
1263           !profileSvc.startWithLastProfile
1264         ) {
1265           // If we don't start with last profile, the user
1266           // likely sees the profile selector on launch.
1267           if (Services.prefs.getBoolPref(launchOnLoginPref)) {
1268             Services.telemetry.setEventRecordingEnabled(
1269               "launch_on_login",
1270               true
1271             );
1272             Services.telemetry.recordEvent(
1273               "launch_on_login",
1274               "last_profile_disable",
1275               "startup"
1276             );
1277           }
1278           Services.prefs.setBoolPref(launchOnLoginPref, false);
1279           // Only remove registry key, not shortcut here as we can assume
1280           // if a user manually created a shortcut they want this behavior.
1281           await lazy.WindowsLaunchOnLogin.removeLaunchOnLoginRegistryKey();
1282         }
1283         break;
1284     }
1285   },
1287   // initialization (called on application startup)
1288   _init: function BG__init() {
1289     let os = Services.obs;
1290     [
1291       "notifications-open-settings",
1292       "final-ui-startup",
1293       "browser-delayed-startup-finished",
1294       "sessionstore-windows-restored",
1295       "browser:purge-session-history",
1296       "quit-application-requested",
1297       "quit-application-granted",
1298       "fxaccounts:onverified",
1299       "fxaccounts:device_connected",
1300       "fxaccounts:verify_login",
1301       "fxaccounts:device_disconnected",
1302       "fxaccounts:commands:open-uri",
1303       "session-save",
1304       "places-init-complete",
1305       "distribution-customization-complete",
1306       "handle-xul-text-link",
1307       "profile-before-change",
1308       "keyword-search",
1309       "restart-in-safe-mode",
1310       "xpi-signature-changed",
1311       "sync-ui-state:update",
1312       "handlersvc-store-initialized",
1313     ].forEach(topic => os.addObserver(this, topic, true));
1314     if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1315       os.addObserver(this, "browser-lastwindow-close-requested", true);
1316       os.addObserver(this, "browser-lastwindow-close-granted", true);
1317     }
1319     lazy.ActorManagerParent.addJSProcessActors(JSPROCESSACTORS);
1320     lazy.ActorManagerParent.addJSWindowActors(JSWINDOWACTORS);
1322     this._firstWindowReady = new Promise(
1323       resolve => (this._firstWindowLoaded = resolve)
1324     );
1325   },
1327   // cleanup (called on application shutdown)
1328   _dispose: function BG__dispose() {
1329     // AboutHomeStartupCache might write to the cache during
1330     // quit-application-granted, so we defer uninitialization
1331     // until here.
1332     AboutHomeStartupCache.uninit();
1334     if (this._bookmarksBackupIdleTime) {
1335       this._userIdleService.removeIdleObserver(
1336         this,
1337         this._bookmarksBackupIdleTime
1338       );
1339       this._bookmarksBackupIdleTime = null;
1340     }
1341     if (this._lateTasksIdleObserver) {
1342       this._userIdleService.removeIdleObserver(
1343         this._lateTasksIdleObserver,
1344         LATE_TASKS_IDLE_TIME_SEC
1345       );
1346       delete this._lateTasksIdleObserver;
1347     }
1348     if (this._gmpInstallManager) {
1349       this._gmpInstallManager.uninit();
1350       delete this._gmpInstallManager;
1351     }
1353     Services.prefs.removeObserver(
1354       "privacy.trackingprotection",
1355       this._matchCBCategory
1356     );
1357     Services.prefs.removeObserver(
1358       "network.cookie.cookieBehavior",
1359       this._matchCBCategory
1360     );
1361     Services.prefs.removeObserver(
1362       "network.cookie.cookieBehavior.pbmode",
1363       this._matchCBCategory
1364     );
1365     Services.prefs.removeObserver(
1366       "network.http.referer.disallowCrossSiteRelaxingDefault",
1367       this._matchCBCategory
1368     );
1369     Services.prefs.removeObserver(
1370       "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
1371       this._matchCBCategory
1372     );
1373     Services.prefs.removeObserver(
1374       "privacy.partition.network_state.ocsp_cache",
1375       this._matchCBCategory
1376     );
1377     Services.prefs.removeObserver(
1378       "privacy.query_stripping.enabled",
1379       this._matchCBCategory
1380     );
1381     Services.prefs.removeObserver(
1382       "privacy.query_stripping.enabled.pbmode",
1383       this._matchCBCategory
1384     );
1385     Services.prefs.removeObserver(
1386       "privacy.fingerprintingProtection",
1387       this._matchCBCategory
1388     );
1389     Services.prefs.removeObserver(
1390       "privacy.fingerprintingProtection.pbmode",
1391       this._matchCBCategory
1392     );
1393     Services.prefs.removeObserver(
1394       ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY,
1395       this._updateCBCategory
1396     );
1397     Services.prefs.removeObserver(
1398       "privacy.trackingprotection",
1399       this._setPrefExpectations
1400     );
1401     Services.prefs.removeObserver(
1402       "browser.contentblocking.features.strict",
1403       this._setPrefExpectationsAndUpdate
1404     );
1405   },
1407   // runs on startup, before the first command line handler is invoked
1408   // (i.e. before the first window is opened)
1409   _beforeUIStartup: function BG__beforeUIStartup() {
1410     lazy.SessionStartup.init();
1412     // check if we're in safe mode
1413     if (Services.appinfo.inSafeMode) {
1414       Services.ww.openWindow(
1415         null,
1416         "chrome://browser/content/safeMode.xhtml",
1417         "_blank",
1418         "chrome,centerscreen,modal,resizable=no",
1419         null
1420       );
1421     }
1423     // apply distribution customizations
1424     this._distributionCustomizer.applyCustomizations();
1426     // handle any UI migration
1427     this._migrateUI();
1429     if (!Services.prefs.prefHasUserValue(PREF_PDFJS_ISDEFAULT_CACHE_STATE)) {
1430       lazy.PdfJs.checkIsDefault(this._isNewProfile);
1431     }
1433     listeners.init();
1435     lazy.SessionStore.init();
1437     lazy.BuiltInThemes.maybeInstallActiveBuiltInTheme();
1439     if (AppConstants.MOZ_NORMANDY) {
1440       lazy.Normandy.init();
1441     }
1443     lazy.SaveToPocket.init();
1445     lazy.ResetPBMPanel.init();
1447     AboutHomeStartupCache.init();
1449     Services.obs.notifyObservers(null, "browser-ui-startup-complete");
1450   },
1452   _checkForOldBuildUpdates() {
1453     // check for update if our build is old
1454     if (
1455       AppConstants.MOZ_UPDATER &&
1456       Services.prefs.getBoolPref("app.update.checkInstallTime")
1457     ) {
1458       let buildID = Services.appinfo.appBuildID;
1459       let today = new Date().getTime();
1460       /* eslint-disable no-multi-spaces */
1461       let buildDate = new Date(
1462         buildID.slice(0, 4), // year
1463         buildID.slice(4, 6) - 1, // months are zero-based.
1464         buildID.slice(6, 8), // day
1465         buildID.slice(8, 10), // hour
1466         buildID.slice(10, 12), // min
1467         buildID.slice(12, 14)
1468       ) // ms
1469         .getTime();
1470       /* eslint-enable no-multi-spaces */
1472       const millisecondsIn24Hours = 86400000;
1473       let acceptableAge =
1474         Services.prefs.getIntPref("app.update.checkInstallTime.days") *
1475         millisecondsIn24Hours;
1477       if (buildDate + acceptableAge < today) {
1478         Cc["@mozilla.org/updates/update-service;1"]
1479           .getService(Ci.nsIApplicationUpdateService)
1480           .checkForBackgroundUpdates();
1481       }
1482     }
1483   },
1485   async _onSafeModeRestart(window) {
1486     // prompt the user to confirm
1487     let productName = lazy.gBrandBundle.GetStringFromName("brandShortName");
1488     let strings = lazy.gBrowserBundle;
1489     let promptTitle = strings.formatStringFromName(
1490       "troubleshootModeRestartPromptTitle",
1491       [productName]
1492     );
1493     let promptMessage = strings.GetStringFromName(
1494       "troubleshootModeRestartPromptMessage"
1495     );
1496     let restartText = strings.GetStringFromName(
1497       "troubleshootModeRestartButton"
1498     );
1499     let buttonFlags =
1500       Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
1501       Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL +
1502       Services.prompt.BUTTON_POS_0_DEFAULT;
1504     let rv = await Services.prompt.asyncConfirmEx(
1505       window.browsingContext,
1506       Ci.nsIPrompt.MODAL_TYPE_INTERNAL_WINDOW,
1507       promptTitle,
1508       promptMessage,
1509       buttonFlags,
1510       restartText,
1511       null,
1512       null,
1513       null,
1514       {}
1515     );
1516     if (rv.get("buttonNumClicked") != 0) {
1517       return;
1518     }
1520     let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(
1521       Ci.nsISupportsPRBool
1522     );
1523     Services.obs.notifyObservers(
1524       cancelQuit,
1525       "quit-application-requested",
1526       "restart"
1527     );
1529     if (!cancelQuit.data) {
1530       Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit);
1531     }
1532   },
1534   /**
1535    * Show a notification bar offering a reset.
1536    *
1537    * @param reason
1538    *        String of either "unused" or "uninstall", specifying the reason
1539    *        why a profile reset is offered.
1540    */
1541   _resetProfileNotification(reason) {
1542     let win = lazy.BrowserWindowTracker.getTopWindow();
1543     if (!win) {
1544       return;
1545     }
1547     const { ResetProfile } = ChromeUtils.importESModule(
1548       "resource://gre/modules/ResetProfile.sys.mjs"
1549     );
1550     if (!ResetProfile.resetSupported()) {
1551       return;
1552     }
1554     let productName = lazy.gBrandBundle.GetStringFromName("brandShortName");
1555     let resetBundle = Services.strings.createBundle(
1556       "chrome://global/locale/resetProfile.properties"
1557     );
1559     let message;
1560     if (reason == "unused") {
1561       message = resetBundle.formatStringFromName("resetUnusedProfile.message", [
1562         productName,
1563       ]);
1564     } else if (reason == "uninstall") {
1565       message = resetBundle.formatStringFromName("resetUninstalled.message", [
1566         productName,
1567       ]);
1568     } else {
1569       throw new Error(
1570         `Unknown reason (${reason}) given to _resetProfileNotification.`
1571       );
1572     }
1573     let buttons = [
1574       {
1575         label: resetBundle.formatStringFromName(
1576           "refreshProfile.resetButton.label",
1577           [productName]
1578         ),
1579         accessKey: resetBundle.GetStringFromName(
1580           "refreshProfile.resetButton.accesskey"
1581         ),
1582         callback() {
1583           ResetProfile.openConfirmationDialog(win);
1584         },
1585       },
1586     ];
1588     win.gNotificationBox.appendNotification(
1589       "reset-profile-notification",
1590       {
1591         label: message,
1592         image: "chrome://global/skin/icons/question-64.png",
1593         priority: win.gNotificationBox.PRIORITY_INFO_LOW,
1594       },
1595       buttons
1596     );
1597   },
1599   _notifyUnsignedAddonsDisabled() {
1600     let win = lazy.BrowserWindowTracker.getTopWindow();
1601     if (!win) {
1602       return;
1603     }
1605     let message = win.gNavigatorBundle.getString(
1606       "unsignedAddonsDisabled.message"
1607     );
1608     let buttons = [
1609       {
1610         label: win.gNavigatorBundle.getString(
1611           "unsignedAddonsDisabled.learnMore.label"
1612         ),
1613         accessKey: win.gNavigatorBundle.getString(
1614           "unsignedAddonsDisabled.learnMore.accesskey"
1615         ),
1616         callback() {
1617           win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true");
1618         },
1619       },
1620     ];
1622     win.gNotificationBox.appendNotification(
1623       "unsigned-addons-disabled",
1624       {
1625         label: message,
1626         priority: win.gNotificationBox.PRIORITY_WARNING_MEDIUM,
1627       },
1628       buttons
1629     );
1630   },
1632   _earlyBlankFirstPaint(cmdLine) {
1633     let startTime = Cu.now();
1634     if (
1635       AppConstants.platform == "macosx" ||
1636       Services.startup.wasSilentlyStarted ||
1637       !Services.prefs.getBoolPref("browser.startup.blankWindow", false)
1638     ) {
1639       return;
1640     }
1642     // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
1643     // using a non-default theme.
1644     if (
1645       !Services.startup.showedPreXULSkeletonUI &&
1646       Services.prefs.getCharPref(
1647         "extensions.activeThemeID",
1648         "default-theme@mozilla.org"
1649       ) != "default-theme@mozilla.org"
1650     ) {
1651       return;
1652     }
1654     let store = Services.xulStore;
1655     let getValue = attr =>
1656       store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
1657     let width = getValue("width");
1658     let height = getValue("height");
1660     // The clean profile case isn't handled yet. Return early for now.
1661     if (!width || !height) {
1662       return;
1663     }
1665     let browserWindowFeatures =
1666       "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
1667       "location,toolbar,personalbar";
1668     // This needs to be set when opening the window to ensure that the AppUserModelID
1669     // is set correctly on Windows. Without it, initial launches with `-private-window`
1670     // will show up under the regular Firefox taskbar icon first, and then switch
1671     // to the Private Browsing icon shortly thereafter.
1672     if (cmdLine.findFlag("private-window", false) != -1) {
1673       if (isPrivateBrowsingAllowedInRegistry()) {
1674         browserWindowFeatures += ",private";
1675       }
1676     }
1677     let win = Services.ww.openWindow(
1678       null,
1679       "about:blank",
1680       null,
1681       browserWindowFeatures,
1682       null
1683     );
1685     // Hide the titlebar if the actual browser window will draw in it.
1686     let hiddenTitlebar = Services.appinfo.drawInTitlebar;
1687     if (hiddenTitlebar) {
1688       win.windowUtils.setChromeMargin(0, 2, 2, 2);
1689     }
1691     let docElt = win.document.documentElement;
1692     docElt.setAttribute("screenX", getValue("screenX"));
1693     docElt.setAttribute("screenY", getValue("screenY"));
1695     // The sizemode="maximized" attribute needs to be set before first paint.
1696     let sizemode = getValue("sizemode");
1697     if (sizemode == "maximized") {
1698       docElt.setAttribute("sizemode", sizemode);
1700       // Set the size to use when the user leaves the maximized mode.
1701       // The persisted size is the outer size, but the height/width
1702       // attributes set the inner size.
1703       let appWin = win.docShell.treeOwner
1704         .QueryInterface(Ci.nsIInterfaceRequestor)
1705         .getInterface(Ci.nsIAppWindow);
1706       height -= appWin.outerToInnerHeightDifferenceInCSSPixels;
1707       width -= appWin.outerToInnerWidthDifferenceInCSSPixels;
1708       docElt.setAttribute("height", height);
1709       docElt.setAttribute("width", width);
1710     } else {
1711       // Setting the size of the window in the features string instead of here
1712       // causes the window to grow by the size of the titlebar.
1713       win.resizeTo(width, height);
1714     }
1716     // Set this before showing the window so that graphics code can use it to
1717     // decide to skip some expensive code paths (eg. starting the GPU process).
1718     docElt.setAttribute("windowtype", "navigator:blank");
1720     // The window becomes visible after OnStopRequest, so make this happen now.
1721     win.stop();
1723     ChromeUtils.addProfilerMarker("earlyBlankFirstPaint", startTime);
1724     win.openTime = Cu.now();
1726     let { TelemetryTimestamps } = ChromeUtils.importESModule(
1727       "resource://gre/modules/TelemetryTimestamps.sys.mjs"
1728     );
1729     TelemetryTimestamps.add("blankWindowShown");
1730   },
1732   _firstWindowTelemetry(aWindow) {
1733     let scaling = aWindow.devicePixelRatio * 100;
1734     try {
1735       Services.telemetry.getHistogramById("DISPLAY_SCALING").add(scaling);
1736     } catch (ex) {}
1737   },
1739   _collectStartupConditionsTelemetry() {
1740     let nowSeconds = Math.round(Date.now() / 1000);
1741     // Don't include cases where we don't have the pref. This rules out the first install
1742     // as well as the first run of a build since this was introduced. These could by some
1743     // definitions be referred to as "cold" startups, but probably not since we likely
1744     // just wrote many of the files we use to disk. This way we should approximate a lower
1745     // bound to the number of cold startups rather than an upper bound.
1746     let lastCheckSeconds = Services.prefs.getIntPref(
1747       "browser.startup.lastColdStartupCheck",
1748       nowSeconds
1749     );
1750     Services.prefs.setIntPref(
1751       "browser.startup.lastColdStartupCheck",
1752       nowSeconds
1753     );
1754     try {
1755       let secondsSinceLastOSRestart =
1756         Services.startup.secondsSinceLastOSRestart;
1757       let isColdStartup =
1758         nowSeconds - secondsSinceLastOSRestart > lastCheckSeconds;
1759       Services.telemetry.scalarSet("startup.is_cold", isColdStartup);
1760       Services.telemetry.scalarSet(
1761         "startup.seconds_since_last_os_restart",
1762         secondsSinceLastOSRestart
1763       );
1764     } catch (ex) {
1765       console.error(ex);
1766     }
1767   },
1769   // the first browser window has finished initializing
1770   _onFirstWindowLoaded: function BG__onFirstWindowLoaded(aWindow) {
1771     lazy.AboutNewTab.init();
1773     lazy.TabCrashHandler.init();
1775     lazy.ProcessHangMonitor.init();
1777     lazy.UrlbarPrefs.updateFirefoxSuggestScenario();
1779     // A channel for "remote troubleshooting" code...
1780     let channel = new lazy.WebChannel(
1781       "remote-troubleshooting",
1782       "remote-troubleshooting"
1783     );
1784     channel.listen((id, data, target) => {
1785       if (data.command == "request") {
1786         let { Troubleshoot } = ChromeUtils.importESModule(
1787           "resource://gre/modules/Troubleshoot.sys.mjs"
1788         );
1789         Troubleshoot.snapshot().then(snapshotData => {
1790           // for privacy we remove crash IDs and all preferences (but bug 1091944
1791           // exists to expose prefs once we are confident of privacy implications)
1792           delete snapshotData.crashes;
1793           delete snapshotData.modifiedPreferences;
1794           delete snapshotData.printingPreferences;
1795           channel.send(snapshotData, target);
1796         });
1797       }
1798     });
1800     // Offer to reset a user's profile if it hasn't been used for 60 days.
1801     const OFFER_PROFILE_RESET_INTERVAL_MS = 60 * 24 * 60 * 60 * 1000;
1802     let lastUse = Services.appinfo.replacedLockTime;
1803     let disableResetPrompt = Services.prefs.getBoolPref(
1804       "browser.disableResetPrompt",
1805       false
1806     );
1808     if (
1809       !disableResetPrompt &&
1810       lastUse &&
1811       Date.now() - lastUse >= OFFER_PROFILE_RESET_INTERVAL_MS
1812     ) {
1813       this._resetProfileNotification("unused");
1814     } else if (AppConstants.platform == "win" && !disableResetPrompt) {
1815       // Check if we were just re-installed and offer Firefox Reset
1816       let updateChannel;
1817       try {
1818         updateChannel = ChromeUtils.importESModule(
1819           "resource://gre/modules/UpdateUtils.sys.mjs"
1820         ).UpdateUtils.UpdateChannel;
1821       } catch (ex) {}
1822       if (updateChannel) {
1823         let uninstalledValue = lazy.WindowsRegistry.readRegKey(
1824           Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
1825           "Software\\Mozilla\\Firefox",
1826           `Uninstalled-${updateChannel}`
1827         );
1828         let removalSuccessful = lazy.WindowsRegistry.removeRegKey(
1829           Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
1830           "Software\\Mozilla\\Firefox",
1831           `Uninstalled-${updateChannel}`
1832         );
1833         if (removalSuccessful && uninstalledValue == "True") {
1834           this._resetProfileNotification("uninstall");
1835         }
1836       }
1837     }
1839     this._checkForOldBuildUpdates();
1841     // Check if Sync is configured
1842     if (Services.prefs.prefHasUserValue("services.sync.username")) {
1843       lazy.WeaveService.init();
1844     }
1846     lazy.PageThumbs.init();
1848     lazy.NewTabUtils.init();
1850     Services.telemetry.setEventRecordingEnabled(
1851       "security.ui.protections",
1852       true
1853     );
1855     Services.telemetry.setEventRecordingEnabled("security.doh.neterror", true);
1857     lazy.PageActions.init();
1859     lazy.DoHController.init();
1861     this._firstWindowTelemetry(aWindow);
1862     this._firstWindowLoaded();
1864     this._collectStartupConditionsTelemetry();
1866     // Set the default favicon size for UI views that use the page-icon protocol.
1867     lazy.PlacesUtils.favicons.setDefaultIconURIPreferredSize(
1868       16 * aWindow.devicePixelRatio
1869     );
1871     this._setPrefExpectationsAndUpdate();
1872     this._matchCBCategory();
1874     // This observes the entire privacy.trackingprotection.* pref tree.
1875     Services.prefs.addObserver(
1876       "privacy.trackingprotection",
1877       this._matchCBCategory
1878     );
1879     Services.prefs.addObserver(
1880       "network.cookie.cookieBehavior",
1881       this._matchCBCategory
1882     );
1883     Services.prefs.addObserver(
1884       "network.cookie.cookieBehavior.pbmode",
1885       this._matchCBCategory
1886     );
1887     Services.prefs.addObserver(
1888       "network.http.referer.disallowCrossSiteRelaxingDefault",
1889       this._matchCBCategory
1890     );
1891     Services.prefs.addObserver(
1892       "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
1893       this._matchCBCategory
1894     );
1895     Services.prefs.addObserver(
1896       "privacy.partition.network_state.ocsp_cache",
1897       this._matchCBCategory
1898     );
1899     Services.prefs.addObserver(
1900       "privacy.query_stripping.enabled",
1901       this._matchCBCategory
1902     );
1903     Services.prefs.addObserver(
1904       "privacy.query_stripping.enabled.pbmode",
1905       this._matchCBCategory
1906     );
1907     Services.prefs.addObserver(
1908       "privacy.fingerprintingProtection",
1909       this._matchCBCategory
1910     );
1911     Services.prefs.addObserver(
1912       "privacy.fingerprintingProtection.pbmode",
1913       this._matchCBCategory
1914     );
1915     Services.prefs.addObserver(
1916       ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY,
1917       this._updateCBCategory
1918     );
1919     Services.prefs.addObserver(
1920       "media.autoplay.default",
1921       this._updateAutoplayPref
1922     );
1923     Services.prefs.addObserver(
1924       "privacy.trackingprotection",
1925       this._setPrefExpectations
1926     );
1927     Services.prefs.addObserver(
1928       "browser.contentblocking.features.strict",
1929       this._setPrefExpectationsAndUpdate
1930     );
1931   },
1933   _updateAutoplayPref() {
1934     const blocked = Services.prefs.getIntPref("media.autoplay.default", 1);
1935     const telemetry = Services.telemetry.getHistogramById(
1936       "AUTOPLAY_DEFAULT_SETTING_CHANGE"
1937     );
1938     const labels = { 0: "allow", 1: "blockAudible", 5: "blockAll" };
1939     if (blocked in labels) {
1940       telemetry.add(labels[blocked]);
1941     }
1942   },
1944   _setPrefExpectations() {
1945     ContentBlockingCategoriesPrefs.setPrefExpectations();
1946   },
1948   _setPrefExpectationsAndUpdate() {
1949     ContentBlockingCategoriesPrefs.setPrefExpectations();
1950     ContentBlockingCategoriesPrefs.updateCBCategory();
1951   },
1953   _matchCBCategory() {
1954     ContentBlockingCategoriesPrefs.matchCBCategory();
1955   },
1957   _updateCBCategory() {
1958     ContentBlockingCategoriesPrefs.updateCBCategory();
1959   },
1961   _recordContentBlockingTelemetry() {
1962     Services.telemetry.setEventRecordingEnabled(
1963       "security.ui.protectionspopup",
1964       Services.prefs.getBoolPref(
1965         "security.protectionspopup.recordEventTelemetry"
1966       )
1967     );
1968     Services.telemetry.setEventRecordingEnabled(
1969       "security.ui.app_menu",
1970       Services.prefs.getBoolPref("security.app_menu.recordEventTelemetry")
1971     );
1973     let tpEnabled = Services.prefs.getBoolPref(
1974       "privacy.trackingprotection.enabled"
1975     );
1976     Services.telemetry
1977       .getHistogramById("TRACKING_PROTECTION_ENABLED")
1978       .add(tpEnabled);
1980     let tpPBDisabled = Services.prefs.getBoolPref(
1981       "privacy.trackingprotection.pbmode.enabled"
1982     );
1983     Services.telemetry
1984       .getHistogramById("TRACKING_PROTECTION_PBM_DISABLED")
1985       .add(!tpPBDisabled);
1987     let cookieBehavior = Services.prefs.getIntPref(
1988       "network.cookie.cookieBehavior"
1989     );
1990     Services.telemetry.getHistogramById("COOKIE_BEHAVIOR").add(cookieBehavior);
1992     let fpEnabled = Services.prefs.getBoolPref(
1993       "privacy.trackingprotection.fingerprinting.enabled"
1994     );
1995     let cmEnabled = Services.prefs.getBoolPref(
1996       "privacy.trackingprotection.cryptomining.enabled"
1997     );
1998     let categoryPref;
1999     switch (
2000       Services.prefs.getStringPref("browser.contentblocking.category", null)
2001     ) {
2002       case "standard":
2003         categoryPref = 0;
2004         break;
2005       case "strict":
2006         categoryPref = 1;
2007         break;
2008       case "custom":
2009         categoryPref = 2;
2010         break;
2011       default:
2012         // Any other value is unsupported.
2013         categoryPref = 3;
2014         break;
2015     }
2017     Services.telemetry.scalarSet(
2018       "contentblocking.fingerprinting_blocking_enabled",
2019       fpEnabled
2020     );
2021     Services.telemetry.scalarSet(
2022       "contentblocking.cryptomining_blocking_enabled",
2023       cmEnabled
2024     );
2025     Services.telemetry.scalarSet("contentblocking.category", categoryPref);
2026   },
2028   _recordDataSanitizationPrefs() {
2029     Services.telemetry.scalarSet(
2030       "datasanitization.privacy_sanitize_sanitizeOnShutdown",
2031       Services.prefs.getBoolPref("privacy.sanitize.sanitizeOnShutdown")
2032     );
2033     Services.telemetry.scalarSet(
2034       "datasanitization.privacy_clearOnShutdown_cookies",
2035       Services.prefs.getBoolPref("privacy.clearOnShutdown.cookies")
2036     );
2037     Services.telemetry.scalarSet(
2038       "datasanitization.privacy_clearOnShutdown_history",
2039       Services.prefs.getBoolPref("privacy.clearOnShutdown.history")
2040     );
2041     Services.telemetry.scalarSet(
2042       "datasanitization.privacy_clearOnShutdown_formdata",
2043       Services.prefs.getBoolPref("privacy.clearOnShutdown.formdata")
2044     );
2045     Services.telemetry.scalarSet(
2046       "datasanitization.privacy_clearOnShutdown_downloads",
2047       Services.prefs.getBoolPref("privacy.clearOnShutdown.downloads")
2048     );
2049     Services.telemetry.scalarSet(
2050       "datasanitization.privacy_clearOnShutdown_cache",
2051       Services.prefs.getBoolPref("privacy.clearOnShutdown.cache")
2052     );
2053     Services.telemetry.scalarSet(
2054       "datasanitization.privacy_clearOnShutdown_sessions",
2055       Services.prefs.getBoolPref("privacy.clearOnShutdown.sessions")
2056     );
2057     Services.telemetry.scalarSet(
2058       "datasanitization.privacy_clearOnShutdown_offlineApps",
2059       Services.prefs.getBoolPref("privacy.clearOnShutdown.offlineApps")
2060     );
2061     Services.telemetry.scalarSet(
2062       "datasanitization.privacy_clearOnShutdown_siteSettings",
2063       Services.prefs.getBoolPref("privacy.clearOnShutdown.siteSettings")
2064     );
2065     Services.telemetry.scalarSet(
2066       "datasanitization.privacy_clearOnShutdown_openWindows",
2067       Services.prefs.getBoolPref("privacy.clearOnShutdown.openWindows")
2068     );
2070     let exceptions = 0;
2071     for (let permission of Services.perms.all) {
2072       // We consider just permissions set for http, https and file URLs.
2073       if (
2074         permission.type == "cookie" &&
2075         permission.capability == Ci.nsICookiePermission.ACCESS_SESSION &&
2076         ["http", "https", "file"].some(scheme =>
2077           permission.principal.schemeIs(scheme)
2078         )
2079       ) {
2080         exceptions++;
2081       }
2082     }
2083     Services.telemetry.scalarSet(
2084       "datasanitization.session_permission_exceptions",
2085       exceptions
2086     );
2087   },
2089   /**
2090    * Application shutdown handler.
2091    */
2092   _onQuitApplicationGranted() {
2093     let tasks = [
2094       // This pref must be set here because SessionStore will use its value
2095       // on quit-application.
2096       () => this._setPrefToSaveSession(),
2098       // Call trackStartupCrashEnd here in case the delayed call on startup hasn't
2099       // yet occurred (see trackStartupCrashEnd caller in browser.js).
2100       () => Services.startup.trackStartupCrashEnd(),
2102       () => {
2103         if (this._bookmarksBackupIdleTime) {
2104           this._userIdleService.removeIdleObserver(
2105             this,
2106             this._bookmarksBackupIdleTime
2107           );
2108           this._bookmarksBackupIdleTime = null;
2109         }
2110       },
2112       () => lazy.BrowserUsageTelemetry.uninit(),
2113       () => lazy.SearchSERPTelemetry.uninit(),
2114       () => lazy.SearchSERPDomainToCategoriesMap.uninit(),
2115       () => lazy.Interactions.uninit(),
2116       () => lazy.PageDataService.uninit(),
2117       () => lazy.PageThumbs.uninit(),
2118       () => lazy.NewTabUtils.uninit(),
2119       () => lazy.Normandy.uninit(),
2120       () => lazy.RFPHelper.uninit(),
2121       () => lazy.ShoppingUtils.uninit(),
2122       () => lazy.ASRouterNewTabHook.destroy(),
2123       () => {
2124         if (AppConstants.MOZ_UPDATER) {
2125           lazy.UpdateListener.reset();
2126         }
2127       },
2128       () => {
2129         // bug 1839426 - The FOG service needs to be instantiated reliably so it
2130         // can perform at-shutdown tasks later in shutdown.
2131         Services.fog;
2132       },
2133     ];
2135     for (let task of tasks) {
2136       try {
2137         task();
2138       } catch (ex) {
2139         console.error(`Error during quit-application-granted: ${ex}`);
2140         if (Cu.isInAutomation) {
2141           // This usually happens after the test harness is done collecting
2142           // test errors, thus we can't easily add a failure to it. The only
2143           // noticeable solution we have is crashing.
2144           Cc["@mozilla.org/xpcom/debug;1"]
2145             .getService(Ci.nsIDebug2)
2146             .abort(ex.filename, ex.lineNumber);
2147         }
2148       }
2149     }
2150   },
2152   // Set up a listener to enable/disable the screenshots extension
2153   // based on its preference.
2154   _monitorScreenshotsPref() {
2155     const SCREENSHOTS_PREF = "extensions.screenshots.disabled";
2156     const COMPONENT_PREF = "screenshots.browser.component.enabled";
2157     const ID = "screenshots@mozilla.org";
2158     const _checkScreenshotsPref = async () => {
2159       let screenshotsDisabled = Services.prefs.getBoolPref(
2160         SCREENSHOTS_PREF,
2161         false
2162       );
2163       let componentEnabled = Services.prefs.getBoolPref(COMPONENT_PREF, true);
2165       let screenshotsAddon = await lazy.AddonManager.getAddonByID(ID);
2167       if (screenshotsDisabled) {
2168         if (componentEnabled) {
2169           lazy.ScreenshotsUtils.uninitialize();
2170         } else if (screenshotsAddon?.isActive) {
2171           await screenshotsAddon.disable({ allowSystemAddons: true });
2172         }
2173       } else if (componentEnabled) {
2174         lazy.ScreenshotsUtils.initialize();
2175         if (screenshotsAddon?.isActive) {
2176           await screenshotsAddon.disable({ allowSystemAddons: true });
2177         }
2178       } else {
2179         try {
2180           await screenshotsAddon.enable({ allowSystemAddons: true });
2181         } catch (ex) {
2182           console.error(`Error trying to enable screenshots extension: ${ex}`);
2183         }
2184         lazy.ScreenshotsUtils.uninitialize();
2185       }
2186     };
2187     Services.prefs.addObserver(SCREENSHOTS_PREF, _checkScreenshotsPref);
2188     Services.prefs.addObserver(COMPONENT_PREF, _checkScreenshotsPref);
2189     _checkScreenshotsPref();
2190   },
2192   _monitorWebcompatReporterPref() {
2193     const PREF = "extensions.webcompat-reporter.enabled";
2194     const ID = "webcompat-reporter@mozilla.org";
2195     Services.prefs.addObserver(PREF, async () => {
2196       let addon = await lazy.AddonManager.getAddonByID(ID);
2197       if (!addon) {
2198         return;
2199       }
2200       let enabled = Services.prefs.getBoolPref(PREF, false);
2201       if (enabled && !addon.isActive) {
2202         await addon.enable({ allowSystemAddons: true });
2203       } else if (!enabled && addon.isActive) {
2204         await addon.disable({ allowSystemAddons: true });
2205       }
2206     });
2207   },
2209   async _setupSearchDetection() {
2210     // There is no pref for this add-on because it shouldn't be disabled.
2211     const ID = "addons-search-detection@mozilla.com";
2213     let addon = await lazy.AddonManager.getAddonByID(ID);
2215     // first time install of addon and install on firefox update
2216     addon =
2217       (await lazy.AddonManager.maybeInstallBuiltinAddon(
2218         ID,
2219         "2.0.0",
2220         "resource://builtin-addons/search-detection/"
2221       )) || addon;
2223     if (!addon.isActive) {
2224       addon.enable();
2225     }
2226   },
2228   _monitorHTTPSOnlyPref() {
2229     const PREF_ENABLED = "dom.security.https_only_mode";
2230     const PREF_WAS_ENABLED = "dom.security.https_only_mode_ever_enabled";
2231     const _checkHTTPSOnlyPref = async () => {
2232       const enabled = Services.prefs.getBoolPref(PREF_ENABLED, false);
2233       const was_enabled = Services.prefs.getBoolPref(PREF_WAS_ENABLED, false);
2234       let value = 0;
2235       if (enabled) {
2236         value = 1;
2237         Services.prefs.setBoolPref(PREF_WAS_ENABLED, true);
2238       } else if (was_enabled) {
2239         value = 2;
2240       }
2241       Services.telemetry.scalarSet("security.https_only_mode_enabled", value);
2242     };
2244     Services.prefs.addObserver(PREF_ENABLED, _checkHTTPSOnlyPref);
2245     _checkHTTPSOnlyPref();
2247     const PREF_PBM_WAS_ENABLED =
2248       "dom.security.https_only_mode_ever_enabled_pbm";
2249     const PREF_PBM_ENABLED = "dom.security.https_only_mode_pbm";
2251     const _checkHTTPSOnlyPBMPref = async () => {
2252       const enabledPBM = Services.prefs.getBoolPref(PREF_PBM_ENABLED, false);
2253       const was_enabledPBM = Services.prefs.getBoolPref(
2254         PREF_PBM_WAS_ENABLED,
2255         false
2256       );
2257       let valuePBM = 0;
2258       if (enabledPBM) {
2259         valuePBM = 1;
2260         Services.prefs.setBoolPref(PREF_PBM_WAS_ENABLED, true);
2261       } else if (was_enabledPBM) {
2262         valuePBM = 2;
2263       }
2264       Services.telemetry.scalarSet(
2265         "security.https_only_mode_enabled_pbm",
2266         valuePBM
2267       );
2268     };
2270     Services.prefs.addObserver(PREF_PBM_ENABLED, _checkHTTPSOnlyPBMPref);
2271     _checkHTTPSOnlyPBMPref();
2272   },
2274   _monitorIonPref() {
2275     const PREF_ION_ID = "toolkit.telemetry.pioneerId";
2277     const _checkIonPref = async () => {
2278       for (let win of Services.wm.getEnumerator("navigator:browser")) {
2279         win.document.getElementById("ion-button").hidden =
2280           !Services.prefs.getStringPref(PREF_ION_ID, null);
2281       }
2282     };
2284     const windowListener = {
2285       onOpenWindow(xulWindow) {
2286         const win = xulWindow.docShell.domWindow;
2287         win.addEventListener("load", () => {
2288           const ionButton = win.document.getElementById("ion-button");
2289           if (ionButton) {
2290             ionButton.hidden = !Services.prefs.getStringPref(PREF_ION_ID, null);
2291           }
2292         });
2293       },
2294       onCloseWindow() {},
2295     };
2297     Services.prefs.addObserver(PREF_ION_ID, _checkIonPref);
2298     Services.wm.addListener(windowListener);
2299     _checkIonPref();
2300   },
2302   _monitorIonStudies() {
2303     const STUDY_ADDON_COLLECTION_KEY = "pioneer-study-addons-v1";
2304     const PREF_ION_NEW_STUDIES_AVAILABLE =
2305       "toolkit.telemetry.pioneer-new-studies-available";
2307     const _badgeIcon = async () => {
2308       for (let win of Services.wm.getEnumerator("navigator:browser")) {
2309         win.document
2310           .getElementById("ion-button")
2311           .querySelector(".toolbarbutton-badge")
2312           .classList.add("feature-callout");
2313       }
2314     };
2316     const windowListener = {
2317       onOpenWindow(xulWindow) {
2318         const win = xulWindow.docShell.domWindow;
2319         win.addEventListener("load", () => {
2320           const ionButton = win.document.getElementById("ion-button");
2321           if (ionButton) {
2322             const badge = ionButton.querySelector(".toolbarbutton-badge");
2323             if (
2324               Services.prefs.getBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, false)
2325             ) {
2326               badge.classList.add("feature-callout");
2327             } else {
2328               badge.classList.remove("feature-callout");
2329             }
2330           }
2331         });
2332       },
2333       onCloseWindow() {},
2334     };
2336     // Update all open windows if the pref changes.
2337     Services.prefs.addObserver(PREF_ION_NEW_STUDIES_AVAILABLE, _badgeIcon);
2339     // Badge any currently-open windows.
2340     if (Services.prefs.getBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, false)) {
2341       _badgeIcon();
2342     }
2344     lazy.RemoteSettings(STUDY_ADDON_COLLECTION_KEY).on("sync", async () => {
2345       Services.prefs.setBoolPref(PREF_ION_NEW_STUDIES_AVAILABLE, true);
2346     });
2348     // When a new window opens, check if we need to badge the icon.
2349     Services.wm.addListener(windowListener);
2350   },
2352   _monitorGPCPref() {
2353     const FEATURE_PREF_ENABLED = "privacy.globalprivacycontrol.enabled";
2354     const FUNCTIONALITY_PREF_ENABLED =
2355       "privacy.globalprivacycontrol.functionality.enabled";
2356     const PREF_WAS_ENABLED = "privacy.globalprivacycontrol.was_ever_enabled";
2357     const _checkGPCPref = async () => {
2358       const feature_enabled = Services.prefs.getBoolPref(
2359         FEATURE_PREF_ENABLED,
2360         false
2361       );
2362       const functionality_enabled = Services.prefs.getBoolPref(
2363         FUNCTIONALITY_PREF_ENABLED,
2364         false
2365       );
2366       const was_enabled = Services.prefs.getBoolPref(PREF_WAS_ENABLED, false);
2367       let value = 0;
2368       if (feature_enabled && functionality_enabled) {
2369         value = 1;
2370         Services.prefs.setBoolPref(PREF_WAS_ENABLED, true);
2371       } else if (was_enabled) {
2372         value = 2;
2373       }
2374       Services.telemetry.scalarSet(
2375         "security.global_privacy_control_enabled",
2376         value
2377       );
2378     };
2380     Services.prefs.addObserver(FEATURE_PREF_ENABLED, _checkGPCPref);
2381     Services.prefs.addObserver(FUNCTIONALITY_PREF_ENABLED, _checkGPCPref);
2382     _checkGPCPref();
2383   },
2385   // All initial windows have opened.
2386   _onWindowsRestored: function BG__onWindowsRestored() {
2387     if (this._windowsWereRestored) {
2388       return;
2389     }
2390     this._windowsWereRestored = true;
2392     lazy.BrowserUsageTelemetry.init();
2393     lazy.SearchSERPTelemetry.init();
2395     lazy.Interactions.init();
2396     lazy.PageDataService.init();
2397     lazy.ExtensionsUI.init();
2399     let signingRequired;
2400     if (AppConstants.MOZ_REQUIRE_SIGNING) {
2401       signingRequired = true;
2402     } else {
2403       signingRequired = Services.prefs.getBoolPref(
2404         "xpinstall.signatures.required"
2405       );
2406     }
2408     if (signingRequired) {
2409       let disabledAddons = lazy.AddonManager.getStartupChanges(
2410         lazy.AddonManager.STARTUP_CHANGE_DISABLED
2411       );
2412       lazy.AddonManager.getAddonsByIDs(disabledAddons).then(addons => {
2413         for (let addon of addons) {
2414           if (addon.signedState <= lazy.AddonManager.SIGNEDSTATE_MISSING) {
2415             this._notifyUnsignedAddonsDisabled();
2416             break;
2417           }
2418         }
2419       });
2420     }
2422     if (AppConstants.MOZ_CRASHREPORTER) {
2423       lazy.UnsubmittedCrashHandler.init();
2424       lazy.UnsubmittedCrashHandler.scheduleCheckForUnsubmittedCrashReports();
2425       lazy.FeatureGate.annotateCrashReporter();
2426       lazy.FeatureGate.observePrefChangesForCrashReportAnnotation();
2427     }
2429     if (AppConstants.ASAN_REPORTER) {
2430       var { AsanReporter } = ChromeUtils.importESModule(
2431         "resource://gre/modules/AsanReporter.sys.mjs"
2432       );
2433       AsanReporter.init();
2434     }
2436     lazy.Sanitizer.onStartup();
2437     this._maybeShowRestoreSessionInfoBar();
2438     this._scheduleStartupIdleTasks();
2439     this._lateTasksIdleObserver = (idleService, topic) => {
2440       if (topic == "idle") {
2441         idleService.removeIdleObserver(
2442           this._lateTasksIdleObserver,
2443           LATE_TASKS_IDLE_TIME_SEC
2444         );
2445         delete this._lateTasksIdleObserver;
2446         this._scheduleBestEffortUserIdleTasks();
2447       }
2448     };
2449     this._userIdleService.addIdleObserver(
2450       this._lateTasksIdleObserver,
2451       LATE_TASKS_IDLE_TIME_SEC
2452     );
2454     this._monitorWebcompatReporterPref();
2455     this._monitorHTTPSOnlyPref();
2456     this._monitorIonPref();
2457     this._monitorIonStudies();
2458     this._setupSearchDetection();
2460     this._monitorGPCPref();
2462     // Loading the MigrationUtils module does the work of registering the
2463     // migration wizard JSWindowActor pair. In case nothing else has done
2464     // this yet, load the MigrationUtils so that the wizard is ready to be
2465     // used.
2466     lazy.MigrationUtils;
2467   },
2469   /**
2470    * Use this function as an entry point to schedule tasks that
2471    * need to run only once after startup, and can be scheduled
2472    * by using an idle callback.
2473    *
2474    * The functions scheduled here will fire from idle callbacks
2475    * once every window has finished being restored by session
2476    * restore, and it's guaranteed that they will run before
2477    * the equivalent per-window idle tasks
2478    * (from _schedulePerWindowIdleTasks in browser.js).
2479    *
2480    * If you have something that can wait even further than the
2481    * per-window initialization, and is okay with not being run in some
2482    * sessions, please schedule them using
2483    * _scheduleBestEffortUserIdleTasks.
2484    * Don't be fooled by thinking that the use of the timeout parameter
2485    * will delay your function: it will just ensure that it potentially
2486    * happens _earlier_ than expected (when the timeout limit has been reached),
2487    * but it will not make it happen later (and out of order) compared
2488    * to the other ones scheduled together.
2489    */
2490   _scheduleStartupIdleTasks() {
2491     const idleTasks = [
2492       // It's important that SafeBrowsing is initialized reasonably
2493       // early, so we use a maximum timeout for it.
2494       {
2495         name: "SafeBrowsing.init",
2496         task: () => {
2497           lazy.SafeBrowsing.init();
2498         },
2499         timeout: 5000,
2500       },
2502       {
2503         name: "ContextualIdentityService.load",
2504         task: async () => {
2505           await lazy.ContextualIdentityService.load();
2506           lazy.Discovery.update();
2507         },
2508       },
2510       {
2511         name: "PlacesUIUtils.unblockToolbars",
2512         task: () => {
2513           // We postponed loading bookmarks toolbar content until startup
2514           // has finished, so we can start loading it now:
2515           lazy.PlacesUIUtils.unblockToolbars();
2516         },
2517       },
2519       {
2520         name: "PlacesDBUtils.telemetry",
2521         condition: lazy.TelemetryUtils.isTelemetryEnabled,
2522         task: () => {
2523           lazy.PlacesDBUtils.telemetry().catch(console.error);
2524         },
2525       },
2527       // Begin listening for incoming push messages.
2528       {
2529         name: "PushService.ensureReady",
2530         task: () => {
2531           try {
2532             lazy.PushService.wrappedJSObject.ensureReady();
2533           } catch (ex) {
2534             // NS_ERROR_NOT_AVAILABLE will get thrown for the PushService
2535             // getter if the PushService is disabled.
2536             if (ex.result != Cr.NS_ERROR_NOT_AVAILABLE) {
2537               throw ex;
2538             }
2539           }
2540         },
2541       },
2543       {
2544         name: "BrowserGlue._recordContentBlockingTelemetry",
2545         task: () => {
2546           this._recordContentBlockingTelemetry();
2547         },
2548       },
2550       {
2551         name: "BrowserGlue._recordDataSanitizationPrefs",
2552         task: () => {
2553           this._recordDataSanitizationPrefs();
2554         },
2555       },
2557       {
2558         name: "enableCertErrorUITelemetry",
2559         task: () => {
2560           let enableCertErrorUITelemetry = Services.prefs.getBoolPref(
2561             "security.certerrors.recordEventTelemetry",
2562             true
2563           );
2564           Services.telemetry.setEventRecordingEnabled(
2565             "security.ui.certerror",
2566             enableCertErrorUITelemetry
2567           );
2568           Services.telemetry.setEventRecordingEnabled(
2569             "security.ui.tlserror",
2570             enableCertErrorUITelemetry
2571           );
2572         },
2573       },
2575       // Load the Login Manager data from disk off the main thread, some time
2576       // after startup.  If the data is required before this runs, for example
2577       // because a restored page contains a password field, it will be loaded on
2578       // the main thread, and this initialization request will be ignored.
2579       {
2580         name: "Services.logins",
2581         task: () => {
2582           try {
2583             Services.logins;
2584           } catch (ex) {
2585             console.error(ex);
2586           }
2587         },
2588         timeout: 3000,
2589       },
2591       // Add breach alerts pref observer reasonably early so the pref flip works
2592       {
2593         name: "_addBreachAlertsPrefObserver",
2594         task: () => {
2595           this._addBreachAlertsPrefObserver();
2596         },
2597       },
2599       // Report pinning status and the type of shortcut used to launch
2600       {
2601         name: "pinningStatusTelemetry",
2602         condition: AppConstants.platform == "win",
2603         task: async () => {
2604           let shellService = Cc[
2605             "@mozilla.org/browser/shell-service;1"
2606           ].getService(Ci.nsIWindowsShellService);
2607           let winTaskbar = Cc["@mozilla.org/windows-taskbar;1"].getService(
2608             Ci.nsIWinTaskbar
2609           );
2611           try {
2612             Services.telemetry.scalarSet(
2613               "os.environment.is_taskbar_pinned",
2614               await shellService.isCurrentAppPinnedToTaskbarAsync(
2615                 winTaskbar.defaultGroupId
2616               )
2617             );
2618             Services.telemetry.scalarSet(
2619               "os.environment.is_taskbar_pinned_private",
2620               await shellService.isCurrentAppPinnedToTaskbarAsync(
2621                 winTaskbar.defaultPrivateGroupId
2622               )
2623             );
2624           } catch (ex) {
2625             console.error(ex);
2626           }
2628           let classification;
2629           let shortcut;
2630           try {
2631             shortcut = Services.appinfo.processStartupShortcut;
2632             classification = shellService.classifyShortcut(shortcut);
2633           } catch (ex) {
2634             console.error(ex);
2635           }
2637           if (!classification) {
2638             if (gThisInstanceIsLaunchOnLogin) {
2639               classification = "Autostart";
2640             } else if (shortcut) {
2641               classification = "OtherShortcut";
2642             } else {
2643               classification = "Other";
2644             }
2645           }
2646           // Because of how taskbar tabs work, it may be classifed as a taskbar
2647           // shortcut, in which case we want to overwrite it.
2648           if (gThisInstanceIsTaskbarTab) {
2649             classification = "TaskbarTab";
2650           }
2651           Services.telemetry.scalarSet(
2652             "os.environment.launch_method",
2653             classification
2654           );
2655         },
2656       },
2658       {
2659         name: "firefoxBridgeNativeMessaging",
2660         condition:
2661           (AppConstants.platform == "macosx" ||
2662             AppConstants.platform == "win") &&
2663           Services.prefs.getBoolPref("browser.firefoxbridge.enabled", false),
2664         task: async () => {
2665           await lazy.FirefoxBridgeExtensionUtils.ensureRegistered();
2666         },
2667       },
2669       // Ensure a Private Browsing Shortcut exists. This is needed in case
2670       // a user tries to use Windows functionality to pin our Private Browsing
2671       // mode icon to the Taskbar (eg: the "Pin to Taskbar" context menu item).
2672       // This is also created by the installer, but it's possible that a user
2673       // has removed it, or is running out of a zip build. The consequences of not
2674       // having a Shortcut for this are that regular Firefox will be pinned instead
2675       // of the Private Browsing version -- so it's quite important we do our best
2676       // to make sure one is available.
2677       // See https://bugzilla.mozilla.org/show_bug.cgi?id=1762994 for additional
2678       // background.
2679       {
2680         name: "ensurePrivateBrowsingShortcutExists",
2681         condition:
2682           AppConstants.platform == "win" &&
2683           // Pref'ed off until Private Browsing window separation is enabled by default
2684           // to avoid a situation where a user pins the Private Browsing shortcut to
2685           // the Taskbar, which will end up launching into a different Taskbar icon.
2686           lazy.NimbusFeatures.majorRelease2022.getVariable(
2687             "feltPrivacyWindowSeparation"
2688           ) &&
2689           // We don't want a shortcut if it's been disabled, eg: by enterprise policy.
2690           lazy.PrivateBrowsingUtils.enabled &&
2691           // Private Browsing shortcuts for packaged builds come with the package,
2692           // if they exist at all. We shouldn't try to create our own.
2693           !Services.sysinfo.getProperty("hasWinPackageId") &&
2694           // If we've ever done this successfully before, don't try again. The
2695           // user may have deleted the shortcut, and we don't want to force it
2696           // on them.
2697           !Services.prefs.getBoolPref(
2698             PREF_PRIVATE_BROWSING_SHORTCUT_CREATED,
2699             false
2700           ),
2701         task: async () => {
2702           let shellService = Cc[
2703             "@mozilla.org/browser/shell-service;1"
2704           ].getService(Ci.nsIWindowsShellService);
2705           let winTaskbar = Cc["@mozilla.org/windows-taskbar;1"].getService(
2706             Ci.nsIWinTaskbar
2707           );
2709           if (
2710             !(await shellService.hasMatchingShortcut(
2711               winTaskbar.defaultPrivateGroupId,
2712               true
2713             ))
2714           ) {
2715             let appdir = Services.dirsvc.get("GreD", Ci.nsIFile);
2716             let exe = appdir.clone();
2717             exe.append(PRIVATE_BROWSING_BINARY);
2718             let strings = new Localization(
2719               ["branding/brand.ftl", "browser/browser.ftl"],
2720               true
2721             );
2722             let [desc] = await strings.formatValues([
2723               "private-browsing-shortcut-text-2",
2724             ]);
2725             await shellService.createShortcut(
2726               exe,
2727               [],
2728               desc,
2729               exe,
2730               // The code we're calling indexes from 0 instead of 1
2731               PRIVATE_BROWSING_EXE_ICON_INDEX - 1,
2732               winTaskbar.defaultPrivateGroupId,
2733               "Programs",
2734               desc + ".lnk",
2735               appdir
2736             );
2737           }
2738           // We always set this as long as no exception has been thrown. This
2739           // ensure that it is `true` both if we created one because it didn't
2740           // exist, or if it already existed (most likely because it was created
2741           // by the installer). This avoids the need to call `hasMatchingShortcut`
2742           // again, which necessarily does pointless I/O.
2743           Services.prefs.setBoolPref(
2744             PREF_PRIVATE_BROWSING_SHORTCUT_CREATED,
2745             true
2746           );
2747         },
2748       },
2750       // Report whether Firefox is the default handler for various files types,
2751       // in particular, ".pdf".
2752       {
2753         name: "IsDefaultHandlerForPDF",
2754         condition: AppConstants.platform == "win",
2755         task: () => {
2756           Services.telemetry.keyedScalarSet(
2757             "os.environment.is_default_handler",
2758             ".pdf",
2759             lazy.ShellService.isDefaultHandlerFor(".pdf")
2760           );
2761         },
2762       },
2764       // Install built-in themes. We already installed the active built-in
2765       // theme, if any, before UI startup.
2766       {
2767         name: "BuiltInThemes.ensureBuiltInThemes",
2768         task: async () => {
2769           await lazy.BuiltInThemes.ensureBuiltInThemes();
2770         },
2771       },
2773       {
2774         name: "WinTaskbarJumpList.startup",
2775         condition: AppConstants.platform == "win",
2776         task: () => {
2777           // For Windows 7, initialize the jump list module.
2778           const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
2779           if (
2780             WINTASKBAR_CONTRACTID in Cc &&
2781             Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available
2782           ) {
2783             const { WinTaskbarJumpList } = ChromeUtils.importESModule(
2784               "resource:///modules/WindowsJumpLists.sys.mjs"
2785             );
2786             WinTaskbarJumpList.startup();
2787           }
2788         },
2789       },
2791       // Report macOS Dock status
2792       {
2793         name: "MacDockSupport.isAppInDock",
2794         condition: AppConstants.platform == "macosx",
2795         task: () => {
2796           try {
2797             Services.telemetry.scalarSet(
2798               "os.environment.is_kept_in_dock",
2799               Cc["@mozilla.org/widget/macdocksupport;1"].getService(
2800                 Ci.nsIMacDockSupport
2801               ).isAppInDock
2802             );
2803           } catch (ex) {
2804             console.error(ex);
2805           }
2806         },
2807       },
2809       {
2810         name: "BrowserGlue._maybeShowDefaultBrowserPrompt",
2811         task: () => {
2812           this._maybeShowDefaultBrowserPrompt();
2813         },
2814       },
2816       {
2817         name: "BrowserGlue._monitorScreenshotsPref",
2818         task: () => {
2819           this._monitorScreenshotsPref();
2820         },
2821       },
2823       {
2824         name: "trackStartupCrashEndSetTimeout",
2825         task: () => {
2826           lazy.setTimeout(function () {
2827             Services.tm.idleDispatchToMainThread(
2828               Services.startup.trackStartupCrashEnd
2829             );
2830           }, STARTUP_CRASHES_END_DELAY_MS);
2831         },
2832       },
2834       {
2835         name: "handlerService.asyncInit",
2836         task: () => {
2837           let handlerService = Cc[
2838             "@mozilla.org/uriloader/handler-service;1"
2839           ].getService(Ci.nsIHandlerService);
2840           handlerService.asyncInit();
2841         },
2842       },
2844       {
2845         name: "RFPHelper.init",
2846         task: () => {
2847           lazy.RFPHelper.init();
2848         },
2849       },
2851       {
2852         name: "Blocklist.loadBlocklistAsync",
2853         task: () => {
2854           lazy.Blocklist.loadBlocklistAsync();
2855         },
2856       },
2858       {
2859         name: "TabUnloader.init",
2860         task: () => {
2861           lazy.TabUnloader.init();
2862         },
2863       },
2865       // Run TRR performance measurements for DoH.
2866       {
2867         name: "doh-rollout.trrRacer.run",
2868         task: () => {
2869           let enabledPref = "doh-rollout.trrRace.enabled";
2870           let completePref = "doh-rollout.trrRace.complete";
2872           if (Services.prefs.getBoolPref(enabledPref, false)) {
2873             if (!Services.prefs.getBoolPref(completePref, false)) {
2874               new lazy.TRRRacer().run(() => {
2875                 Services.prefs.setBoolPref(completePref, true);
2876               });
2877             }
2878           } else {
2879             Services.prefs.addObserver(enabledPref, function observer() {
2880               if (Services.prefs.getBoolPref(enabledPref, false)) {
2881                 Services.prefs.removeObserver(enabledPref, observer);
2883                 if (!Services.prefs.getBoolPref(completePref, false)) {
2884                   new lazy.TRRRacer().run(() => {
2885                     Services.prefs.setBoolPref(completePref, true);
2886                   });
2887                 }
2888               }
2889             });
2890           }
2891         },
2892       },
2894       // FOG doesn't need to be initialized _too_ early because it has a
2895       // pre-init buffer.
2896       {
2897         name: "initializeFOG",
2898         task: () => {
2899           Services.fog.initializeFOG();
2901           // Register Glean to listen for experiment updates releated to the
2902           // "gleanInternalSdk" feature defined in the t/c/nimbus/FeatureManifest.yaml
2903           // This feature is intended for internal Glean use only. For features wishing
2904           // to set a remote metric configuration, please use the "glean" feature for
2905           // the purpose of setting the data-control-plane features via Server Knobs.
2906           lazy.NimbusFeatures.gleanInternalSdk.onUpdate(() => {
2907             let cfg = lazy.NimbusFeatures.gleanInternalSdk.getVariable(
2908               "gleanMetricConfiguration"
2909             );
2910             Services.fog.setMetricsFeatureConfig(JSON.stringify(cfg));
2911           });
2913           // Register Glean to listen for experiment updates releated to the
2914           // "glean" feature defined in the t/c/nimbus/FeatureManifest.yaml
2915           lazy.NimbusFeatures.glean.onUpdate(() => {
2916             let cfg = lazy.NimbusFeatures.glean.getVariable(
2917               "gleanMetricConfiguration"
2918             );
2919             Services.fog.setMetricsFeatureConfig(JSON.stringify(cfg));
2920           });
2921         },
2922       },
2924       // Add the import button if this is the first startup.
2925       {
2926         name: "PlacesUIUtils.ImportButton",
2927         task: async () => {
2928           // First check if we've already added the import button, in which
2929           // case we should check for events indicating we can remove it.
2930           if (
2931             Services.prefs.getBoolPref(
2932               "browser.bookmarks.addedImportButton",
2933               false
2934             )
2935           ) {
2936             lazy.PlacesUIUtils.removeImportButtonWhenImportSucceeds();
2937             return;
2938           }
2940           // Otherwise, check if this is a new profile where we need to add it.
2941           // `maybeAddImportButton` will call
2942           // `removeImportButtonWhenImportSucceeds`itself if/when it adds the
2943           // button. Doing things in this order avoids listening for removal
2944           // more than once.
2945           if (
2946             this._isNewProfile &&
2947             // Not in automation: the button changes CUI state, breaking tests
2948             !Cu.isInAutomation
2949           ) {
2950             await lazy.PlacesUIUtils.maybeAddImportButton();
2951           }
2952         },
2953       },
2955       // Add the setup button if this is the first startup
2956       {
2957         name: "AWToolbarButton.SetupButton",
2958         task: async () => {
2959           if (
2960             // Not in automation: the button changes CUI state,
2961             // breaking tests. Check this first, so that the module
2962             // doesn't load if it doesn't have to.
2963             !Cu.isInAutomation &&
2964             lazy.AWToolbarButton.hasToolbarButtonEnabled
2965           ) {
2966             await lazy.AWToolbarButton.maybeAddSetupButton();
2967           }
2968         },
2969       },
2971       {
2972         name: "ASRouterNewTabHook.createInstance",
2973         task: () => {
2974           lazy.ASRouterNewTabHook.createInstance(lazy.ASRouterDefaultConfig());
2975         },
2976       },
2978       {
2979         name: "BackgroundUpdate",
2980         condition: AppConstants.MOZ_UPDATE_AGENT,
2981         task: async () => {
2982           // Never in automation!  This is close to
2983           // `UpdateService.disabledForTesting`, but without creating the
2984           // service, which can perform a good deal of I/O in order to log its
2985           // state.  Since this is in the startup path, we avoid all of that.
2986           let disabledForTesting =
2987             (Cu.isInAutomation ||
2988               lazy.Marionette.running ||
2989               lazy.RemoteAgent.running) &&
2990             Services.prefs.getBoolPref("app.update.disabledForTesting", false);
2991           if (!disabledForTesting) {
2992             try {
2993               await lazy.BackgroundUpdate.scheduleFirefoxMessagingSystemTargetingSnapshotting();
2994             } catch (e) {
2995               console.error(
2996                 "There was an error scheduling Firefox Messaging System targeting snapshotting: ",
2997                 e
2998               );
2999             }
3000             await lazy.BackgroundUpdate.maybeScheduleBackgroundUpdateTask();
3001           }
3002         },
3003       },
3005       // Login detection service is used in fission to identify high value sites.
3006       {
3007         name: "LoginDetection.init",
3008         task: () => {
3009           let loginDetection = Cc[
3010             "@mozilla.org/login-detection-service;1"
3011           ].createInstance(Ci.nsILoginDetectionService);
3012           loginDetection.init();
3013         },
3014       },
3016       {
3017         name: "BrowserGlue._collectTelemetryPiPEnabled",
3018         task: () => {
3019           this._collectTelemetryPiPEnabled();
3020         },
3021       },
3022       // Schedule a sync (if enabled) after we've loaded
3023       {
3024         name: "WeaveService",
3025         task: async () => {
3026           if (lazy.WeaveService.enabled) {
3027             await lazy.WeaveService.whenLoaded();
3028             lazy.WeaveService.Weave.Service.scheduler.autoConnect();
3029           }
3030         },
3031       },
3033       {
3034         name: "unblock-untrusted-modules-thread",
3035         condition: AppConstants.platform == "win",
3036         task: () => {
3037           Services.obs.notifyObservers(
3038             null,
3039             "unblock-untrusted-modules-thread"
3040           );
3041         },
3042       },
3044       {
3045         name: "UpdateListener.maybeShowUnsupportedNotification",
3046         condition: AppConstants.MOZ_UPDATER,
3047         task: () => {
3048           lazy.UpdateListener.maybeShowUnsupportedNotification();
3049         },
3050       },
3052       {
3053         name: "QuickSuggest.init",
3054         task: () => {
3055           lazy.QuickSuggest.init();
3056         },
3057       },
3059       {
3060         name: "DAPTelemetrySender.startup",
3061         condition:
3062           lazy.TelemetryUtils.isTelemetryEnabled &&
3063           lazy.NimbusFeatures.dapTelemetry.getVariable("enabled"),
3064         task: () => {
3065           lazy.DAPTelemetrySender.startup();
3066         },
3067       },
3069       {
3070         name: "ShoppingUtils.init",
3071         task: () => {
3072           lazy.ShoppingUtils.init();
3073         },
3074       },
3076       {
3077         // Starts the JSOracle process for ORB JavaScript validation, if it hasn't started already.
3078         name: "start-orb-javascript-oracle",
3079         task: () => {
3080           ChromeUtils.ensureJSOracleStarted();
3081         },
3082       },
3084       {
3085         name: "SearchSERPDomainToCategoriesMap.init",
3086         task: () => {
3087           lazy.SearchSERPDomainToCategoriesMap.init().catch(console.error);
3088         },
3089       },
3091       {
3092         name: "BackupService initialization",
3093         condition: Services.prefs.getBoolPref("browser.backup.enabled", false),
3094         task: () => {
3095           lazy.BackupService.init();
3096         },
3097       },
3099       {
3100         name: "browser-startup-idle-tasks-finished",
3101         task: () => {
3102           // Use idleDispatch a second time to run this after the per-window
3103           // idle tasks.
3104           ChromeUtils.idleDispatch(() => {
3105             Services.obs.notifyObservers(
3106               null,
3107               "browser-startup-idle-tasks-finished"
3108             );
3109             BrowserInitState._resolveStartupIdleTask();
3110           });
3111         },
3112       },
3113       // Do NOT add anything after idle tasks finished.
3114     ];
3116     for (let task of idleTasks) {
3117       if ("condition" in task && !task.condition) {
3118         continue;
3119       }
3121       ChromeUtils.idleDispatch(
3122         () => {
3123           if (!Services.startup.shuttingDown) {
3124             let startTime = Cu.now();
3125             try {
3126               task.task();
3127             } catch (ex) {
3128               console.error(ex);
3129             } finally {
3130               ChromeUtils.addProfilerMarker(
3131                 "startupIdleTask",
3132                 startTime,
3133                 task.name
3134               );
3135             }
3136           }
3137         },
3138         task.timeout ? { timeout: task.timeout } : undefined
3139       );
3140     }
3141   },
3143   /**
3144    * Use this function as an entry point to schedule tasks that we hope
3145    * to run once per session, at any arbitrary point in time, and which we
3146    * are okay with sometimes not running at all.
3147    *
3148    * This function will be called from an idle observer. Check the value of
3149    * LATE_TASKS_IDLE_TIME_SEC to see the current value for this idle
3150    * observer.
3151    *
3152    * Note: this function may never be called if the user is never idle for the
3153    * requisite time (LATE_TASKS_IDLE_TIME_SEC). Be certain before adding
3154    * something here that it's okay that it never be run.
3155    */
3156   _scheduleBestEffortUserIdleTasks() {
3157     const idleTasks = [
3158       function primaryPasswordTelemetry() {
3159         // Telemetry for primary-password - we do this after a delay as it
3160         // can cause IO if NSS/PSM has not already initialized.
3161         let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"].getService(
3162           Ci.nsIPK11TokenDB
3163         );
3164         let token = tokenDB.getInternalKeyToken();
3165         let mpEnabled = token.hasPassword;
3166         if (mpEnabled) {
3167           Services.telemetry
3168             .getHistogramById("MASTER_PASSWORD_ENABLED")
3169             .add(mpEnabled);
3170         }
3171       },
3173       function GMPInstallManagerSimpleCheckAndInstall() {
3174         let { GMPInstallManager } = ChromeUtils.importESModule(
3175           "resource://gre/modules/GMPInstallManager.sys.mjs"
3176         );
3177         this._gmpInstallManager = new GMPInstallManager();
3178         // We don't really care about the results, if someone is interested they
3179         // can check the log.
3180         this._gmpInstallManager.simpleCheckAndInstall().catch(() => {});
3181       }.bind(this),
3183       function RemoteSettingsInit() {
3184         lazy.RemoteSettings.init();
3185         this._addBreachesSyncHandler();
3186       }.bind(this),
3188       function PublicSuffixListInit() {
3189         lazy.PublicSuffixList.init();
3190       },
3192       function RemoteSecuritySettingsInit() {
3193         lazy.RemoteSecuritySettings.init();
3194       },
3196       function CorroborateInit() {
3197         if (Services.prefs.getBoolPref("corroborator.enabled", false)) {
3198           lazy.Corroborate.init().catch(console.error);
3199         }
3200       },
3202       function BrowserUsageTelemetryReportProfileCount() {
3203         lazy.BrowserUsageTelemetry.reportProfileCount();
3204       },
3206       function reportAllowedAppSources() {
3207         lazy.OsEnvironment.reportAllowedAppSources();
3208       },
3210       function searchBackgroundChecks() {
3211         Services.search.runBackgroundChecks();
3212       },
3214       function reportInstallationTelemetry() {
3215         lazy.BrowserUsageTelemetry.reportInstallationTelemetry();
3216       },
3217     ];
3219     for (let task of idleTasks) {
3220       ChromeUtils.idleDispatch(async () => {
3221         if (!Services.startup.shuttingDown) {
3222           let startTime = Cu.now();
3223           try {
3224             await task();
3225           } catch (ex) {
3226             console.error(ex);
3227           } finally {
3228             ChromeUtils.addProfilerMarker(
3229               "startupLateIdleTask",
3230               startTime,
3231               task.name
3232             );
3233           }
3234         }
3235       });
3236     }
3237   },
3239   _addBreachesSyncHandler() {
3240     if (
3241       Services.prefs.getBoolPref(
3242         "signon.management.page.breach-alerts.enabled",
3243         false
3244       )
3245     ) {
3246       lazy
3247         .RemoteSettings(lazy.LoginBreaches.REMOTE_SETTINGS_COLLECTION)
3248         .on("sync", async event => {
3249           await lazy.LoginBreaches.update(event.data.current);
3250         });
3251     }
3252   },
3254   _addBreachAlertsPrefObserver() {
3255     const BREACH_ALERTS_PREF = "signon.management.page.breach-alerts.enabled";
3256     const clearVulnerablePasswordsIfBreachAlertsDisabled = async function () {
3257       if (!Services.prefs.getBoolPref(BREACH_ALERTS_PREF)) {
3258         await lazy.LoginBreaches.clearAllPotentiallyVulnerablePasswords();
3259       }
3260     };
3261     clearVulnerablePasswordsIfBreachAlertsDisabled();
3262     Services.prefs.addObserver(
3263       BREACH_ALERTS_PREF,
3264       clearVulnerablePasswordsIfBreachAlertsDisabled
3265     );
3266   },
3268   _quitSource: "unknown",
3269   _registerQuitSource(source) {
3270     this._quitSource = source;
3271   },
3273   _onQuitRequest: function BG__onQuitRequest(aCancelQuit, aQuitType) {
3274     // If user has already dismissed quit request, then do nothing
3275     if (aCancelQuit instanceof Ci.nsISupportsPRBool && aCancelQuit.data) {
3276       return;
3277     }
3279     // There are several cases where we won't show a dialog here:
3280     // 1. There is only 1 tab open in 1 window
3281     // 2. browser.warnOnQuit == false
3282     // 3. The browser is currently in Private Browsing mode
3283     // 4. The browser will be restarted.
3284     // 5. The user has automatic session restore enabled and
3285     //    browser.sessionstore.warnOnQuit is not set to true.
3286     // 6. The user doesn't have automatic session restore enabled
3287     //    and browser.tabs.warnOnClose is not set to true.
3288     //
3289     // Otherwise, we will show the "closing multiple tabs" dialog.
3290     //
3291     // aQuitType == "lastwindow" is overloaded. "lastwindow" is used to indicate
3292     // "the last window is closing but we're not quitting (a non-browser window is open)"
3293     // and also "we're quitting by closing the last window".
3295     if (aQuitType == "restart" || aQuitType == "os-restart") {
3296       return;
3297     }
3299     // browser.warnOnQuit is a hidden global boolean to override all quit prompts.
3300     if (!Services.prefs.getBoolPref("browser.warnOnQuit")) {
3301       return;
3302     }
3304     let windowcount = 0;
3305     let pagecount = 0;
3306     let pinnedcount = 0;
3307     for (let win of lazy.BrowserWindowTracker.orderedWindows) {
3308       if (win.closed) {
3309         continue;
3310       }
3311       windowcount++;
3312       let tabbrowser = win.gBrowser;
3313       if (tabbrowser) {
3314         pinnedcount += tabbrowser._numPinnedTabs;
3315         pagecount += tabbrowser.visibleTabs.length - tabbrowser._numPinnedTabs;
3316       }
3317     }
3319     // No windows open so no need for a warning.
3320     if (!windowcount) {
3321       return;
3322     }
3324     // browser.warnOnQuitShortcut is checked when quitting using the shortcut key.
3325     // The warning will appear even when only one window/tab is open. For other
3326     // methods of quitting, the warning only appears when there is more than one
3327     // window or tab open.
3328     let shouldWarnForShortcut =
3329       this._quitSource == "shortcut" &&
3330       Services.prefs.getBoolPref("browser.warnOnQuitShortcut");
3331     let shouldWarnForTabs =
3332       pagecount >= 2 && Services.prefs.getBoolPref("browser.tabs.warnOnClose");
3333     if (!shouldWarnForTabs && !shouldWarnForShortcut) {
3334       return;
3335     }
3337     if (!aQuitType) {
3338       aQuitType = "quit";
3339     }
3341     let win = lazy.BrowserWindowTracker.getTopWindow();
3343     // Our prompt for quitting is most important, so replace others.
3344     win.gDialogBox.replaceDialogIfOpen();
3346     let titleId, buttonLabelId;
3347     if (windowcount > 1) {
3348       // More than 1 window. Compose our own message.
3349       titleId = {
3350         id: "tabbrowser-confirm-close-windows-title",
3351         args: { windowCount: windowcount },
3352       };
3353       buttonLabelId = "tabbrowser-confirm-close-windows-button";
3354     } else if (shouldWarnForShortcut) {
3355       titleId = "tabbrowser-confirm-close-tabs-with-key-title";
3356       buttonLabelId = "tabbrowser-confirm-close-tabs-with-key-button";
3357     } else {
3358       titleId = {
3359         id: "tabbrowser-confirm-close-tabs-title",
3360         args: { tabCount: pagecount },
3361       };
3362       buttonLabelId = "tabbrowser-confirm-close-tabs-button";
3363     }
3365     // The checkbox label is different depending on whether the shortcut
3366     // was used to quit or not.
3367     let checkboxLabelId;
3368     if (shouldWarnForShortcut) {
3369       const quitKeyElement = win.document.getElementById("key_quitApplication");
3370       const quitKey = lazy.ShortcutUtils.prettifyShortcut(quitKeyElement);
3371       checkboxLabelId = {
3372         id: "tabbrowser-confirm-close-tabs-with-key-checkbox",
3373         args: { quitKey },
3374       };
3375     } else {
3376       checkboxLabelId = "tabbrowser-confirm-close-tabs-checkbox";
3377     }
3379     const [title, buttonLabel, checkboxLabel] =
3380       win.gBrowser.tabLocalization.formatMessagesSync([
3381         titleId,
3382         buttonLabelId,
3383         checkboxLabelId,
3384       ]);
3386     let warnOnClose = { value: true };
3387     let flags =
3388       Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0 +
3389       Services.prompt.BUTTON_TITLE_CANCEL * Services.prompt.BUTTON_POS_1;
3390     // buttonPressed will be 0 for closing, 1 for cancel (don't close/quit)
3391     let buttonPressed = Services.prompt.confirmEx(
3392       win,
3393       title.value,
3394       null,
3395       flags,
3396       buttonLabel.value,
3397       null,
3398       null,
3399       checkboxLabel.value,
3400       warnOnClose
3401     );
3402     Services.telemetry.setEventRecordingEnabled("close_tab_warning", true);
3403     let warnCheckbox = warnOnClose.value ? "checked" : "unchecked";
3405     let sessionWillBeRestored =
3406       Services.prefs.getIntPref("browser.startup.page") == 3 ||
3407       Services.prefs.getBoolPref("browser.sessionstore.resume_session_once");
3408     Services.telemetry.recordEvent(
3409       "close_tab_warning",
3410       "shown",
3411       "application",
3412       null,
3413       {
3414         source: this._quitSource,
3415         button: buttonPressed == 0 ? "close" : "cancel",
3416         warn_checkbox: warnCheckbox,
3417         closing_wins: "" + windowcount,
3418         closing_tabs: "" + (pagecount + pinnedcount),
3419         will_restore: sessionWillBeRestored ? "yes" : "no",
3420       }
3421     );
3423     // If the user has unticked the box, and has confirmed closing, stop showing
3424     // the warning.
3425     if (buttonPressed == 0 && !warnOnClose.value) {
3426       if (shouldWarnForShortcut) {
3427         Services.prefs.setBoolPref("browser.warnOnQuitShortcut", false);
3428       } else {
3429         Services.prefs.setBoolPref("browser.tabs.warnOnClose", false);
3430       }
3431     }
3433     this._quitSource = "unknown";
3435     aCancelQuit.data = buttonPressed != 0;
3436   },
3438   /**
3439    * Initialize Places
3440    * - imports the bookmarks html file if bookmarks database is empty, try to
3441    *   restore bookmarks from a JSON backup if the backend indicates that the
3442    *   database was corrupt.
3443    *
3444    * These prefs can be set up by the frontend:
3445    *
3446    * WARNING: setting these preferences to true will overwite existing bookmarks
3447    *
3448    * - browser.places.importBookmarksHTML
3449    *   Set to true will import the bookmarks.html file from the profile folder.
3450    * - browser.bookmarks.restore_default_bookmarks
3451    *   Set to true by safe-mode dialog to indicate we must restore default
3452    *   bookmarks.
3453    */
3454   _initPlaces: function BG__initPlaces(aInitialMigrationPerformed) {
3455     if (this._placesInitialized) {
3456       throw new Error("Cannot initialize Places more than once");
3457     }
3458     this._placesInitialized = true;
3460     // We must instantiate the history service since it will tell us if we
3461     // need to import or restore bookmarks due to first-run, corruption or
3462     // forced migration (due to a major schema change).
3463     // If the database is corrupt or has been newly created we should
3464     // import bookmarks.
3465     let dbStatus = lazy.PlacesUtils.history.databaseStatus;
3467     // Show a notification with a "more info" link for a locked places.sqlite.
3468     if (dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_LOCKED) {
3469       // Note: initPlaces should always happen when the first window is ready,
3470       // in any case, better safe than sorry.
3471       this._firstWindowReady.then(() => {
3472         this._showPlacesLockedNotificationBox();
3473         this._placesBrowserInitComplete = true;
3474         Services.obs.notifyObservers(null, "places-browser-init-complete");
3475       });
3476       return;
3477     }
3479     let importBookmarks =
3480       !aInitialMigrationPerformed &&
3481       (dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_CREATE ||
3482         dbStatus == lazy.PlacesUtils.history.DATABASE_STATUS_CORRUPT);
3484     // Check if user or an extension has required to import bookmarks.html
3485     let importBookmarksHTML = false;
3486     try {
3487       importBookmarksHTML = Services.prefs.getBoolPref(
3488         "browser.places.importBookmarksHTML"
3489       );
3490       if (importBookmarksHTML) {
3491         importBookmarks = true;
3492       }
3493     } catch (ex) {}
3495     // Support legacy bookmarks.html format for apps that depend on that format.
3496     let autoExportHTML = Services.prefs.getBoolPref(
3497       "browser.bookmarks.autoExportHTML",
3498       false
3499     ); // Do not export.
3500     if (autoExportHTML) {
3501       // Sqlite.sys.mjs and Places shutdown happen at profile-before-change, thus,
3502       // to be on the safe side, this should run earlier.
3503       lazy.AsyncShutdown.profileChangeTeardown.addBlocker(
3504         "Places: export bookmarks.html",
3505         () =>
3506           lazy.BookmarkHTMLUtils.exportToFile(
3507             lazy.BookmarkHTMLUtils.defaultPath
3508           )
3509       );
3510     }
3512     (async () => {
3513       // Check if Safe Mode or the user has required to restore bookmarks from
3514       // default profile's bookmarks.html
3515       let restoreDefaultBookmarks = false;
3516       try {
3517         restoreDefaultBookmarks = Services.prefs.getBoolPref(
3518           "browser.bookmarks.restore_default_bookmarks"
3519         );
3520         if (restoreDefaultBookmarks) {
3521           // Ensure that we already have a bookmarks backup for today.
3522           await this._backupBookmarks();
3523           importBookmarks = true;
3524         }
3525       } catch (ex) {}
3527       // If the user did not require to restore default bookmarks, or import
3528       // from bookmarks.html, we will try to restore from JSON
3529       if (importBookmarks && !restoreDefaultBookmarks && !importBookmarksHTML) {
3530         // get latest JSON backup
3531         let lastBackupFile = await lazy.PlacesBackups.getMostRecentBackup();
3532         if (lastBackupFile) {
3533           // restore from JSON backup
3534           await lazy.BookmarkJSONUtils.importFromFile(lastBackupFile, {
3535             replace: true,
3536             source: lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP,
3537           });
3538           importBookmarks = false;
3539         } else {
3540           // We have created a new database but we don't have any backup available
3541           importBookmarks = true;
3542           if (await IOUtils.exists(lazy.BookmarkHTMLUtils.defaultPath)) {
3543             // If bookmarks.html is available in current profile import it...
3544             importBookmarksHTML = true;
3545           } else {
3546             // ...otherwise we will restore defaults
3547             restoreDefaultBookmarks = true;
3548           }
3549         }
3550       }
3552       // Import default bookmarks when necessary.
3553       // Otherwise, if any kind of import runs, default bookmarks creation should be
3554       // delayed till the import operations has finished.  Not doing so would
3555       // cause them to be overwritten by the newly imported bookmarks.
3556       if (!importBookmarks) {
3557         // Now apply distribution customized bookmarks.
3558         // This should always run after Places initialization.
3559         try {
3560           await this._distributionCustomizer.applyBookmarks();
3561         } catch (e) {
3562           console.error(e);
3563         }
3564       } else {
3565         // An import operation is about to run.
3566         let bookmarksUrl = null;
3567         if (restoreDefaultBookmarks) {
3568           // User wants to restore the default set of bookmarks shipped with the
3569           // browser, those that new profiles start with.
3570           bookmarksUrl = "chrome://browser/content/default-bookmarks.html";
3571         } else if (await IOUtils.exists(lazy.BookmarkHTMLUtils.defaultPath)) {
3572           bookmarksUrl = PathUtils.toFileURI(
3573             lazy.BookmarkHTMLUtils.defaultPath
3574           );
3575         }
3577         if (bookmarksUrl) {
3578           // Import from bookmarks.html file.
3579           try {
3580             if (
3581               Services.policies.isAllowed("defaultBookmarks") &&
3582               // Default bookmarks are imported after startup, and they may
3583               // influence the outcome of tests, thus it's possible to use
3584               // this test-only pref to skip the import.
3585               !(
3586                 Cu.isInAutomation &&
3587                 Services.prefs.getBoolPref(
3588                   "browser.bookmarks.testing.skipDefaultBookmarksImport",
3589                   false
3590                 )
3591               )
3592             ) {
3593               await lazy.BookmarkHTMLUtils.importFromURL(bookmarksUrl, {
3594                 replace: true,
3595                 source: lazy.PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP,
3596               });
3597             }
3598           } catch (e) {
3599             console.error("Bookmarks.html file could be corrupt. ", e);
3600           }
3601           try {
3602             // Now apply distribution customized bookmarks.
3603             // This should always run after Places initialization.
3604             await this._distributionCustomizer.applyBookmarks();
3605           } catch (e) {
3606             console.error(e);
3607           }
3608         } else {
3609           console.error(new Error("Unable to find bookmarks.html file."));
3610         }
3612         // Reset preferences, so we won't try to import again at next run
3613         if (importBookmarksHTML) {
3614           Services.prefs.setBoolPref(
3615             "browser.places.importBookmarksHTML",
3616             false
3617           );
3618         }
3619         if (restoreDefaultBookmarks) {
3620           Services.prefs.setBoolPref(
3621             "browser.bookmarks.restore_default_bookmarks",
3622             false
3623           );
3624         }
3625       }
3627       // Initialize bookmark archiving on idle.
3628       // If the last backup has been created before the last browser session,
3629       // and is days old, be more aggressive with the idle timer.
3630       let idleTime = BOOKMARKS_BACKUP_IDLE_TIME_SEC;
3631       if (!(await lazy.PlacesBackups.hasRecentBackup())) {
3632         idleTime /= 2;
3633       }
3634       this._userIdleService.addIdleObserver(this, idleTime);
3635       this._bookmarksBackupIdleTime = idleTime;
3637       if (this._isNewProfile) {
3638         // New profiles may have existing bookmarks (imported from another browser or
3639         // copied into the profile) and we want to show the bookmark toolbar for them
3640         // in some cases.
3641         await lazy.PlacesUIUtils.maybeToggleBookmarkToolbarVisibility();
3642       }
3643     })()
3644       .catch(ex => {
3645         console.error(ex);
3646       })
3647       .then(() => {
3648         // NB: deliberately after the catch so that we always do this, even if
3649         // we threw halfway through initializing in the Task above.
3650         this._placesBrowserInitComplete = true;
3651         Services.obs.notifyObservers(null, "places-browser-init-complete");
3652       });
3653   },
3655   /**
3656    * If a backup for today doesn't exist, this creates one.
3657    */
3658   _backupBookmarks: function BG__backupBookmarks() {
3659     return (async function () {
3660       let lastBackupFile = await lazy.PlacesBackups.getMostRecentBackup();
3661       // Should backup bookmarks if there are no backups or the maximum
3662       // interval between backups elapsed.
3663       if (
3664         !lastBackupFile ||
3665         new Date() - lazy.PlacesBackups.getDateForFile(lastBackupFile) >
3666           BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS * 86400000
3667       ) {
3668         let maxBackups = Services.prefs.getIntPref(
3669           "browser.bookmarks.max_backups"
3670         );
3671         await lazy.PlacesBackups.create(maxBackups);
3672       }
3673     })();
3674   },
3676   /**
3677    * Show the notificationBox for a locked places database.
3678    */
3679   _showPlacesLockedNotificationBox:
3680     async function BG__showPlacesLockedNotificationBox() {
3681       var win = lazy.BrowserWindowTracker.getTopWindow();
3682       var buttons = [{ supportPage: "places-locked" }];
3684       var notifyBox = win.gBrowser.getNotificationBox();
3685       var notification = await notifyBox.appendNotification(
3686         "places-locked",
3687         {
3688           label: { "l10n-id": "places-locked-prompt" },
3689           priority: win.gNotificationBox.PRIORITY_CRITICAL_MEDIUM,
3690         },
3691         buttons
3692       );
3693       notification.persistence = -1; // Until user closes it
3694     },
3696   _onThisDeviceConnected() {
3697     const [title, body] = lazy.accountsL10n.formatValuesSync([
3698       "account-connection-title",
3699       "account-connection-connected",
3700     ]);
3702     let clickCallback = (subject, topic) => {
3703       if (topic != "alertclickcallback") {
3704         return;
3705       }
3706       this._openPreferences("sync");
3707     };
3708     this.AlertsService.showAlertNotification(
3709       null,
3710       title,
3711       body,
3712       true,
3713       null,
3714       clickCallback
3715     );
3716   },
3718   _migrateXULStoreForDocument(fromURL, toURL) {
3719     Array.from(Services.xulStore.getIDsEnumerator(fromURL)).forEach(id => {
3720       Array.from(Services.xulStore.getAttributeEnumerator(fromURL, id)).forEach(
3721         attr => {
3722           let value = Services.xulStore.getValue(fromURL, id, attr);
3723           Services.xulStore.setValue(toURL, id, attr, value);
3724         }
3725       );
3726     });
3727   },
3729   _migrateHashedKeysForXULStoreForDocument(docUrl) {
3730     Array.from(Services.xulStore.getIDsEnumerator(docUrl))
3731       .filter(id => id.startsWith("place:"))
3732       .forEach(id => {
3733         Services.xulStore.removeValue(docUrl, id, "open");
3734         let hashedId = lazy.PlacesUIUtils.obfuscateUrlForXulStore(id);
3735         Services.xulStore.setValue(docUrl, hashedId, "open", "true");
3736       });
3737   },
3739   // eslint-disable-next-line complexity
3740   _migrateUI() {
3741     // Use an increasing number to keep track of the current migration state.
3742     // Completely unrelated to the current Firefox release number.
3743     const UI_VERSION = 143;
3744     const BROWSER_DOCURL = AppConstants.BROWSER_CHROME_URL;
3746     if (!Services.prefs.prefHasUserValue("browser.migration.version")) {
3747       // This is a new profile, nothing to migrate.
3748       Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
3749       this._isNewProfile = true;
3751       if (AppConstants.platform == "win") {
3752         // Ensure that the Firefox Bridge protocols are registered for the new profile.
3753         // No-op if they are registered for the user or the local machine already.
3754         lazy.FirefoxBridgeExtensionUtils.maybeRegisterFirefoxBridgeProtocols();
3755       }
3757       return;
3758     }
3760     this._isNewProfile = false;
3761     let currentUIVersion = Services.prefs.getIntPref(
3762       "browser.migration.version"
3763     );
3764     if (currentUIVersion >= UI_VERSION) {
3765       return;
3766     }
3768     let xulStore = Services.xulStore;
3770     if (currentUIVersion < 90) {
3771       this._migrateXULStoreForDocument(
3772         "chrome://browser/content/places/historySidebar.xul",
3773         "chrome://browser/content/places/historySidebar.xhtml"
3774       );
3775       this._migrateXULStoreForDocument(
3776         "chrome://browser/content/places/places.xul",
3777         "chrome://browser/content/places/places.xhtml"
3778       );
3779       this._migrateXULStoreForDocument(
3780         "chrome://browser/content/places/bookmarksSidebar.xul",
3781         "chrome://browser/content/places/bookmarksSidebar.xhtml"
3782       );
3783     }
3785     // Clear socks proxy values if they were shared from http, to prevent
3786     // websocket breakage after bug 1577862 (see bug 969282).
3787     if (
3788       currentUIVersion < 91 &&
3789       Services.prefs.getBoolPref("network.proxy.share_proxy_settings", false) &&
3790       Services.prefs.getIntPref("network.proxy.type", 0) == 1
3791     ) {
3792       let httpProxy = Services.prefs.getCharPref("network.proxy.http", "");
3793       let httpPort = Services.prefs.getIntPref("network.proxy.http_port", 0);
3794       let socksProxy = Services.prefs.getCharPref("network.proxy.socks", "");
3795       let socksPort = Services.prefs.getIntPref("network.proxy.socks_port", 0);
3796       if (httpProxy && httpProxy == socksProxy && httpPort == socksPort) {
3797         Services.prefs.setCharPref(
3798           "network.proxy.socks",
3799           Services.prefs.getCharPref("network.proxy.backup.socks", "")
3800         );
3801         Services.prefs.setIntPref(
3802           "network.proxy.socks_port",
3803           Services.prefs.getIntPref("network.proxy.backup.socks_port", 0)
3804         );
3805       }
3806     }
3808     if (currentUIVersion < 92) {
3809       // privacy.userContext.longPressBehavior pref was renamed and changed to a boolean
3810       let longpress = Services.prefs.getIntPref(
3811         "privacy.userContext.longPressBehavior",
3812         0
3813       );
3814       if (longpress == 1) {
3815         Services.prefs.setBoolPref(
3816           "privacy.userContext.newTabContainerOnLeftClick.enabled",
3817           true
3818         );
3819       }
3820     }
3822     if (currentUIVersion < 93) {
3823       // The Gecko Profiler Addon is now an internal component. Remove the old
3824       // addon, and enable the new UI.
3826       function enableProfilerButton(wasAddonActive) {
3827         // Enable the feature pref. This will add it to the customization palette,
3828         // but not to the the navbar.
3829         Services.prefs.setBoolPref(
3830           "devtools.performance.popup.feature-flag",
3831           true
3832         );
3834         if (wasAddonActive) {
3835           const { ProfilerMenuButton } = ChromeUtils.importESModule(
3836             "resource://devtools/client/performance-new/popup/menu-button.sys.mjs"
3837           );
3838           if (!ProfilerMenuButton.isInNavbar()) {
3839             // The profiler menu button is not enabled. Turn it on now.
3840             const win = lazy.BrowserWindowTracker.getTopWindow();
3841             if (win && win.document) {
3842               ProfilerMenuButton.addToNavbar(win.document);
3843             }
3844           }
3845         }
3846       }
3848       let addonPromise;
3849       try {
3850         addonPromise = lazy.AddonManager.getAddonByID(
3851           "geckoprofiler@mozilla.com"
3852         );
3853       } catch (error) {
3854         console.error(
3855           "Could not access the AddonManager to upgrade the profile. This is most " +
3856             "likely because the upgrader is being run from an xpcshell test where " +
3857             "the AddonManager is not initialized."
3858         );
3859       }
3860       Promise.resolve(addonPromise).then(addon => {
3861         if (!addon) {
3862           // Either the addon wasn't installed, or the call to getAddonByID failed.
3863           return;
3864         }
3865         // Remove the old addon.
3866         const wasAddonActive = addon.isActive;
3867         addon
3868           .uninstall()
3869           .catch(console.error)
3870           .then(() => enableProfilerButton(wasAddonActive))
3871           .catch(console.error);
3872       }, console.error);
3873     }
3875     // Clear unused socks proxy backup values - see bug 1625773.
3876     if (currentUIVersion < 94) {
3877       let backup = Services.prefs.getCharPref("network.proxy.backup.socks", "");
3878       let backupPort = Services.prefs.getIntPref(
3879         "network.proxy.backup.socks_port",
3880         0
3881       );
3882       let socksProxy = Services.prefs.getCharPref("network.proxy.socks", "");
3883       let socksPort = Services.prefs.getIntPref("network.proxy.socks_port", 0);
3884       if (backup == socksProxy) {
3885         Services.prefs.clearUserPref("network.proxy.backup.socks");
3886       }
3887       if (backupPort == socksPort) {
3888         Services.prefs.clearUserPref("network.proxy.backup.socks_port");
3889       }
3890     }
3892     if (currentUIVersion < 95) {
3893       const oldPrefName = "media.autoplay.enabled.user-gestures-needed";
3894       const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
3895       const newPrefValue = oldPrefValue ? 0 : 1;
3896       Services.prefs.setIntPref("media.autoplay.blocking_policy", newPrefValue);
3897       Services.prefs.clearUserPref(oldPrefName);
3898     }
3900     if (currentUIVersion < 96) {
3901       const oldPrefName = "browser.urlbar.openViewOnFocus";
3902       const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
3903       Services.prefs.setBoolPref(
3904         "browser.urlbar.suggest.topsites",
3905         oldPrefValue
3906       );
3907       Services.prefs.clearUserPref(oldPrefName);
3908     }
3910     if (currentUIVersion < 97) {
3911       let userCustomizedWheelMax = Services.prefs.prefHasUserValue(
3912         "general.smoothScroll.mouseWheel.durationMaxMS"
3913       );
3914       let userCustomizedWheelMin = Services.prefs.prefHasUserValue(
3915         "general.smoothScroll.mouseWheel.durationMinMS"
3916       );
3918       if (!userCustomizedWheelMin && !userCustomizedWheelMax) {
3919         // If the user has an existing profile but hasn't customized the wheel
3920         // animation duration, they will now get the new default values. This
3921         // condition used to set a migrationPercent pref to 0, so that users
3922         // upgrading an older profile would gradually have their wheel animation
3923         // speed migrated to the new values. However, that "gradual migration"
3924         // was phased out by FF 86, so we don't need to set that pref anymore.
3925       } else if (userCustomizedWheelMin && !userCustomizedWheelMax) {
3926         // If they customized just one of the two, save the old value for the
3927         // other one as well, because the two values go hand-in-hand and we
3928         // don't want to move just one to a new value and leave the other one
3929         // at a customized value. In both of these cases, we leave the "migration
3930         // complete" percentage at 100, because they have customized this and
3931         // don't need any further migration.
3932         Services.prefs.setIntPref(
3933           "general.smoothScroll.mouseWheel.durationMaxMS",
3934           400
3935         );
3936       } else if (!userCustomizedWheelMin && userCustomizedWheelMax) {
3937         // Same as above case, but for the other pref.
3938         Services.prefs.setIntPref(
3939           "general.smoothScroll.mouseWheel.durationMinMS",
3940           200
3941         );
3942       } else {
3943         // The last remaining case is if they customized both values, in which
3944         // case also don't need to do anything; the user's customized values
3945         // will be retained and respected.
3946       }
3947     }
3949     if (currentUIVersion < 98) {
3950       Services.prefs.clearUserPref("browser.search.cohort");
3951     }
3953     if (currentUIVersion < 99) {
3954       Services.prefs.clearUserPref("security.tls.version.enable-deprecated");
3955     }
3957     if (currentUIVersion < 102) {
3958       // In Firefox 83, we moved to a dynamic button, so it needs to be removed
3959       // from default placement. This is done early enough that it doesn't
3960       // impact adding new managed bookmarks.
3961       const { CustomizableUI } = ChromeUtils.importESModule(
3962         "resource:///modules/CustomizableUI.sys.mjs"
3963       );
3964       CustomizableUI.removeWidgetFromArea("managed-bookmarks");
3965     }
3967     // We have to rerun these because we had to use 102 on beta.
3968     // They were 101 and 102 before.
3969     if (currentUIVersion < 103) {
3970       // Set a pref if the bookmarks toolbar was already visible,
3971       // so we can keep it visible when navigating away from newtab
3972       let bookmarksToolbarWasVisible =
3973         Services.xulStore.getValue(
3974           BROWSER_DOCURL,
3975           "PersonalToolbar",
3976           "collapsed"
3977         ) == "false";
3978       if (bookmarksToolbarWasVisible) {
3979         // Migrate the user to the "always visible" value. See firefox.js for
3980         // the other possible states.
3981         Services.prefs.setCharPref(
3982           "browser.toolbars.bookmarks.visibility",
3983           "always"
3984         );
3985       }
3986       Services.xulStore.removeValue(
3987         BROWSER_DOCURL,
3988         "PersonalToolbar",
3989         "collapsed"
3990       );
3992       Services.prefs.clearUserPref(
3993         "browser.livebookmarks.migrationAttemptsLeft"
3994       );
3995     }
3997     // For existing profiles, continue putting bookmarks in the
3998     // "other bookmarks" folder.
3999     if (currentUIVersion < 104) {
4000       Services.prefs.setCharPref(
4001         "browser.bookmarks.defaultLocation",
4002         "unfiled"
4003       );
4004     }
4006     // Renamed and flipped the logic of a pref to make its purpose more clear.
4007     if (currentUIVersion < 105) {
4008       const oldPrefName = "browser.urlbar.imeCompositionClosesPanel";
4009       const oldPrefValue = Services.prefs.getBoolPref(oldPrefName, true);
4010       Services.prefs.setBoolPref(
4011         "browser.urlbar.keepPanelOpenDuringImeComposition",
4012         !oldPrefValue
4013       );
4014       Services.prefs.clearUserPref(oldPrefName);
4015     }
4017     // Initialize the new browser.urlbar.showSuggestionsBeforeGeneral pref.
4018     if (currentUIVersion < 106) {
4019       lazy.UrlbarPrefs.initializeShowSearchSuggestionsFirstPref();
4020     }
4022     if (currentUIVersion < 107) {
4023       // Migrate old http URIs for mailto handlers to their https equivalents.
4024       // The handler service will do this. We need to wait with migrating
4025       // until the handler service has started up, so just set a pref here.
4026       const kPref = "browser.handlers.migrations";
4027       // We might have set up another migration further up. Create an array,
4028       // and drop empty strings resulting from the `split`:
4029       let migrations = Services.prefs
4030         .getCharPref(kPref, "")
4031         .split(",")
4032         .filter(x => !!x);
4033       migrations.push("secure-mail");
4034       Services.prefs.setCharPref(kPref, migrations.join(","));
4035     }
4037     if (currentUIVersion < 108) {
4038       // Migrate old ctrlTab pref to new ctrlTab pref
4039       let defaultValue = false;
4040       let oldPrefName = "browser.ctrlTab.recentlyUsedOrder";
4041       let oldPrefDefault = true;
4042       // Use old pref value if the user used Ctrl+Tab before, elsewise use new default value
4043       if (Services.prefs.getBoolPref("browser.engagement.ctrlTab.has-used")) {
4044         let newPrefValue = Services.prefs.getBoolPref(
4045           oldPrefName,
4046           oldPrefDefault
4047         );
4048         Services.prefs.setBoolPref(
4049           "browser.ctrlTab.sortByRecentlyUsed",
4050           newPrefValue
4051         );
4052       } else {
4053         Services.prefs.setBoolPref(
4054           "browser.ctrlTab.sortByRecentlyUsed",
4055           defaultValue
4056         );
4057       }
4058     }
4060     if (currentUIVersion < 109) {
4061       // Migrate old pref to new pref
4062       if (
4063         Services.prefs.prefHasUserValue("signon.recipes.remoteRecipesEnabled")
4064       ) {
4065         // Fetch the previous value of signon.recipes.remoteRecipesEnabled and assign it to signon.recipes.remoteRecipes.enabled.
4066         Services.prefs.setBoolPref(
4067           "signon.recipes.remoteRecipes.enabled",
4068           Services.prefs.getBoolPref(
4069             "signon.recipes.remoteRecipesEnabled",
4070             true
4071           )
4072         );
4073         //Then clear user pref
4074         Services.prefs.clearUserPref("signon.recipes.remoteRecipesEnabled");
4075       }
4076     }
4078     if (currentUIVersion < 120) {
4079       // Migrate old titlebar bool pref to new int-based one.
4080       const oldPref = "browser.tabs.drawInTitlebar";
4081       const newPref = "browser.tabs.inTitlebar";
4082       if (Services.prefs.prefHasUserValue(oldPref)) {
4083         // We may have int prefs for builds between bug 1736518 and bug 1739539.
4084         const oldPrefType = Services.prefs.getPrefType(oldPref);
4085         if (oldPrefType == Services.prefs.PREF_BOOL) {
4086           Services.prefs.setIntPref(
4087             newPref,
4088             Services.prefs.getBoolPref(oldPref) ? 1 : 0
4089           );
4090         } else {
4091           Services.prefs.setIntPref(
4092             newPref,
4093             Services.prefs.getIntPref(oldPref)
4094           );
4095         }
4096         Services.prefs.clearUserPref(oldPref);
4097       }
4098     }
4100     if (currentUIVersion < 121) {
4101       // Migrate stored uris and convert them to use hashed keys
4102       this._migrateHashedKeysForXULStoreForDocument(BROWSER_DOCURL);
4103       this._migrateHashedKeysForXULStoreForDocument(
4104         "chrome://browser/content/places/bookmarksSidebar.xhtml"
4105       );
4106       this._migrateHashedKeysForXULStoreForDocument(
4107         "chrome://browser/content/places/historySidebar.xhtml"
4108       );
4109     }
4111     if (currentUIVersion < 122) {
4112       // Migrate xdg-desktop-portal pref from old to new prefs.
4113       try {
4114         const oldPref = "widget.use-xdg-desktop-portal";
4115         if (Services.prefs.getBoolPref(oldPref)) {
4116           Services.prefs.setIntPref(
4117             "widget.use-xdg-desktop-portal.file-picker",
4118             1
4119           );
4120           Services.prefs.setIntPref(
4121             "widget.use-xdg-desktop-portal.mime-handler",
4122             1
4123           );
4124         }
4125         Services.prefs.clearUserPref(oldPref);
4126       } catch (ex) {}
4127     }
4129     // Bug 1745248: Due to multiple backouts, do not use UI Version 123
4130     // as this version is most likely set for the Nightly channel
4132     if (currentUIVersion < 124) {
4133       // Migrate "extensions.formautofill.available" and
4134       // "extensions.formautofill.creditCards.available" from old to new prefs
4135       const oldFormAutofillModule = "extensions.formautofill.available";
4136       const oldCreditCardsAvailable =
4137         "extensions.formautofill.creditCards.available";
4138       const newCreditCardsAvailable =
4139         "extensions.formautofill.creditCards.supported";
4140       const newAddressesAvailable =
4141         "extensions.formautofill.addresses.supported";
4142       if (Services.prefs.prefHasUserValue(oldFormAutofillModule)) {
4143         let moduleAvailability = Services.prefs.getCharPref(
4144           oldFormAutofillModule
4145         );
4146         if (moduleAvailability == "on") {
4147           Services.prefs.setCharPref(newAddressesAvailable, moduleAvailability);
4148           Services.prefs.setCharPref(
4149             newCreditCardsAvailable,
4150             Services.prefs.getBoolPref(oldCreditCardsAvailable) ? "on" : "off"
4151           );
4152         }
4154         if (moduleAvailability == "off") {
4155           Services.prefs.setCharPref(
4156             newCreditCardsAvailable,
4157             moduleAvailability
4158           );
4159           Services.prefs.setCharPref(newAddressesAvailable, moduleAvailability);
4160         }
4161       }
4163       // after migrating, clear old prefs so we can remove them later.
4164       Services.prefs.clearUserPref(oldFormAutofillModule);
4165       Services.prefs.clearUserPref(oldCreditCardsAvailable);
4166     }
4168     if (currentUIVersion < 125) {
4169       // Bug 1756243 - Clear PiP cached coordinates since we changed their
4170       // coordinate space.
4171       const PIP_PLAYER_URI =
4172         "chrome://global/content/pictureinpicture/player.xhtml";
4173       try {
4174         for (let value of ["left", "top", "width", "height"]) {
4175           Services.xulStore.removeValue(
4176             PIP_PLAYER_URI,
4177             "picture-in-picture",
4178             value
4179           );
4180         }
4181       } catch (ex) {
4182         console.error("Failed to clear XULStore PiP values: ", ex);
4183       }
4184     }
4186     function migrateXULAttributeToStyle(url, id, attr) {
4187       try {
4188         let value = Services.xulStore.getValue(url, id, attr);
4189         if (value) {
4190           Services.xulStore.setValue(url, id, "style", `${attr}: ${value}px;`);
4191         }
4192       } catch (ex) {
4193         console.error(`Error migrating ${id}'s ${attr} value: `, ex);
4194       }
4195     }
4197     // Bug 1792748 used version 129 with a buggy variant of the sidebar width
4198     // migration. This version is already in use in the nightly channel, so it
4199     // shouldn't be used.
4201     // Bug 1793366: migrate sidebar persisted attribute from width to style.
4202     if (currentUIVersion < 130) {
4203       migrateXULAttributeToStyle(BROWSER_DOCURL, "sidebar-box", "width");
4204     }
4206     // Migration 131 was moved to 133 to allow for an uplift.
4208     if (currentUIVersion < 132) {
4209       // These attributes are no longer persisted, thus remove them from xulstore.
4210       for (let url of [
4211         "chrome://browser/content/places/bookmarkProperties.xhtml",
4212         "chrome://browser/content/places/bookmarkProperties2.xhtml",
4213       ]) {
4214         for (let attr of ["width", "screenX", "screenY"]) {
4215           xulStore.removeValue(url, "bookmarkproperties", attr);
4216         }
4217       }
4218     }
4220     if (currentUIVersion < 133) {
4221       xulStore.removeValue(BROWSER_DOCURL, "urlbar-container", "width");
4222     }
4224     // Migration 134 was removed because it was no longer necessary.
4226     if (currentUIVersion < 135 && AppConstants.platform == "linux") {
4227       // Avoid changing titlebar setting for users that used to had it off.
4228       try {
4229         if (!Services.prefs.prefHasUserValue("browser.tabs.inTitlebar")) {
4230           let de = Services.appinfo.desktopEnvironment;
4231           let oldDefault = de.includes("gnome") || de.includes("pantheon");
4232           if (!oldDefault) {
4233             Services.prefs.setIntPref("browser.tabs.inTitlebar", 0);
4234           }
4235         }
4236       } catch (e) {
4237         console.error("Error migrating tabsInTitlebar setting", e);
4238       }
4239     }
4241     if (currentUIVersion < 136) {
4242       migrateXULAttributeToStyle(
4243         "chrome://browser/content/places/places.xhtml",
4244         "placesList",
4245         "width"
4246       );
4247     }
4249     if (currentUIVersion < 137) {
4250       // The default value for enabling smooth scrolls is now false if the
4251       // user prefers reduced motion. If the value was previously set, do
4252       // not reset it, but if it was not explicitly set preserve the old
4253       // default value.
4254       if (
4255         !Services.prefs.prefHasUserValue("general.smoothScroll") &&
4256         Services.appinfo.prefersReducedMotion
4257       ) {
4258         Services.prefs.setBoolPref("general.smoothScroll", true);
4259       }
4260     }
4262     if (currentUIVersion < 138) {
4263       // Bug 1757297: Change scheme of all existing 'https-only-load-insecure'
4264       // permissions with https scheme to http scheme.
4265       try {
4266         Services.perms
4267           .getAllByTypes(["https-only-load-insecure"])
4268           .filter(permission => permission.principal.schemeIs("https"))
4269           .forEach(permission => {
4270             const capability = permission.capability;
4271             const uri = permission.principal.URI.mutate()
4272               .setScheme("http")
4273               .finalize();
4274             const principal =
4275               Services.scriptSecurityManager.createContentPrincipal(uri, {});
4276             Services.perms.removePermission(permission);
4277             Services.perms.addFromPrincipal(
4278               principal,
4279               "https-only-load-insecure",
4280               capability
4281             );
4282           });
4283       } catch (e) {
4284         console.error("Error migrating https-only-load-insecure permission", e);
4285       }
4286     }
4288     if (currentUIVersion < 139) {
4289       // Reset the default permissions to ALLOW_ACTION to rollback issues for
4290       // affected users, see Bug 1579517
4291       // originInfo in the format [origin, type]
4292       [
4293         ["https://www.mozilla.org", "uitour"],
4294         ["https://support.mozilla.org", "uitour"],
4295         ["about:home", "uitour"],
4296         ["about:newtab", "uitour"],
4297         ["https://addons.mozilla.org", "install"],
4298         ["https://support.mozilla.org", "remote-troubleshooting"],
4299         ["about:welcome", "autoplay-media"],
4300       ].forEach(originInfo => {
4301         // Reset permission on the condition that it is set to
4302         // UNKNOWN_ACTION, we want to prevent resetting user
4303         // manipulated permissions
4304         if (
4305           Services.perms.UNKNOWN_ACTION ==
4306           Services.perms.testPermissionFromPrincipal(
4307             Services.scriptSecurityManager.createContentPrincipalFromOrigin(
4308               originInfo[0]
4309             ),
4310             originInfo[1]
4311           )
4312         ) {
4313           // Adding permissions which have default values does not create
4314           // new permissions, but rather remove the UNKNOWN_ACTION permission
4315           // overrides. User's not affected by Bug 1579517 will not be affected by this addition.
4316           Services.perms.addFromPrincipal(
4317             Services.scriptSecurityManager.createContentPrincipalFromOrigin(
4318               originInfo[0]
4319             ),
4320             originInfo[1],
4321             Services.perms.ALLOW_ACTION
4322           );
4323         }
4324       });
4325     }
4327     if (currentUIVersion < 140) {
4328       // Remove browser.fixup.alternate.enabled pref in Bug 1850902.
4329       Services.prefs.clearUserPref("browser.fixup.alternate.enabled");
4330     }
4332     if (currentUIVersion < 141) {
4333       for (const filename of ["signons.sqlite", "signons.sqlite.corrupt"]) {
4334         const filePath = PathUtils.join(PathUtils.profileDir, filename);
4335         IOUtils.remove(filePath, { ignoreAbsent: true }).catch(console.error);
4336       }
4337     }
4339     if (currentUIVersion < 142) {
4340       // Bug 1860392 - Remove incorrectly persisted theming values from sidebar style.
4341       try {
4342         let value = xulStore.getValue(BROWSER_DOCURL, "sidebar-box", "style");
4343         if (value) {
4344           // Remove custom properties.
4345           value = value
4346             .split(";")
4347             .filter(v => !v.trim().startsWith("--"))
4348             .join(";");
4349           xulStore.setValue(BROWSER_DOCURL, "sidebar-box", "style", value);
4350         }
4351       } catch (ex) {
4352         console.error(ex);
4353       }
4354     }
4356     if (currentUIVersion < 143) {
4357       if (AppConstants.platform == "win") {
4358         // In Firefox 122, we enabled the firefox and firefox-private protocols.
4359         // We switched over to using firefox-bridge and firefox-private-bridge,
4360         // but we want to clean up the use of the other protocols.
4361         lazy.FirefoxBridgeExtensionUtils.maybeDeleteBridgeProtocolRegistryEntries();
4363         // Register the new firefox bridge related protocols now
4364         lazy.FirefoxBridgeExtensionUtils.maybeRegisterFirefoxBridgeProtocols();
4366         // Clean up the old user prefs from FX 122
4367         Services.prefs.clearUserPref(
4368           "network.protocol-handler.external.firefox"
4369         );
4370         Services.prefs.clearUserPref(
4371           "network.protocol-handler.external.firefox-private"
4372         );
4373         Services.prefs.clearUserPref("browser.shell.customProtocolsRegistered");
4374       }
4375     }
4377     // Update the migration version.
4378     Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
4379   },
4381   async _showUpgradeDialog() {
4382     const data = await lazy.OnboardingMessageProvider.getUpgradeMessage();
4383     const { gBrowser } = lazy.BrowserWindowTracker.getTopWindow();
4385     // We'll be adding a new tab open the tab-modal dialog in.
4386     let tab;
4388     const upgradeTabsProgressListener = {
4389       onLocationChange(aBrowser) {
4390         if (aBrowser === tab.linkedBrowser) {
4391           lazy.setTimeout(() => {
4392             // We're now far enough along in the load that we no longer have to
4393             // worry about a call to onLocationChange triggering SubDialog.abort,
4394             // so display the dialog
4395             const config = {
4396               type: "SHOW_SPOTLIGHT",
4397               data,
4398             };
4399             lazy.SpecialMessageActions.handleAction(config, tab.linkedBrowser);
4401             gBrowser.removeTabsProgressListener(upgradeTabsProgressListener);
4402           }, 0);
4403         }
4404       },
4405     };
4407     // Make sure we're ready to show the dialog once onLocationChange gets
4408     // called.
4409     gBrowser.addTabsProgressListener(upgradeTabsProgressListener);
4411     tab = gBrowser.addTrustedTab("about:home", {
4412       relatedToCurrent: true,
4413     });
4415     gBrowser.selectedTab = tab;
4416   },
4418   async _showAboutWelcomeModal() {
4419     const { gBrowser } = lazy.BrowserWindowTracker.getTopWindow();
4420     const data = await lazy.NimbusFeatures.aboutwelcome.getAllVariables();
4422     const config = {
4423       type: "SHOW_SPOTLIGHT",
4424       data: {
4425         content: {
4426           template: "multistage",
4427           id: data?.id || "ABOUT_WELCOME_MODAL",
4428           backdrop: data?.backdrop,
4429           screens: data?.screens,
4430           UTMTerm: data?.UTMTerm,
4431         },
4432       },
4433     };
4435     lazy.SpecialMessageActions.handleAction(config, gBrowser);
4436   },
4438   async _maybeShowDefaultBrowserPrompt() {
4439     // Highest priority is about:welcome window modal experiment
4440     // Second highest priority is the upgrade dialog, which can include a "primary
4441     // browser" request and is limited in various ways, e.g., major upgrades.
4442     if (
4443       lazy.BrowserHandler.firstRunProfile &&
4444       lazy.NimbusFeatures.aboutwelcome.getVariable("showModal")
4445     ) {
4446       this._showAboutWelcomeModal();
4447       return;
4448     }
4449     const dialogVersion = 106;
4450     const dialogVersionPref = "browser.startup.upgradeDialog.version";
4451     const dialogReason = await (async () => {
4452       if (!lazy.BrowserHandler.majorUpgrade) {
4453         return "not-major";
4454       }
4455       const lastVersion = Services.prefs.getIntPref(dialogVersionPref, 0);
4456       if (lastVersion > dialogVersion) {
4457         return "newer-shown";
4458       }
4459       if (lastVersion === dialogVersion) {
4460         return "already-shown";
4461       }
4463       // Check the default branch as enterprise policies can set prefs there.
4464       const defaultPrefs = Services.prefs.getDefaultBranch("");
4465       if (
4466         !defaultPrefs.getBoolPref(
4467           "browser.messaging-system.whatsNewPanel.enabled",
4468           true
4469         )
4470       ) {
4471         return "no-whatsNew";
4472       }
4473       if (!defaultPrefs.getBoolPref("browser.aboutwelcome.enabled", true)) {
4474         return "no-welcome";
4475       }
4476       if (!Services.policies.isAllowed("postUpdateCustomPage")) {
4477         return "disallow-postUpdate";
4478       }
4480       const useMROnboarding =
4481         lazy.NimbusFeatures.majorRelease2022.getVariable("onboarding");
4482       const showUpgradeDialog =
4483         useMROnboarding ??
4484         lazy.NimbusFeatures.upgradeDialog.getVariable("enabled");
4486       return showUpgradeDialog ? "" : "disabled";
4487     })();
4489     // Record why the dialog is showing or not.
4490     Services.telemetry.setEventRecordingEnabled("upgrade_dialog", true);
4491     Services.telemetry.recordEvent(
4492       "upgrade_dialog",
4493       "trigger",
4494       "reason",
4495       dialogReason || "satisfied"
4496     );
4498     // Show the upgrade dialog if allowed and remember the version.
4499     if (!dialogReason) {
4500       Services.prefs.setIntPref(dialogVersionPref, dialogVersion);
4501       this._showUpgradeDialog();
4502       return;
4503     }
4505     const willPrompt = await DefaultBrowserCheck.willCheckDefaultBrowser(
4506       /* isStartupCheck */ true
4507     );
4508     if (willPrompt) {
4509       let win = lazy.BrowserWindowTracker.getTopWindow();
4510       DefaultBrowserCheck.prompt(win);
4511     } else if (await lazy.QuickSuggest.maybeShowOnboardingDialog()) {
4512       return;
4513     }
4515     await lazy.ASRouter.waitForInitialized;
4516     lazy.ASRouter.sendTriggerMessage({
4517       browser:
4518         lazy.BrowserWindowTracker.getTopWindow()?.gBrowser.selectedBrowser,
4519       // triggerId and triggerContext
4520       id: "defaultBrowserCheck",
4521       context: { willShowDefaultPrompt: willPrompt, source: "startup" },
4522     });
4523   },
4525   /**
4526    * Only show the infobar when canRestoreLastSession and the pref value == 1
4527    */
4528   async _maybeShowRestoreSessionInfoBar() {
4529     let count = Services.prefs.getIntPref(
4530       "browser.startup.couldRestoreSession.count",
4531       0
4532     );
4533     if (count < 0 || count >= 2) {
4534       return;
4535     }
4536     if (count == 0) {
4537       // We don't show the infobar right after the update which establishes this pref
4538       // Increment the counter so we can consider it next time
4539       Services.prefs.setIntPref(
4540         "browser.startup.couldRestoreSession.count",
4541         ++count
4542       );
4543       return;
4544     }
4546     const win = lazy.BrowserWindowTracker.getTopWindow();
4547     // We've restarted at least once; we will show the notification if possible.
4548     // We can't do that if there's no session to restore, or this is a private window.
4549     if (
4550       !lazy.SessionStore.canRestoreLastSession ||
4551       lazy.PrivateBrowsingUtils.isWindowPrivate(win)
4552     ) {
4553       return;
4554     }
4556     Services.prefs.setIntPref(
4557       "browser.startup.couldRestoreSession.count",
4558       ++count
4559     );
4561     const messageFragment = win.document.createDocumentFragment();
4562     const message = win.document.createElement("span");
4563     const icon = win.document.createElement("img");
4564     icon.src = "chrome://browser/skin/menu.svg";
4565     icon.setAttribute("data-l10n-name", "icon");
4566     icon.className = "inline-icon";
4567     message.appendChild(icon);
4568     messageFragment.appendChild(message);
4569     win.document.l10n.setAttributes(
4570       message,
4571       "restore-session-startup-suggestion-message"
4572     );
4574     const buttons = [
4575       {
4576         "l10n-id": "restore-session-startup-suggestion-button",
4577         primary: true,
4578         callback: () => {
4579           win.PanelUI.selectAndMarkItem([
4580             "appMenu-history-button",
4581             "appMenu-restoreSession",
4582           ]);
4583         },
4584       },
4585     ];
4587     const notifyBox = win.gBrowser.getNotificationBox();
4588     const notification = await notifyBox.appendNotification(
4589       "startup-restore-session-suggestion",
4590       {
4591         label: messageFragment,
4592         priority: notifyBox.PRIORITY_INFO_MEDIUM,
4593       },
4594       buttons
4595     );
4596     // Don't allow it to be immediately hidden:
4597     notification.timeout = Date.now() + 3000;
4598   },
4600   /**
4601    * Open preferences even if there are no open windows.
4602    */
4603   _openPreferences(...args) {
4604     let chromeWindow = lazy.BrowserWindowTracker.getTopWindow();
4605     if (chromeWindow) {
4606       chromeWindow.openPreferences(...args);
4607       return;
4608     }
4610     if (Services.appShell.hiddenDOMWindow.openPreferences) {
4611       Services.appShell.hiddenDOMWindow.openPreferences(...args);
4612     }
4613   },
4615   _openURLInNewWindow(url) {
4616     let urlString = Cc["@mozilla.org/supports-string;1"].createInstance(
4617       Ci.nsISupportsString
4618     );
4619     urlString.data = url;
4620     return new Promise(resolve => {
4621       let win = Services.ww.openWindow(
4622         null,
4623         AppConstants.BROWSER_CHROME_URL,
4624         "_blank",
4625         "chrome,all,dialog=no",
4626         urlString
4627       );
4628       win.addEventListener(
4629         "load",
4630         () => {
4631           resolve(win);
4632         },
4633         { once: true }
4634       );
4635     });
4636   },
4638   /**
4639    * Called as an observer when Sync's "display URIs" notification is fired.
4640    *
4641    * We open the received URIs in background tabs.
4642    */
4643   async _onDisplaySyncURIs(data) {
4644     try {
4645       // The payload is wrapped weirdly because of how Sync does notifications.
4646       const URIs = data.wrappedJSObject.object;
4648       // win can be null, but it's ok, we'll assign it later in openTab()
4649       let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4651       const openTab = async URI => {
4652         let tab;
4653         if (!win) {
4654           win = await this._openURLInNewWindow(URI.uri);
4655           let tabs = win.gBrowser.tabs;
4656           tab = tabs[tabs.length - 1];
4657         } else {
4658           tab = win.gBrowser.addWebTab(URI.uri);
4659         }
4660         tab.attention = true;
4661         return tab;
4662       };
4664       const firstTab = await openTab(URIs[0]);
4665       await Promise.all(URIs.slice(1).map(URI => openTab(URI)));
4667       const deviceName = URIs[0].sender && URIs[0].sender.name;
4668       let titleL10nId, body;
4669       if (URIs.length == 1) {
4670         // Due to bug 1305895, tabs from iOS may not have device information, so
4671         // we have separate strings to handle those cases. (See Also
4672         // unnamedTabsArrivingNotificationNoDevice.body below)
4673         titleL10nId = deviceName
4674           ? {
4675               id: "account-single-tab-arriving-from-device-title",
4676               args: { deviceName },
4677             }
4678           : { id: "account-single-tab-arriving-title" };
4679         // Use the page URL as the body. We strip the fragment and query (after
4680         // the `?` and `#` respectively) to reduce size, and also format it the
4681         // same way that the url bar would.
4682         let url = URIs[0].uri.replace(/([?#]).*$/, "$1");
4683         const wasTruncated = url.length < URIs[0].uri.length;
4684         url = lazy.BrowserUIUtils.trimURL(url);
4685         if (wasTruncated) {
4686           body = await lazy.accountsL10n.formatValue(
4687             "account-single-tab-arriving-truncated-url",
4688             { url }
4689           );
4690         } else {
4691           body = url;
4692         }
4693       } else {
4694         titleL10nId = { id: "account-multiple-tabs-arriving-title" };
4695         const allKnownSender = URIs.every(URI => URI.sender != null);
4696         const allSameDevice =
4697           allKnownSender &&
4698           URIs.every(URI => URI.sender.id == URIs[0].sender.id);
4699         let bodyL10nId;
4700         if (allSameDevice) {
4701           bodyL10nId = deviceName
4702             ? "account-multiple-tabs-arriving-from-single-device"
4703             : "account-multiple-tabs-arriving-from-unknown-device";
4704         } else {
4705           bodyL10nId = "account-multiple-tabs-arriving-from-multiple-devices";
4706         }
4708         body = await lazy.accountsL10n.formatValue(bodyL10nId, {
4709           deviceName,
4710           tabCount: URIs.length,
4711         });
4712       }
4713       const title = await lazy.accountsL10n.formatValue(titleL10nId);
4715       const clickCallback = (obsSubject, obsTopic) => {
4716         if (obsTopic == "alertclickcallback") {
4717           win.gBrowser.selectedTab = firstTab;
4718         }
4719       };
4721       // Specify an icon because on Windows no icon is shown at the moment
4722       let imageURL;
4723       if (AppConstants.platform == "win") {
4724         imageURL = "chrome://branding/content/icon64.png";
4725       }
4726       this.AlertsService.showAlertNotification(
4727         imageURL,
4728         title,
4729         body,
4730         true,
4731         null,
4732         clickCallback
4733       );
4734     } catch (ex) {
4735       console.error("Error displaying tab(s) received by Sync: ", ex);
4736     }
4737   },
4739   async _onVerifyLoginNotification({ body, title, url }) {
4740     let tab;
4741     let imageURL;
4742     if (AppConstants.platform == "win") {
4743       imageURL = "chrome://branding/content/icon64.png";
4744     }
4745     let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4746     if (!win) {
4747       win = await this._openURLInNewWindow(url);
4748       let tabs = win.gBrowser.tabs;
4749       tab = tabs[tabs.length - 1];
4750     } else {
4751       tab = win.gBrowser.addWebTab(url);
4752     }
4753     tab.attention = true;
4754     let clickCallback = (subject, topic) => {
4755       if (topic != "alertclickcallback") {
4756         return;
4757       }
4758       win.gBrowser.selectedTab = tab;
4759     };
4761     try {
4762       this.AlertsService.showAlertNotification(
4763         imageURL,
4764         title,
4765         body,
4766         true,
4767         null,
4768         clickCallback
4769       );
4770     } catch (ex) {
4771       console.error("Error notifying of a verify login event: ", ex);
4772     }
4773   },
4775   _onDeviceConnected(deviceName) {
4776     const [title, body] = lazy.accountsL10n.formatValuesSync([
4777       { id: "account-connection-title" },
4778       deviceName
4779         ? { id: "account-connection-connected-with", args: { deviceName } }
4780         : { id: "account-connection-connected-with-noname" },
4781     ]);
4783     let clickCallback = async (subject, topic) => {
4784       if (topic != "alertclickcallback") {
4785         return;
4786       }
4787       let url = await lazy.FxAccounts.config.promiseManageDevicesURI(
4788         "device-connected-notification"
4789       );
4790       let win = lazy.BrowserWindowTracker.getTopWindow({ private: false });
4791       if (!win) {
4792         this._openURLInNewWindow(url);
4793       } else {
4794         win.gBrowser.addWebTab(url);
4795       }
4796     };
4798     try {
4799       this.AlertsService.showAlertNotification(
4800         null,
4801         title,
4802         body,
4803         true,
4804         null,
4805         clickCallback
4806       );
4807     } catch (ex) {
4808       console.error("Error notifying of a new Sync device: ", ex);
4809     }
4810   },
4812   _onDeviceDisconnected() {
4813     const [title, body] = lazy.accountsL10n.formatValuesSync([
4814       "account-connection-title",
4815       "account-connection-disconnected",
4816     ]);
4818     let clickCallback = (subject, topic) => {
4819       if (topic != "alertclickcallback") {
4820         return;
4821       }
4822       this._openPreferences("sync");
4823     };
4824     this.AlertsService.showAlertNotification(
4825       null,
4826       title,
4827       body,
4828       true,
4829       null,
4830       clickCallback
4831     );
4832   },
4834   _updateFxaBadges(win) {
4835     let fxaButton = win.document.getElementById("fxa-toolbar-menu-button");
4836     let badge = fxaButton?.querySelector(".toolbarbutton-badge");
4838     let state = lazy.UIState.get();
4839     if (
4840       state.status == lazy.UIState.STATUS_LOGIN_FAILED ||
4841       state.status == lazy.UIState.STATUS_NOT_VERIFIED
4842     ) {
4843       // If the fxa toolbar button is in the toolbox, we display the notification
4844       // on the fxa button instead of the app menu.
4845       let navToolbox = win.document.getElementById("navigator-toolbox");
4846       let isFxAButtonShown = navToolbox.contains(fxaButton);
4847       if (isFxAButtonShown) {
4848         state.status == lazy.UIState.STATUS_LOGIN_FAILED
4849           ? fxaButton?.setAttribute("badge-status", state.status)
4850           : badge?.classList.add("feature-callout");
4851       } else {
4852         lazy.AppMenuNotifications.showBadgeOnlyNotification(
4853           "fxa-needs-authentication"
4854         );
4855       }
4856     } else {
4857       fxaButton?.removeAttribute("badge-status");
4858       badge?.classList.remove("feature-callout");
4859       lazy.AppMenuNotifications.removeNotification("fxa-needs-authentication");
4860     }
4861   },
4863   _collectTelemetryPiPEnabled() {
4864     Services.telemetry.setEventRecordingEnabled(
4865       "pictureinpicture.settings",
4866       true
4867     );
4868     Services.telemetry.setEventRecordingEnabled("pictureinpicture", true);
4870     const TOGGLE_ENABLED_PREF =
4871       "media.videocontrols.picture-in-picture.video-toggle.enabled";
4873     const observe = (subject, topic) => {
4874       const enabled = Services.prefs.getBoolPref(TOGGLE_ENABLED_PREF, false);
4875       Services.telemetry.scalarSet("pictureinpicture.toggle_enabled", enabled);
4877       // Record events when preferences change
4878       if (topic === "nsPref:changed") {
4879         if (enabled) {
4880           Services.telemetry.recordEvent(
4881             "pictureinpicture.settings",
4882             "enable",
4883             "settings"
4884           );
4885         }
4886       }
4887     };
4889     Services.prefs.addObserver(TOGGLE_ENABLED_PREF, observe);
4890     observe();
4891   },
4893   QueryInterface: ChromeUtils.generateQI([
4894     "nsIObserver",
4895     "nsISupportsWeakReference",
4896   ]),
4899 var ContentBlockingCategoriesPrefs = {
4900   PREF_CB_CATEGORY: "browser.contentblocking.category",
4901   PREF_STRICT_DEF: "browser.contentblocking.features.strict",
4902   switchingCategory: false,
4904   setPrefExpectations() {
4905     // The prefs inside CATEGORY_PREFS are initial values.
4906     // If the pref remains null, then it will expect the default value.
4907     // The "standard" category is defined as expecting all 5 default values.
4908     this.CATEGORY_PREFS = {
4909       strict: {
4910         "network.cookie.cookieBehavior": null,
4911         "network.cookie.cookieBehavior.pbmode": null,
4912         "privacy.trackingprotection.pbmode.enabled": null,
4913         "privacy.trackingprotection.enabled": null,
4914         "privacy.trackingprotection.socialtracking.enabled": null,
4915         "privacy.trackingprotection.fingerprinting.enabled": null,
4916         "privacy.trackingprotection.cryptomining.enabled": null,
4917         "privacy.trackingprotection.emailtracking.enabled": null,
4918         "privacy.trackingprotection.emailtracking.pbmode.enabled": null,
4919         "privacy.annotate_channels.strict_list.enabled": null,
4920         "network.http.referer.disallowCrossSiteRelaxingDefault": null,
4921         "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation":
4922           null,
4923         "privacy.partition.network_state.ocsp_cache": null,
4924         "privacy.query_stripping.enabled": null,
4925         "privacy.query_stripping.enabled.pbmode": null,
4926         "privacy.fingerprintingProtection": null,
4927         "privacy.fingerprintingProtection.pbmode": null,
4928       },
4929       standard: {
4930         "network.cookie.cookieBehavior": null,
4931         "network.cookie.cookieBehavior.pbmode": null,
4932         "privacy.trackingprotection.pbmode.enabled": null,
4933         "privacy.trackingprotection.enabled": null,
4934         "privacy.trackingprotection.socialtracking.enabled": null,
4935         "privacy.trackingprotection.fingerprinting.enabled": null,
4936         "privacy.trackingprotection.cryptomining.enabled": null,
4937         "privacy.trackingprotection.emailtracking.enabled": null,
4938         "privacy.trackingprotection.emailtracking.pbmode.enabled": null,
4939         "privacy.annotate_channels.strict_list.enabled": null,
4940         "network.http.referer.disallowCrossSiteRelaxingDefault": null,
4941         "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation":
4942           null,
4943         "privacy.partition.network_state.ocsp_cache": null,
4944         "privacy.query_stripping.enabled": null,
4945         "privacy.query_stripping.enabled.pbmode": null,
4946         "privacy.fingerprintingProtection": null,
4947         "privacy.fingerprintingProtection.pbmode": null,
4948       },
4949     };
4950     let type = "strict";
4951     let rulesArray = Services.prefs
4952       .getStringPref(this.PREF_STRICT_DEF)
4953       .split(",");
4954     for (let item of rulesArray) {
4955       switch (item) {
4956         case "tp":
4957           this.CATEGORY_PREFS[type][
4958             "privacy.trackingprotection.enabled"
4959           ] = true;
4960           break;
4961         case "-tp":
4962           this.CATEGORY_PREFS[type][
4963             "privacy.trackingprotection.enabled"
4964           ] = false;
4965           break;
4966         case "tpPrivate":
4967           this.CATEGORY_PREFS[type][
4968             "privacy.trackingprotection.pbmode.enabled"
4969           ] = true;
4970           break;
4971         case "-tpPrivate":
4972           this.CATEGORY_PREFS[type][
4973             "privacy.trackingprotection.pbmode.enabled"
4974           ] = false;
4975           break;
4976         case "fp":
4977           this.CATEGORY_PREFS[type][
4978             "privacy.trackingprotection.fingerprinting.enabled"
4979           ] = true;
4980           break;
4981         case "-fp":
4982           this.CATEGORY_PREFS[type][
4983             "privacy.trackingprotection.fingerprinting.enabled"
4984           ] = false;
4985           break;
4986         case "cm":
4987           this.CATEGORY_PREFS[type][
4988             "privacy.trackingprotection.cryptomining.enabled"
4989           ] = true;
4990           break;
4991         case "-cm":
4992           this.CATEGORY_PREFS[type][
4993             "privacy.trackingprotection.cryptomining.enabled"
4994           ] = false;
4995           break;
4996         case "stp":
4997           this.CATEGORY_PREFS[type][
4998             "privacy.trackingprotection.socialtracking.enabled"
4999           ] = true;
5000           break;
5001         case "-stp":
5002           this.CATEGORY_PREFS[type][
5003             "privacy.trackingprotection.socialtracking.enabled"
5004           ] = false;
5005           break;
5006         case "emailTP":
5007           this.CATEGORY_PREFS[type][
5008             "privacy.trackingprotection.emailtracking.enabled"
5009           ] = true;
5010           break;
5011         case "-emailTP":
5012           this.CATEGORY_PREFS[type][
5013             "privacy.trackingprotection.emailtracking.enabled"
5014           ] = false;
5015           break;
5016         case "emailTPPrivate":
5017           this.CATEGORY_PREFS[type][
5018             "privacy.trackingprotection.emailtracking.pbmode.enabled"
5019           ] = true;
5020           break;
5021         case "-emailTPPrivate":
5022           this.CATEGORY_PREFS[type][
5023             "privacy.trackingprotection.emailtracking.pbmode.enabled"
5024           ] = false;
5025           break;
5026         case "lvl2":
5027           this.CATEGORY_PREFS[type][
5028             "privacy.annotate_channels.strict_list.enabled"
5029           ] = true;
5030           break;
5031         case "-lvl2":
5032           this.CATEGORY_PREFS[type][
5033             "privacy.annotate_channels.strict_list.enabled"
5034           ] = false;
5035           break;
5036         case "rp":
5037           this.CATEGORY_PREFS[type][
5038             "network.http.referer.disallowCrossSiteRelaxingDefault"
5039           ] = true;
5040           break;
5041         case "-rp":
5042           this.CATEGORY_PREFS[type][
5043             "network.http.referer.disallowCrossSiteRelaxingDefault"
5044           ] = false;
5045           break;
5046         case "rpTop":
5047           this.CATEGORY_PREFS[type][
5048             "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation"
5049           ] = true;
5050           break;
5051         case "-rpTop":
5052           this.CATEGORY_PREFS[type][
5053             "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation"
5054           ] = false;
5055           break;
5056         case "ocsp":
5057           this.CATEGORY_PREFS[type][
5058             "privacy.partition.network_state.ocsp_cache"
5059           ] = true;
5060           break;
5061         case "-ocsp":
5062           this.CATEGORY_PREFS[type][
5063             "privacy.partition.network_state.ocsp_cache"
5064           ] = false;
5065           break;
5066         case "qps":
5067           this.CATEGORY_PREFS[type]["privacy.query_stripping.enabled"] = true;
5068           break;
5069         case "-qps":
5070           this.CATEGORY_PREFS[type]["privacy.query_stripping.enabled"] = false;
5071           break;
5072         case "qpsPBM":
5073           this.CATEGORY_PREFS[type][
5074             "privacy.query_stripping.enabled.pbmode"
5075           ] = true;
5076           break;
5077         case "-qpsPBM":
5078           this.CATEGORY_PREFS[type][
5079             "privacy.query_stripping.enabled.pbmode"
5080           ] = false;
5081           break;
5082         case "fpp":
5083           this.CATEGORY_PREFS[type]["privacy.fingerprintingProtection"] = true;
5084           break;
5085         case "-fpp":
5086           this.CATEGORY_PREFS[type]["privacy.fingerprintingProtection"] = false;
5087           break;
5088         case "fppPrivate":
5089           this.CATEGORY_PREFS[type][
5090             "privacy.fingerprintingProtection.pbmode"
5091           ] = true;
5092           break;
5093         case "-fppPrivate":
5094           this.CATEGORY_PREFS[type][
5095             "privacy.fingerprintingProtection.pbmode"
5096           ] = false;
5097           break;
5098         case "cookieBehavior0":
5099           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5100             Ci.nsICookieService.BEHAVIOR_ACCEPT;
5101           break;
5102         case "cookieBehavior1":
5103           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5104             Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN;
5105           break;
5106         case "cookieBehavior2":
5107           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5108             Ci.nsICookieService.BEHAVIOR_REJECT;
5109           break;
5110         case "cookieBehavior3":
5111           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5112             Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN;
5113           break;
5114         case "cookieBehavior4":
5115           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5116             Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
5117           break;
5118         case "cookieBehavior5":
5119           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior"] =
5120             Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
5121           break;
5122         case "cookieBehaviorPBM0":
5123           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5124             Ci.nsICookieService.BEHAVIOR_ACCEPT;
5125           break;
5126         case "cookieBehaviorPBM1":
5127           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5128             Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN;
5129           break;
5130         case "cookieBehaviorPBM2":
5131           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5132             Ci.nsICookieService.BEHAVIOR_REJECT;
5133           break;
5134         case "cookieBehaviorPBM3":
5135           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5136             Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN;
5137           break;
5138         case "cookieBehaviorPBM4":
5139           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5140             Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
5141           break;
5142         case "cookieBehaviorPBM5":
5143           this.CATEGORY_PREFS[type]["network.cookie.cookieBehavior.pbmode"] =
5144             Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
5145           break;
5146         default:
5147           console.error(`Error: Unknown rule observed ${item}`);
5148       }
5149     }
5150   },
5152   /**
5153    * Checks if CB prefs match perfectly with one of our pre-defined categories.
5154    */
5155   prefsMatch(category) {
5156     // The category pref must be either unset, or match.
5157     if (
5158       Services.prefs.prefHasUserValue(this.PREF_CB_CATEGORY) &&
5159       Services.prefs.getStringPref(this.PREF_CB_CATEGORY) != category
5160     ) {
5161       return false;
5162     }
5163     for (let pref in this.CATEGORY_PREFS[category]) {
5164       let value = this.CATEGORY_PREFS[category][pref];
5165       if (value == null) {
5166         if (Services.prefs.prefHasUserValue(pref)) {
5167           return false;
5168         }
5169       } else {
5170         let prefType = Services.prefs.getPrefType(pref);
5171         if (
5172           (prefType == Services.prefs.PREF_BOOL &&
5173             Services.prefs.getBoolPref(pref) != value) ||
5174           (prefType == Services.prefs.PREF_INT &&
5175             Services.prefs.getIntPref(pref) != value) ||
5176           (prefType == Services.prefs.PREF_STRING &&
5177             Services.prefs.getStringPref(pref) != value)
5178         ) {
5179           return false;
5180         }
5181       }
5182     }
5183     return true;
5184   },
5186   matchCBCategory() {
5187     if (this.switchingCategory) {
5188       return;
5189     }
5190     // If PREF_CB_CATEGORY is not set match users to a Content Blocking category. Check if prefs fit
5191     // perfectly into strict or standard, otherwise match with custom. If PREF_CB_CATEGORY has previously been set,
5192     // a change of one of these prefs necessarily puts us in "custom".
5193     if (this.prefsMatch("standard")) {
5194       Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "standard");
5195     } else if (this.prefsMatch("strict")) {
5196       Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "strict");
5197     } else {
5198       Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "custom");
5199     }
5201     // If there is a custom policy which changes a related pref, then put the user in custom so
5202     // they still have access to other content blocking prefs, and to keep our default definitions
5203     // from changing.
5204     let policy = Services.policies.getActivePolicies();
5205     if (policy && (policy.EnableTrackingProtection || policy.Cookies)) {
5206       Services.prefs.setStringPref(this.PREF_CB_CATEGORY, "custom");
5207     }
5208   },
5210   updateCBCategory() {
5211     if (
5212       this.switchingCategory ||
5213       !Services.prefs.prefHasUserValue(this.PREF_CB_CATEGORY)
5214     ) {
5215       return;
5216     }
5217     // Turn on switchingCategory flag, to ensure that when the individual prefs that change as a result
5218     // of the category change do not trigger yet another category change.
5219     this.switchingCategory = true;
5220     let value = Services.prefs.getStringPref(this.PREF_CB_CATEGORY);
5221     this.setPrefsToCategory(value);
5222     this.switchingCategory = false;
5223   },
5225   /**
5226    * Sets all user-exposed content blocking preferences to values that match the selected category.
5227    */
5228   setPrefsToCategory(category) {
5229     // Leave prefs as they were if we are switching to "custom" category.
5230     if (category == "custom") {
5231       return;
5232     }
5234     for (let pref in this.CATEGORY_PREFS[category]) {
5235       let value = this.CATEGORY_PREFS[category][pref];
5236       if (!Services.prefs.prefIsLocked(pref)) {
5237         if (value == null) {
5238           Services.prefs.clearUserPref(pref);
5239         } else {
5240           switch (Services.prefs.getPrefType(pref)) {
5241             case Services.prefs.PREF_BOOL:
5242               Services.prefs.setBoolPref(pref, value);
5243               break;
5244             case Services.prefs.PREF_INT:
5245               Services.prefs.setIntPref(pref, value);
5246               break;
5247             case Services.prefs.PREF_STRING:
5248               Services.prefs.setStringPref(pref, value);
5249               break;
5250           }
5251         }
5252       }
5253     }
5254   },
5258  * ContentPermissionIntegration is responsible for showing the user
5259  * simple permission prompts when content requests additional
5260  * capabilities.
5262  * While there are some built-in permission prompts, createPermissionPrompt
5263  * can also be overridden by system add-ons or tests to provide new ones.
5265  * This override ability is provided by Integration.sys.mjs. See
5266  * PermissionUI.sys.mjs for an example of how to provide a new prompt
5267  * from an add-on.
5268  */
5269 const ContentPermissionIntegration = {
5270   /**
5271    * Creates a PermissionPrompt for a given permission type and
5272    * nsIContentPermissionRequest.
5273    *
5274    * @param {string} type
5275    *        The type of the permission request from content. This normally
5276    *        matches the "type" field of an nsIContentPermissionType, but it
5277    *        can be something else if the permission does not use the
5278    *        nsIContentPermissionRequest model. Note that this type might also
5279    *        be different from the permission key used in the permissions
5280    *        database.
5281    *        Example: "geolocation"
5282    * @param {nsIContentPermissionRequest} request
5283    *        The request for a permission from content.
5284    * @return {PermissionPrompt} (see PermissionUI.sys.mjs),
5285    *         or undefined if the type cannot be handled.
5286    */
5287   createPermissionPrompt(type, request) {
5288     switch (type) {
5289       case "geolocation": {
5290         return new lazy.PermissionUI.GeolocationPermissionPrompt(request);
5291       }
5292       case "xr": {
5293         return new lazy.PermissionUI.XRPermissionPrompt(request);
5294       }
5295       case "desktop-notification": {
5296         return new lazy.PermissionUI.DesktopNotificationPermissionPrompt(
5297           request
5298         );
5299       }
5300       case "persistent-storage": {
5301         return new lazy.PermissionUI.PersistentStoragePermissionPrompt(request);
5302       }
5303       case "midi": {
5304         return new lazy.PermissionUI.MIDIPermissionPrompt(request);
5305       }
5306       case "storage-access": {
5307         return new lazy.PermissionUI.StorageAccessPermissionPrompt(request);
5308       }
5309     }
5310     return undefined;
5311   },
5314 export function ContentPermissionPrompt() {}
5316 ContentPermissionPrompt.prototype = {
5317   classID: Components.ID("{d8903bf6-68d5-4e97-bcd1-e4d3012f721a}"),
5319   QueryInterface: ChromeUtils.generateQI(["nsIContentPermissionPrompt"]),
5321   /**
5322    * This implementation of nsIContentPermissionPrompt.prompt ensures
5323    * that there's only one nsIContentPermissionType in the request,
5324    * and that it's of type nsIContentPermissionType. Failing to
5325    * satisfy either of these conditions will result in this method
5326    * throwing NS_ERRORs. If the combined ContentPermissionIntegration
5327    * cannot construct a prompt for this particular request, an
5328    * NS_ERROR_FAILURE will be thrown.
5329    *
5330    * Any time an error is thrown, the nsIContentPermissionRequest is
5331    * cancelled automatically.
5332    *
5333    * @param {nsIContentPermissionRequest} request
5334    *        The request that we're to show a prompt for.
5335    */
5336   prompt(request) {
5337     if (request.element && request.element.fxrPermissionPrompt) {
5338       // For Firefox Reality on Desktop, switch to a different mechanism to
5339       // prompt the user since fewer permissions are available and since many
5340       // UI dependencies are not availabe.
5341       request.element.fxrPermissionPrompt(request);
5342       return;
5343     }
5345     let type;
5346     try {
5347       // Only allow exactly one permission request here.
5348       let types = request.types.QueryInterface(Ci.nsIArray);
5349       if (types.length != 1) {
5350         throw Components.Exception(
5351           "Expected an nsIContentPermissionRequest with only 1 type.",
5352           Cr.NS_ERROR_UNEXPECTED
5353         );
5354       }
5356       type = types.queryElementAt(0, Ci.nsIContentPermissionType).type;
5357       let combinedIntegration = lazy.Integration.contentPermission.getCombined(
5358         ContentPermissionIntegration
5359       );
5361       let permissionPrompt = combinedIntegration.createPermissionPrompt(
5362         type,
5363         request
5364       );
5365       if (!permissionPrompt) {
5366         throw Components.Exception(
5367           `Failed to handle permission of type ${type}`,
5368           Cr.NS_ERROR_FAILURE
5369         );
5370       }
5372       permissionPrompt.prompt();
5373     } catch (ex) {
5374       console.error(ex);
5375       request.cancel();
5376       throw ex;
5377     }
5379     let schemeHistogram = Services.telemetry.getKeyedHistogramById(
5380       "PERMISSION_REQUEST_ORIGIN_SCHEME"
5381     );
5382     let scheme = 0;
5383     try {
5384       if (request.principal.schemeIs("http")) {
5385         scheme = 1;
5386       } else if (request.principal.schemeIs("https")) {
5387         scheme = 2;
5388       }
5389     } catch (ex) {
5390       // If the request principal is not available at this point,
5391       // the request has likely been cancelled before being shown to the
5392       // user. We shouldn't record this request.
5393       if (ex.result != Cr.NS_ERROR_FAILURE) {
5394         console.error(ex);
5395       }
5396       return;
5397     }
5398     schemeHistogram.add(type, scheme);
5400     let userInputHistogram = Services.telemetry.getKeyedHistogramById(
5401       "PERMISSION_REQUEST_HANDLING_USER_INPUT"
5402     );
5403     userInputHistogram.add(
5404       type,
5405       request.hasValidTransientUserGestureActivation
5406     );
5407   },
5410 export var DefaultBrowserCheck = {
5411   async prompt(win) {
5412     const shellService = win.getShellService();
5413     const needPin = await shellService.doesAppNeedPin();
5415     win.MozXULElement.insertFTLIfNeeded("branding/brand.ftl");
5416     win.MozXULElement.insertFTLIfNeeded(
5417       "browser/defaultBrowserNotification.ftl"
5418     );
5419     // Resolve the translations for the prompt elements and return only the
5420     // string values
5421     const pinMessage =
5422       AppConstants.platform == "macosx"
5423         ? "default-browser-prompt-message-pin-mac"
5424         : "default-browser-prompt-message-pin";
5425     let [promptTitle, promptMessage, askLabel, yesButton, notNowButton] = (
5426       await win.document.l10n.formatMessages([
5427         {
5428           id: needPin
5429             ? "default-browser-prompt-title-pin"
5430             : "default-browser-prompt-title-alt",
5431         },
5432         {
5433           id: needPin ? pinMessage : "default-browser-prompt-message-alt",
5434         },
5435         { id: "default-browser-prompt-checkbox-not-again-label" },
5436         {
5437           id: needPin
5438             ? "default-browser-prompt-button-primary-pin"
5439             : "default-browser-prompt-button-primary-alt",
5440         },
5441         { id: "default-browser-prompt-button-secondary" },
5442       ])
5443     ).map(({ value }) => value);
5445     let ps = Services.prompt;
5446     let buttonFlags =
5447       ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0 +
5448       ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_1 +
5449       ps.BUTTON_POS_0_DEFAULT;
5450     let rv = await ps.asyncConfirmEx(
5451       win.browsingContext,
5452       ps.MODAL_TYPE_INTERNAL_WINDOW,
5453       promptTitle,
5454       promptMessage,
5455       buttonFlags,
5456       yesButton,
5457       notNowButton,
5458       null,
5459       askLabel,
5460       false, // checkbox state
5461       { headerIconURL: "chrome://branding/content/icon32.png" }
5462     );
5463     let buttonNumClicked = rv.get("buttonNumClicked");
5464     let checkboxState = rv.get("checked");
5465     if (buttonNumClicked == 0) {
5466       try {
5467         await shellService.setAsDefault();
5468       } catch (e) {
5469         this.log.error("Failed to set the default browser", e);
5470       }
5472       shellService.pinToTaskbar();
5473     }
5474     if (checkboxState) {
5475       shellService.shouldCheckDefaultBrowser = false;
5476     }
5478     try {
5479       let resultEnum = buttonNumClicked * 2 + !checkboxState;
5480       Services.telemetry
5481         .getHistogramById("BROWSER_SET_DEFAULT_RESULT")
5482         .add(resultEnum);
5483     } catch (ex) {
5484       /* Don't break if Telemetry is acting up. */
5485     }
5486   },
5488   /**
5489    * Checks if the default browser check prompt will be shown.
5490    * @param {boolean} isStartupCheck
5491    *   If true, prefs will be set and telemetry will be recorded.
5492    * @returns {boolean} True if the default browser check prompt will be shown.
5493    */
5494   async willCheckDefaultBrowser(isStartupCheck) {
5495     let win = lazy.BrowserWindowTracker.getTopWindow();
5496     let shellService = win.getShellService();
5498     // Perform default browser checking.
5499     if (!shellService) {
5500       return false;
5501     }
5503     let shouldCheck =
5504       !AppConstants.DEBUG && shellService.shouldCheckDefaultBrowser;
5506     // Even if we shouldn't check the default browser, we still continue when
5507     // isStartupCheck = true to set prefs and telemetry.
5508     if (!shouldCheck && !isStartupCheck) {
5509       return false;
5510     }
5512     // Skip the "Set Default Browser" check during first-run or after the
5513     // browser has been run a few times.
5514     const skipDefaultBrowserCheck =
5515       Services.prefs.getBoolPref(
5516         "browser.shell.skipDefaultBrowserCheckOnFirstRun"
5517       ) &&
5518       !Services.prefs.getBoolPref(
5519         "browser.shell.didSkipDefaultBrowserCheckOnFirstRun"
5520       );
5522     let promptCount = Services.prefs.getIntPref(
5523       "browser.shell.defaultBrowserCheckCount",
5524       0
5525     );
5527     // If SessionStartup's state is not initialized, checking sessionType will set
5528     // its internal state to "do not restore".
5529     await lazy.SessionStartup.onceInitialized;
5530     let willRecoverSession =
5531       lazy.SessionStartup.sessionType == lazy.SessionStartup.RECOVER_SESSION;
5533     // Don't show the prompt if we're already the default browser.
5534     let isDefault = false;
5535     let isDefaultError = false;
5536     try {
5537       isDefault = shellService.isDefaultBrowser(isStartupCheck, false);
5538     } catch (ex) {
5539       isDefaultError = true;
5540     }
5542     if (isDefault && isStartupCheck) {
5543       let now = Math.floor(Date.now() / 1000).toString();
5544       Services.prefs.setCharPref(
5545         "browser.shell.mostRecentDateSetAsDefault",
5546         now
5547       );
5548     }
5550     let willPrompt = shouldCheck && !isDefault && !willRecoverSession;
5552     if (willPrompt) {
5553       if (skipDefaultBrowserCheck) {
5554         if (isStartupCheck) {
5555           Services.prefs.setBoolPref(
5556             "browser.shell.didSkipDefaultBrowserCheckOnFirstRun",
5557             true
5558           );
5559         }
5560         willPrompt = false;
5561       } else {
5562         promptCount++;
5563         if (isStartupCheck) {
5564           Services.prefs.setIntPref(
5565             "browser.shell.defaultBrowserCheckCount",
5566             promptCount
5567           );
5568         }
5569         if (!AppConstants.RELEASE_OR_BETA && promptCount > 3) {
5570           willPrompt = false;
5571         }
5572       }
5573     }
5575     if (isStartupCheck) {
5576       try {
5577         // Report default browser status on startup to telemetry
5578         // so we can track whether we are the default.
5579         Services.telemetry
5580           .getHistogramById("BROWSER_IS_USER_DEFAULT")
5581           .add(isDefault);
5582         Services.telemetry
5583           .getHistogramById("BROWSER_IS_USER_DEFAULT_ERROR")
5584           .add(isDefaultError);
5585         Services.telemetry
5586           .getHistogramById("BROWSER_SET_DEFAULT_ALWAYS_CHECK")
5587           .add(shouldCheck);
5588         Services.telemetry
5589           .getHistogramById("BROWSER_SET_DEFAULT_DIALOG_PROMPT_RAWCOUNT")
5590           .add(promptCount);
5591       } catch (ex) {
5592         /* Don't break the default prompt if telemetry is broken. */
5593       }
5594     }
5596     return willPrompt;
5597   },
5601  * AboutHomeStartupCache is responsible for reading and writing the
5602  * initial about:home document from the HTTP cache as a startup
5603  * performance optimization. It only works when the "privileged about
5604  * content process" is enabled and when ENABLED_PREF is set to true.
5606  * See https://firefox-source-docs.mozilla.org/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.html
5607  * for further details.
5608  */
5609 export var AboutHomeStartupCache = {
5610   ABOUT_HOME_URI_STRING: "about:home",
5611   SCRIPT_EXTENSION: "script",
5612   ENABLED_PREF: "browser.startup.homepage.abouthome_cache.enabled",
5613   PRELOADED_NEWTAB_PREF: "browser.newtab.preload",
5614   LOG_LEVEL_PREF: "browser.startup.homepage.abouthome_cache.loglevel",
5616   // It's possible that the layout of about:home will change such that
5617   // we want to invalidate any pre-existing caches. We do this by setting
5618   // this meta key in the nsICacheEntry for the page.
5619   //
5620   // The version is currently set to the build ID, meaning that the cache
5621   // is invalidated after every upgrade (like the main startup cache).
5622   CACHE_VERSION_META_KEY: "version",
5624   LOG_NAME: "AboutHomeStartupCache",
5626   // These messages are used to request the "privileged about content process"
5627   // to create the cached document, and then to receive that document.
5628   CACHE_REQUEST_MESSAGE: "AboutHomeStartupCache:CacheRequest",
5629   CACHE_RESPONSE_MESSAGE: "AboutHomeStartupCache:CacheResponse",
5630   CACHE_USAGE_RESULT_MESSAGE: "AboutHomeStartupCache:UsageResult",
5632   // When a "privileged about content process" is launched, this message is
5633   // sent to give it some nsIInputStream's for the about:home document they
5634   // should load.
5635   SEND_STREAMS_MESSAGE: "AboutHomeStartupCache:InputStreams",
5637   // This time in ms is used to debounce messages that are broadcast to
5638   // all about:newtab's, or the preloaded about:newtab. We use those
5639   // messages as a signal that it's likely time to refresh the cache.
5640   CACHE_DEBOUNCE_RATE_MS: 5000,
5642   // This is how long we'll block the AsyncShutdown while waiting for
5643   // the cache to write. If we fail to write within that time, we will
5644   // allow the shutdown to proceed.
5645   SHUTDOWN_CACHE_WRITE_TIMEOUT_MS: 1000,
5647   // The following values are as possible values for the
5648   // browser.startup.abouthome_cache_result scalar. Keep these in sync with the
5649   // scalar definition in Scalars.yaml. See setDeferredResult for more
5650   // information.
5651   CACHE_RESULT_SCALARS: {
5652     UNSET: 0,
5653     DOES_NOT_EXIST: 1,
5654     CORRUPT_PAGE: 2,
5655     CORRUPT_SCRIPT: 3,
5656     INVALIDATED: 4,
5657     LATE: 5,
5658     VALID_AND_USED: 6,
5659     DISABLED: 7,
5660     NOT_LOADING_ABOUTHOME: 8,
5661     PRELOADING_DISABLED: 9,
5662   },
5664   // This will be set to one of the values of CACHE_RESULT_SCALARS
5665   // once it is determined which result best suits what occurred.
5666   _cacheDeferredResultScalar: -1,
5668   // A reference to the nsICacheEntry to read from and write to.
5669   _cacheEntry: null,
5671   // These nsIPipe's are sent down to the "privileged about content process"
5672   // immediately after the process launches. This allows us to race the loading
5673   // of the cache entry in the parent process with the load of the about:home
5674   // page in the content process, since we'll connect the InputStream's to
5675   // the pipes as soon as the nsICacheEntry is available.
5676   //
5677   // The page pipe is for the HTML markup for the page.
5678   _pagePipe: null,
5679   // The script pipe is for the JavaScript that the HTML markup loads
5680   // to set its internal state.
5681   _scriptPipe: null,
5682   _cacheDeferred: null,
5684   _enabled: false,
5685   _initted: false,
5686   _hasWrittenThisSession: false,
5687   _finalized: false,
5688   _firstPrivilegedProcessCreated: false,
5690   init() {
5691     if (this._initted) {
5692       throw new Error("AboutHomeStartupCache already initted.");
5693     }
5695     this.setDeferredResult(this.CACHE_RESULT_SCALARS.UNSET);
5697     this._enabled = !!lazy.NimbusFeatures.abouthomecache.getVariable("enabled");
5699     if (!this._enabled) {
5700       this.recordResult(this.CACHE_RESULT_SCALARS.DISABLED);
5701       return;
5702     }
5704     this.log = console.createInstance({
5705       prefix: this.LOG_NAME,
5706       maxLogLevelPref: this.LOG_LEVEL_PREF,
5707     });
5709     this.log.trace("Initting.");
5711     // If the user is not configured to load about:home at startup, then
5712     // let's not bother with the cache - loading it needlessly is more likely
5713     // to hinder what we're actually trying to load.
5714     let willLoadAboutHome =
5715       !lazy.HomePage.overridden &&
5716       Services.prefs.getIntPref("browser.startup.page") === 1;
5718     if (!willLoadAboutHome) {
5719       this.log.trace("Not configured to load about:home by default.");
5720       this.recordResult(this.CACHE_RESULT_SCALARS.NOT_LOADING_ABOUTHOME);
5721       return;
5722     }
5724     if (!Services.prefs.getBoolPref(this.PRELOADED_NEWTAB_PREF, false)) {
5725       this.log.trace("Preloaded about:newtab disabled.");
5726       this.recordResult(this.CACHE_RESULT_SCALARS.PRELOADING_DISABLED);
5727       return;
5728     }
5730     Services.obs.addObserver(this, "ipc:content-created");
5731     Services.obs.addObserver(this, "process-type-set");
5732     Services.obs.addObserver(this, "ipc:content-shutdown");
5733     Services.obs.addObserver(this, "intl:app-locales-changed");
5735     this.log.trace("Constructing pipes.");
5736     this._pagePipe = this.makePipe();
5737     this._scriptPipe = this.makePipe();
5739     this._cacheEntryPromise = new Promise(resolve => {
5740       this._cacheEntryResolver = resolve;
5741     });
5743     let lci = Services.loadContextInfo.default;
5744     let storage = Services.cache2.diskCacheStorage(lci);
5745     try {
5746       storage.asyncOpenURI(
5747         this.aboutHomeURI,
5748         "",
5749         Ci.nsICacheStorage.OPEN_PRIORITY,
5750         this
5751       );
5752     } catch (e) {
5753       this.log.error("Failed to open about:home cache entry", e);
5754     }
5756     this._cacheTask = new lazy.DeferredTask(async () => {
5757       await this.cacheNow();
5758     }, this.CACHE_DEBOUNCE_RATE_MS);
5760     lazy.AsyncShutdown.quitApplicationGranted.addBlocker(
5761       "AboutHomeStartupCache: Writing cache",
5762       async () => {
5763         await this.onShutdown();
5764       },
5765       () => this._cacheProgress
5766     );
5768     this._cacheDeferred = null;
5769     this._initted = true;
5770     this.log.trace("Initialized.");
5771   },
5773   get initted() {
5774     return this._initted;
5775   },
5777   uninit() {
5778     if (!this._enabled) {
5779       return;
5780     }
5782     try {
5783       Services.obs.removeObserver(this, "ipc:content-created");
5784       Services.obs.removeObserver(this, "process-type-set");
5785       Services.obs.removeObserver(this, "ipc:content-shutdown");
5786       Services.obs.removeObserver(this, "intl:app-locales-changed");
5787     } catch (e) {
5788       // If we failed to initialize and register for these observer
5789       // notifications, then attempting to remove them will throw.
5790       // It's fine to ignore that case on shutdown.
5791     }
5793     if (this._cacheTask) {
5794       this._cacheTask.disarm();
5795       this._cacheTask = null;
5796     }
5798     this._pagePipe = null;
5799     this._scriptPipe = null;
5800     this._initted = false;
5801     this._cacheEntry = null;
5802     this._hasWrittenThisSession = false;
5803     this._cacheEntryPromise = null;
5804     this._cacheEntryResolver = null;
5805     this._cacheDeferredResultScalar = -1;
5807     if (this.log) {
5808       this.log.trace("Uninitialized.");
5809       this.log = null;
5810     }
5812     this._procManager = null;
5813     this._procManagerID = null;
5814     this._appender = null;
5815     this._cacheDeferred = null;
5816     this._finalized = false;
5817     this._firstPrivilegedProcessCreated = false;
5818   },
5820   _aboutHomeURI: null,
5822   get aboutHomeURI() {
5823     if (this._aboutHomeURI) {
5824       return this._aboutHomeURI;
5825     }
5827     this._aboutHomeURI = Services.io.newURI(this.ABOUT_HOME_URI_STRING);
5828     return this._aboutHomeURI;
5829   },
5831   // For the AsyncShutdown blocker, this is used to populate the progress
5832   // value.
5833   _cacheProgress: "Not yet begun",
5835   /**
5836    * Called by the AsyncShutdown blocker on quit-application-granted
5837    * to potentially flush the most recent cache to disk. If one was
5838    * never written during the session, one is generated and written
5839    * before the async function resolves.
5840    *
5841    * @param withTimeout (boolean)
5842    *   Whether or not the timeout mechanism should be used. Defaults
5843    *   to true.
5844    * @returns Promise
5845    * @resolves boolean
5846    *   If a cache has never been written, or a cache write is in
5847    *   progress, resolves true when the cache has been written. Also
5848    *   resolves to true if a cache didn't need to be written.
5849    *
5850    *   Resolves to false if a cache write unexpectedly timed out.
5851    */
5852   async onShutdown(withTimeout = true) {
5853     // If we never wrote this session, arm the task so that the next
5854     // step can finalize.
5855     if (!this._hasWrittenThisSession) {
5856       this.log.trace("Never wrote a cache this session. Arming cache task.");
5857       this._cacheTask.arm();
5858     }
5860     Services.telemetry.scalarSet(
5861       "browser.startup.abouthome_cache_shutdownwrite",
5862       this._cacheTask.isArmed
5863     );
5865     if (this._cacheTask.isArmed) {
5866       this.log.trace("Finalizing cache task on shutdown");
5867       this._finalized = true;
5869       // To avoid hanging shutdowns, we'll ensure that we wait a maximum of
5870       // SHUTDOWN_CACHE_WRITE_TIMEOUT_MS millseconds before giving up.
5871       const TIMED_OUT = Symbol();
5872       let timeoutID = 0;
5874       let timeoutPromise = new Promise(resolve => {
5875         timeoutID = lazy.setTimeout(
5876           () => resolve(TIMED_OUT),
5877           this.SHUTDOWN_CACHE_WRITE_TIMEOUT_MS
5878         );
5879       });
5881       let promises = [this._cacheTask.finalize()];
5882       if (withTimeout) {
5883         this.log.trace("Using timeout mechanism.");
5884         promises.push(timeoutPromise);
5885       } else {
5886         this.log.trace("Skipping timeout mechanism.");
5887       }
5889       let result = await Promise.race(promises);
5890       this.log.trace("Done blocking shutdown.");
5891       lazy.clearTimeout(timeoutID);
5892       if (result === TIMED_OUT) {
5893         this.log.error("Timed out getting cache streams. Skipping cache task.");
5894         return false;
5895       }
5896     }
5897     this.log.trace("onShutdown is exiting");
5898     return true;
5899   },
5901   /**
5902    * Called by the _cacheTask DeferredTask to actually do the work of
5903    * caching the about:home document.
5904    *
5905    * @returns Promise
5906    * @resolves undefined
5907    *   Resolves when a fresh version of the cache has been written.
5908    */
5909   async cacheNow() {
5910     this.log.trace("Caching now.");
5911     this._cacheProgress = "Getting cache streams";
5913     let { pageInputStream, scriptInputStream } = await this.requestCache();
5915     if (!pageInputStream || !scriptInputStream) {
5916       this.log.trace("Failed to get cache streams.");
5917       this._cacheProgress = "Failed to get streams";
5918       return;
5919     }
5921     this.log.trace("Got cache streams.");
5923     this._cacheProgress = "Writing to cache";
5925     try {
5926       this.log.trace("Populating cache.");
5927       await this.populateCache(pageInputStream, scriptInputStream);
5928     } catch (e) {
5929       this._cacheProgress = "Failed to populate cache";
5930       this.log.error("Populating the cache failed: ", e);
5931       return;
5932     }
5934     this._cacheProgress = "Done";
5935     this.log.trace("Done writing to cache.");
5936     this._hasWrittenThisSession = true;
5937   },
5939   /**
5940    * Requests the cached document streams from the "privileged about content
5941    * process".
5942    *
5943    * @returns Promise
5944    * @resolves Object
5945    *   Resolves with an Object with the following properties:
5946    *
5947    *   pageInputStream (nsIInputStream)
5948    *     The page content to write to the cache, or null if request the streams
5949    *     failed.
5950    *
5951    *   scriptInputStream (nsIInputStream)
5952    *     The script content to write to the cache, or null if request the streams
5953    *     failed.
5954    */
5955   requestCache() {
5956     this.log.trace("Parent is requesting Activity Stream state object.");
5957     if (!this._procManager) {
5958       this.log.error("requestCache called with no _procManager!");
5959       return { pageInputStream: null, scriptInputStream: null };
5960     }
5962     if (
5963       this._procManager.remoteType != lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE
5964     ) {
5965       this.log.error("Somehow got the wrong process type.");
5966       return { pageInputStream: null, scriptInputStream: null };
5967     }
5969     let state = lazy.AboutNewTab.activityStream.store.getState();
5970     return new Promise(resolve => {
5971       this._cacheDeferred = resolve;
5972       this.log.trace("Parent is requesting cache streams.");
5973       this._procManager.sendAsyncMessage(this.CACHE_REQUEST_MESSAGE, { state });
5974     });
5975   },
5977   /**
5978    * Helper function that returns a newly constructed nsIPipe instance.
5979    *
5980    * @return nsIPipe
5981    */
5982   makePipe() {
5983     let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
5984     pipe.init(
5985       true /* non-blocking input */,
5986       true /* non-blocking output */,
5987       0 /* segment size */,
5988       0 /* max segments */
5989     );
5990     return pipe;
5991   },
5993   get pagePipe() {
5994     return this._pagePipe;
5995   },
5997   get scriptPipe() {
5998     return this._scriptPipe;
5999   },
6001   /**
6002    * Called when the nsICacheEntry has been accessed. If the nsICacheEntry
6003    * has content that we want to send down to the "privileged about content
6004    * process", then we connect that content to the nsIPipe's that may or
6005    * may not have already been sent down to the process.
6006    *
6007    * In the event that the nsICacheEntry doesn't contain anything usable,
6008    * the nsInputStreams on the nsIPipe's are closed.
6009    */
6010   connectToPipes() {
6011     this.log.trace(`Connecting nsICacheEntry to pipes.`);
6013     // If the cache doesn't yet exist, we'll know because the version metadata
6014     // won't exist yet.
6015     let version;
6016     try {
6017       this.log.trace("");
6018       version = this._cacheEntry.getMetaDataElement(
6019         this.CACHE_VERSION_META_KEY
6020       );
6021     } catch (e) {
6022       if (e.result == Cr.NS_ERROR_NOT_AVAILABLE) {
6023         this.log.debug("Cache meta data does not exist. Closing streams.");
6024         this.pagePipe.outputStream.close();
6025         this.scriptPipe.outputStream.close();
6026         this.setDeferredResult(this.CACHE_RESULT_SCALARS.DOES_NOT_EXIST);
6027         return;
6028       }
6030       throw e;
6031     }
6033     this.log.info("Version retrieved is", version);
6035     if (version != Services.appinfo.appBuildID) {
6036       this.log.info("Version does not match! Dooming and closing streams.\n");
6037       // This cache is no good - doom it, and prepare for a new one.
6038       this.clearCache();
6039       this.pagePipe.outputStream.close();
6040       this.scriptPipe.outputStream.close();
6041       this.setDeferredResult(this.CACHE_RESULT_SCALARS.INVALIDATED);
6042       return;
6043     }
6045     let cachePageInputStream;
6047     try {
6048       cachePageInputStream = this._cacheEntry.openInputStream(0);
6049     } catch (e) {
6050       this.log.error("Failed to open main input stream for cache entry", e);
6051       this.pagePipe.outputStream.close();
6052       this.scriptPipe.outputStream.close();
6053       this.setDeferredResult(this.CACHE_RESULT_SCALARS.CORRUPT_PAGE);
6054       return;
6055     }
6057     this.log.trace("Connecting page stream to pipe.");
6058     lazy.NetUtil.asyncCopy(
6059       cachePageInputStream,
6060       this.pagePipe.outputStream,
6061       () => {
6062         this.log.info("Page stream connected to pipe.");
6063       }
6064     );
6066     let cacheScriptInputStream;
6067     try {
6068       this.log.trace("Connecting script stream to pipe.");
6069       cacheScriptInputStream =
6070         this._cacheEntry.openAlternativeInputStream("script");
6071       lazy.NetUtil.asyncCopy(
6072         cacheScriptInputStream,
6073         this.scriptPipe.outputStream,
6074         () => {
6075           this.log.info("Script stream connected to pipe.");
6076         }
6077       );
6078     } catch (e) {
6079       if (e.result == Cr.NS_ERROR_NOT_AVAILABLE) {
6080         // For some reason, the script was not available. We'll close the pipe
6081         // without sending anything into it. The privileged about content process
6082         // will notice that there's nothing available in the pipe, and fall back
6083         // to dynamically generating the page.
6084         this.log.error("Script stream not available! Closing pipe.");
6085         this.scriptPipe.outputStream.close();
6086         this.setDeferredResult(this.CACHE_RESULT_SCALARS.CORRUPT_SCRIPT);
6087       } else {
6088         throw e;
6089       }
6090     }
6092     this.setDeferredResult(this.CACHE_RESULT_SCALARS.VALID_AND_USED);
6093     this.log.trace("Streams connected to pipes.");
6094   },
6096   /**
6097    * Called when we have received a the cache values from the "privileged
6098    * about content process". The page and script streams are written to
6099    * the nsICacheEntry.
6100    *
6101    * This writing is asynchronous, and if a write happens to already be
6102    * underway when this function is called, that latter call will be
6103    * ignored.
6104    *
6105    * @param pageInputStream (nsIInputStream)
6106    *   A stream containing the HTML markup to be saved to the cache.
6107    * @param scriptInputStream (nsIInputStream)
6108    *   A stream containing the JS hydration script to be saved to the cache.
6109    * @returns Promise
6110    * @resolves undefined
6111    *   When the cache has been successfully written to.
6112    * @rejects Error
6113    *   Rejects with a JS Error if writing any part of the cache happens to
6114    *   fail.
6115    */
6116   async populateCache(pageInputStream, scriptInputStream) {
6117     await this.ensureCacheEntry();
6119     await new Promise((resolve, reject) => {
6120       // Doom the old cache entry, so we can start writing to a new one.
6121       this.log.trace("Populating the cache. Dooming old entry.");
6122       this.clearCache();
6124       this.log.trace("Opening the page output stream.");
6125       let pageOutputStream;
6126       try {
6127         pageOutputStream = this._cacheEntry.openOutputStream(0, -1);
6128       } catch (e) {
6129         reject(e);
6130         return;
6131       }
6133       this.log.info("Writing the page cache.");
6134       lazy.NetUtil.asyncCopy(pageInputStream, pageOutputStream, pageResult => {
6135         if (!Components.isSuccessCode(pageResult)) {
6136           this.log.error("Failed to write page. Result: " + pageResult);
6137           reject(new Error(pageResult));
6138           return;
6139         }
6141         this.log.trace(
6142           "Writing the page data is complete. Now opening the " +
6143             "script output stream."
6144         );
6146         let scriptOutputStream;
6147         try {
6148           scriptOutputStream = this._cacheEntry.openAlternativeOutputStream(
6149             "script",
6150             -1
6151           );
6152         } catch (e) {
6153           reject(e);
6154           return;
6155         }
6157         this.log.info("Writing the script cache.");
6158         lazy.NetUtil.asyncCopy(
6159           scriptInputStream,
6160           scriptOutputStream,
6161           scriptResult => {
6162             if (!Components.isSuccessCode(scriptResult)) {
6163               this.log.error("Failed to write script. Result: " + scriptResult);
6164               reject(new Error(scriptResult));
6165               return;
6166             }
6168             this.log.trace(
6169               "Writing the script cache is done. Setting version."
6170             );
6171             try {
6172               this._cacheEntry.setMetaDataElement(
6173                 "version",
6174                 Services.appinfo.appBuildID
6175               );
6176             } catch (e) {
6177               this.log.error("Failed to write version.");
6178               reject(e);
6179               return;
6180             }
6181             this.log.trace(`Version is set to ${Services.appinfo.appBuildID}.`);
6182             this.log.info("Caching of page and script is done.");
6183             resolve();
6184           }
6185         );
6186       });
6187     });
6189     this.log.trace("populateCache has finished.");
6190   },
6192   /**
6193    * Returns a Promise that resolves once the nsICacheEntry for the cache
6194    * is available to write to and read from.
6195    *
6196    * @returns Promise
6197    * @resolves nsICacheEntry
6198    *   Once the cache entry has become available.
6199    * @rejects String
6200    *   Rejects with an error message if getting the cache entry is attempted
6201    *   before the AboutHomeStartupCache component has been initialized.
6202    */
6203   ensureCacheEntry() {
6204     if (!this._initted) {
6205       return Promise.reject(
6206         "Cannot ensureCacheEntry - AboutHomeStartupCache is not initted"
6207       );
6208     }
6210     return this._cacheEntryPromise;
6211   },
6213   /**
6214    * Clears the contents of the cache.
6215    */
6216   clearCache() {
6217     this.log.trace("Clearing the cache.");
6218     this._cacheEntry = this._cacheEntry.recreate();
6219     this._cacheEntryPromise = new Promise(resolve => {
6220       resolve(this._cacheEntry);
6221     });
6222     this._hasWrittenThisSession = false;
6223   },
6225   /**
6226    * Called when a content process is created. If this is the "privileged
6227    * about content process", then the cache streams will be sent to it.
6228    *
6229    * @param childID (Number)
6230    *   The unique ID for the content process that was created, as passed by
6231    *   ipc:content-created.
6232    * @param procManager (ProcessMessageManager)
6233    *   The ProcessMessageManager for the created content process.
6234    * @param processParent
6235    *   The nsIDOMProcessParent for the tab.
6236    */
6237   onContentProcessCreated(childID, procManager, processParent) {
6238     if (procManager.remoteType == lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE) {
6239       if (this._finalized) {
6240         this.log.trace(
6241           "Ignoring privileged about content process launch after finalization."
6242         );
6243         return;
6244       }
6246       if (this._firstPrivilegedProcessCreated) {
6247         this.log.trace(
6248           "Ignoring non-first privileged about content processes."
6249         );
6250         return;
6251       }
6253       this.log.trace(
6254         `A privileged about content process is launching with ID ${childID}.`
6255       );
6257       this.log.info("Sending input streams down to content process.");
6258       let actor = processParent.getActor("BrowserProcess");
6259       actor.sendAsyncMessage(this.SEND_STREAMS_MESSAGE, {
6260         pageInputStream: this.pagePipe.inputStream,
6261         scriptInputStream: this.scriptPipe.inputStream,
6262       });
6264       procManager.addMessageListener(this.CACHE_RESPONSE_MESSAGE, this);
6265       procManager.addMessageListener(this.CACHE_USAGE_RESULT_MESSAGE, this);
6266       this._procManager = procManager;
6267       this._procManagerID = childID;
6268       this._firstPrivilegedProcessCreated = true;
6269     }
6270   },
6272   /**
6273    * Called when a content process is destroyed. Either it shut down normally,
6274    * or it crashed. If this is the "privileged about content process", then some
6275    * internal state is cleared.
6276    *
6277    * @param childID (Number)
6278    *   The unique ID for the content process that was created, as passed by
6279    *   ipc:content-shutdown.
6280    */
6281   onContentProcessShutdown(childID) {
6282     this.log.info(`Content process shutdown: ${childID}`);
6283     if (this._procManagerID == childID) {
6284       this.log.info("It was the current privileged about process.");
6285       if (this._cacheDeferred) {
6286         this.log.error(
6287           "A privileged about content process shut down while cache streams " +
6288             "were still en route."
6289         );
6290         // The crash occurred while we were waiting on cache input streams to
6291         // be returned to us. Resolve with null streams instead.
6292         this._cacheDeferred({ pageInputStream: null, scriptInputStream: null });
6293         this._cacheDeferred = null;
6294       }
6296       this._procManager.removeMessageListener(
6297         this.CACHE_RESPONSE_MESSAGE,
6298         this
6299       );
6300       this._procManager.removeMessageListener(
6301         this.CACHE_USAGE_RESULT_MESSAGE,
6302         this
6303       );
6304       this._procManager = null;
6305       this._procManagerID = null;
6306     }
6307   },
6309   /**
6310    * Called externally by ActivityStreamMessageChannel anytime
6311    * a message is broadcast to all about:newtabs, or sent to the
6312    * preloaded about:newtab. This is used to determine if we need
6313    * to refresh the cache.
6314    */
6315   onPreloadedNewTabMessage() {
6316     if (!this._initted || !this._enabled) {
6317       return;
6318     }
6320     if (this._finalized) {
6321       this.log.trace("Ignoring preloaded newtab update after finalization.");
6322       return;
6323     }
6325     this.log.trace("Preloaded about:newtab was updated.");
6327     this._cacheTask.disarm();
6328     this._cacheTask.arm();
6329   },
6331   /**
6332    * Stores the CACHE_RESULT_SCALARS value that most accurately represents
6333    * the current notion of how the cache has operated so far. It is stored
6334    * temporarily like this because we need to hear from the privileged
6335    * about content process to hear whether or not retrieving the cache
6336    * actually worked on that end. The success state reported back from
6337    * the privileged about content process will be compared against the
6338    * deferred result scalar to compute what will be recorded to
6339    * Telemetry.
6340    *
6341    * Note that this value will only be recorded if its value is GREATER
6342    * than the currently recorded value. This is because it's possible for
6343    * certain functions that record results to re-enter - but we want to record
6344    * the _first_ condition that caused the cache to not be read from.
6345    *
6346    * @param result (Number)
6347    *   One of the CACHE_RESULT_SCALARS values. If this value is less than
6348    *   the currently recorded value, it is ignored.
6349    */
6350   setDeferredResult(result) {
6351     if (this._cacheDeferredResultScalar < result) {
6352       this._cacheDeferredResultScalar = result;
6353     }
6354   },
6356   /**
6357    * Records the final result of how the cache operated for the user
6358    * during this session to Telemetry.
6359    */
6360   recordResult(result) {
6361     // Note: this can be called very early on in the lifetime of
6362     // AboutHomeStartupCache, so things like this.log might not exist yet.
6363     Services.telemetry.scalarSet(
6364       "browser.startup.abouthome_cache_result",
6365       result
6366     );
6367   },
6369   /**
6370    * Called when the parent process receives a message from the privileged
6371    * about content process saying whether or not reading from the cache
6372    * was successful.
6373    *
6374    * @param success (boolean)
6375    *   True if reading from the cache succeeded.
6376    */
6377   onUsageResult(success) {
6378     this.log.trace(`Received usage result. Success = ${success}`);
6379     if (success) {
6380       if (
6381         this._cacheDeferredResultScalar !=
6382         this.CACHE_RESULT_SCALARS.VALID_AND_USED
6383       ) {
6384         this.log.error(
6385           "Somehow got a success result despite having never " +
6386             "successfully sent down the cache streams"
6387         );
6388         this.recordResult(this._cacheDeferredResultScalar);
6389       } else {
6390         this.recordResult(this.CACHE_RESULT_SCALARS.VALID_AND_USED);
6391       }
6393       return;
6394     }
6396     if (
6397       this._cacheDeferredResultScalar ==
6398       this.CACHE_RESULT_SCALARS.VALID_AND_USED
6399     ) {
6400       // We failed to read from the cache despite having successfully
6401       // sent it down to the content process. We presume then that the
6402       // streams just didn't provide any bytes in time.
6403       this.recordResult(this.CACHE_RESULT_SCALARS.LATE);
6404     } else {
6405       // We failed to read the cache, but already knew why. We can
6406       // now record that value.
6407       this.recordResult(this._cacheDeferredResultScalar);
6408     }
6409   },
6411   QueryInterface: ChromeUtils.generateQI([
6412     "nsICacheEntryOpenallback",
6413     "nsIObserver",
6414   ]),
6416   /** MessageListener **/
6418   receiveMessage(message) {
6419     // Only the privileged about content process can write to the cache.
6420     if (
6421       message.target.remoteType != lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE
6422     ) {
6423       this.log.error(
6424         "Received a message from a non-privileged content process!"
6425       );
6426       return;
6427     }
6429     switch (message.name) {
6430       case this.CACHE_RESPONSE_MESSAGE: {
6431         this.log.trace("Parent received cache streams.");
6432         if (!this._cacheDeferred) {
6433           this.log.error("Parent doesn't have _cacheDeferred set up!");
6434           return;
6435         }
6437         this._cacheDeferred(message.data);
6438         this._cacheDeferred = null;
6439         break;
6440       }
6441       case this.CACHE_USAGE_RESULT_MESSAGE: {
6442         this.onUsageResult(message.data.success);
6443         break;
6444       }
6445     }
6446   },
6448   /** nsIObserver **/
6450   observe(aSubject, aTopic, aData) {
6451     switch (aTopic) {
6452       case "intl:app-locales-changed": {
6453         this.clearCache();
6454         break;
6455       }
6456       case "process-type-set":
6457       // Intentional fall-through
6458       case "ipc:content-created": {
6459         let childID = aData;
6460         let procManager = aSubject
6461           .QueryInterface(Ci.nsIInterfaceRequestor)
6462           .getInterface(Ci.nsIMessageSender);
6463         let pp = aSubject.QueryInterface(Ci.nsIDOMProcessParent);
6464         this.onContentProcessCreated(childID, procManager, pp);
6465         break;
6466       }
6468       case "ipc:content-shutdown": {
6469         let childID = aData;
6470         this.onContentProcessShutdown(childID);
6471         break;
6472       }
6473     }
6474   },
6476   /** nsICacheEntryOpenCallback **/
6478   onCacheEntryCheck() {
6479     return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED;
6480   },
6482   onCacheEntryAvailable(aEntry) {
6483     this.log.trace("Cache entry is available.");
6485     this._cacheEntry = aEntry;
6486     this.connectToPipes();
6487     this._cacheEntryResolver(this._cacheEntry);
6488   },