Source code

Revision control

Other Tools

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var EXPORTED_SYMBOLS = [
"AboutHomeStartupCache",
"BrowserGlue",
"ContentPermissionPrompt",
"DefaultBrowserCheck",
];
const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
);
XPCOMUtils.defineLazyModuleGetters(this, {
ASRouterDefaultConfig:
ContextualIdentityService:
DownloadsViewableInternally:
RemoteSecuritySettings:
});
// eslint-disable-next-line no-unused-vars
XPCOMUtils.defineLazyModuleGetters(this, {
});
// Modules requiring an initialization method call.
let initializedModules = {};
[
[
"ContentPrefServiceParent",
"alwaysInit",
],
["UpdateListener", "resource://gre/modules/UpdateListener.jsm", "init"],
].forEach(([name, resource, init]) => {
XPCOMUtils.defineLazyGetter(this, name, () => {
ChromeUtils.import(resource, initializedModules);
initializedModules[name][init]();
return initializedModules[name];
});
});
XPCOMUtils.defineLazyServiceGetter(
this,
"PushService",
"@mozilla.org/push/Service;1",
"nsIPushService"
);
const PREF_PDFJS_ISDEFAULT_CACHE_STATE = "pdfjs.enabledCache.state";
/**
* Fission-compatible JSProcess implementations.
* Each actor options object takes the form of a ProcessActorOptions dictionary.
* Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
*/
let JSPROCESSACTORS = {
// Miscellaneous stuff that needs to be initialized per process.
BrowserProcess: {
child: {
observers: [
// WebRTC related notifications. They are here to avoid loading WebRTC
// components when not needed.
"getUserMedia:request",
"recording-device-stopped",
"PeerConnection:request",
"recording-device-events",
"recording-window-ended",
],
},
},
RefreshBlockerObserver: {
child: {
observers: [
"webnavigation-create",
"chrome-webnavigation-create",
"webnavigation-destroy",
"chrome-webnavigation-destroy",
],
},
enablePreference: "accessibility.blockautorefresh",
onPreferenceChanged: (prefName, prevValue, isEnabled) => {
BrowserWindowTracker.orderedWindows.forEach(win => {
for (let browser of win.gBrowser.browsers) {
try {
browser.sendMessageToActor(
"PreferenceChanged",
{ isEnabled },
"RefreshBlocker",
"all"
);
} catch (ex) {}
}
});
},
},
};
/**
* Fission-compatible JSWindowActor implementations.
* Detailed documentation of these options is in dom/docs/ipc/jsactors.rst,
*/
let JSWINDOWACTORS = {
AboutLogins: {
},
child: {
events: {
AboutLoginsCopyLoginDetail: { wantUntrusted: true },
AboutLoginsCreateLogin: { wantUntrusted: true },
AboutLoginsDeleteLogin: { wantUntrusted: true },
AboutLoginsDismissBreachAlert: { wantUntrusted: true },
AboutLoginsImportFromBrowser: { wantUntrusted: true },
AboutLoginsImportFromFile: { wantUntrusted: true },
AboutLoginsImportReportInit: { wantUntrusted: true },
AboutLoginsImportReportReady: { wantUntrusted: true },
AboutLoginsInit: { wantUntrusted: true },
AboutLoginsGetHelp: { wantUntrusted: true },
AboutLoginsOpenPreferences: { wantUntrusted: true },
AboutLoginsOpenSite: { wantUntrusted: true },
AboutLoginsRecordTelemetryEvent: { wantUntrusted: true },
AboutLoginsRemoveAllLogins: { wantUntrusted: true },
AboutLoginsSortChanged: { wantUntrusted: true },
AboutLoginsSyncEnable: { wantUntrusted: true },
AboutLoginsSyncOptions: { wantUntrusted: true },
AboutLoginsUpdateLogin: { wantUntrusted: true },
AboutLoginsExportPasswords: { wantUntrusted: true },
},
},
matches: ["about:logins", "about:logins?*", "about:loginsimportreport"],
},
AboutNewInstall: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:newinstall"],
},
AboutNewTab: {
},
child: {
events: {
DOMContentLoaded: {},
pageshow: {},
visibilitychange: {},
},
},
// The wildcard on about:newtab is for the ?endpoint query parameter
// that is used for snippets debugging. The wildcard for about:home
// is similar, and also allows for falling back to loading the
// about:home document dynamically if an attempt is made to load
// about:home?jscache from the AboutHomeStartupCache as a top-level
// load.
matches: ["about:home*", "about:welcome", "about:newtab*"],
remoteTypes: ["privilegedabout"],
},
AboutPlugins: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:plugins"],
},
AboutPocket: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:pocket-saved*", "about:pocket-signup*"],
},
AboutPrivateBrowsing: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:privatebrowsing"],
},
AboutProtections: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:protections", "about:protections?*"],
},
AboutReader: {
},
child: {
events: {
DOMContentLoaded: {},
pageshow: { mozSystemGroup: true },
pagehide: { mozSystemGroup: true },
},
},
messageManagerGroups: ["browsers"],
},
AboutTabCrashed: {
},
child: {
events: {
DOMWindowCreated: { capture: true },
},
},
matches: ["about:tabcrashed*"],
},
AboutWelcome: {
},
child: {
events: {
// This is added so the actor instantiates immediately and makes
// methods available to the page js on load.
DOMWindowCreated: {},
},
},
matches: ["about:welcome"],
remoteTypes: ["privilegedabout"],
// See Bug 1618306
// Remove this preference check when we turn on separate about:welcome for all users.
enablePreference: "browser.aboutwelcome.enabled",
},
BlockedSite: {
},
child: {
events: {
AboutBlockedLoaded: { wantUntrusted: true },
click: {},
},
},
matches: ["about:blocked?*"],
allFrames: true,
},
BrowserTab: {
parent: {
},
child: {
events: {
DOMWindowCreated: {},
MozAfterPaint: {},
},
},
messageManagerGroups: ["browsers"],
},
ClickHandler: {
},
child: {
events: {
click: { capture: true, mozSystemGroup: true },
auxclick: { capture: true, mozSystemGroup: true },
},
},
allFrames: true,
},
// Collects description and icon information from meta tags.
ContentMeta: {
},
child: {
events: {
DOMMetaAdded: {},
},
},
},
ContentSearch: {
},
child: {
events: {
ContentSearchClient: { capture: true, wantUntrusted: true },
},
},
matches: [
"about:home",
"about:welcome",
"about:newtab",
"about:privatebrowsing",
"about:test-about-content-search-ui",
],
remoteTypes: ["privilegedabout"],
},
ContextMenu: {
},
child: {
events: {
contextmenu: { mozSystemGroup: true },
},
},
allFrames: true,
},
DecoderDoctor: {
},
child: {
observers: ["decoder-doctor-notification"],
},
messageManagerGroups: ["browsers"],
allFrames: true,
},
DOMFullscreen: {
},
child: {
group: "browsers",
events: {
"MozDOMFullscreen:Request": {},
"MozDOMFullscreen:Entered": {},
"MozDOMFullscreen:NewOrigin": {},
"MozDOMFullscreen:Exit": {},
"MozDOMFullscreen:Exited": {},
},
},
allFrames: true,
},
EncryptedMedia: {
},
child: {
observers: ["mediakeys-request"],
},
messageManagerGroups: ["browsers"],
allFrames: true,
},
FormValidation: {
},
child: {
events: {
MozInvalidForm: {},
},
},
allFrames: true,
},
LightweightTheme: {
child: {
events: {
pageshow: { mozSystemGroup: true },
},
},
includeChrome: true,
allFrames: true,
matches: [
"about:home",
"about:newtab",
"about:welcome",
],
},
LinkHandler: {
},
child: {
events: {
DOMHeadElementParsed: {},
DOMLinkAdded: {},
DOMLinkChanged: {},
pageshow: {},
pagehide: {},
},
},
},
NetError: {
parent: {
},
child: {
events: {
DOMWindowCreated: {},
click: {},
},
},
matches: ["about:certerror?*", "about:neterror?*"],
allFrames: true,
},
PageInfo: {
child: {
},
allFrames: true,
},
PageStyle: {
parent: {
},
child: {
events: {
pageshow: {},
},
},
// Only matching web pages, as opposed to internal about:, chrome: or
matches: ["*://*/*", "file:///*"],
messageManagerGroups: ["browsers"],
allFrames: true,
},
Pdfjs: {
parent: {
},
child: {
},
allFrames: true,
},
Plugin: {
parent: {
},
child: {
events: {
PluginBindingAttached: { capture: true, wantUntrusted: true },
PluginCrashed: { capture: true },
PluginOutdated: { capture: true },
PluginInstantiated: { capture: true },
PluginRemoved: { capture: true },
HiddenPlugin: { capture: true },
},
observers: ["decoder-doctor-notification"],
},
allFrames: true,
},
PointerLock: {
},
child: {
events: {
"MozDOMPointerLock:Entered": {},
"MozDOMPointerLock:Exited": {},
},
},
messageManagerGroups: ["browsers"],
allFrames: true,
},
Prompt: {
parent: {
},
includeChrome: true,
allFrames: true,
},
RefreshBlocker: {
},
},
messageManagerGroups: ["browsers"],
enablePreference: "accessibility.blockautorefresh",
},
SearchSERPTelemetry: {
},
child: {
events: {
DOMContentLoaded: {},
pageshow: { mozSystemGroup: true },
unload: {},
},
},
},
ShieldFrame: {
},
child: {
events: {
pageshow: {},
pagehide: {},
ShieldPageEvent: { wantUntrusted: true },
},
},
matches: ["about:studies"],
},
ASRouter: {
parent: {
},
child: {
events: {
// This is added so the actor instantiates immediately and makes
// methods available to the page js on load.
DOMWindowCreated: {},
},
},
matches: ["about:home*", "about:newtab*", "about:welcome*"],
remoteTypes: ["privilegedabout"],
},
SwitchDocumentDirection: {
},
allFrames: true,
},
Translation: {
},
child: {
events: {
pageshow: {},
load: { mozSystemGroup: true, capture: true },
},
},
enablePreference: "browser.translation.detectLanguage",
},
UITour: {
parent: {
},
child: {
events: {
mozUITour: { wantUntrusted: true },
},
},
},
WebRTC: {
parent: {
},
child: {
},
allFrames: true,
},
};
(function earlyBlankFirstPaint() {
let startTime = Cu.now();
if (
AppConstants.platform == "macosx" ||
!Services.prefs.getBoolPref("browser.startup.blankWindow", false)
) {
return;
}
// Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
// using a non-default theme.
if (
Services.prefs.getCharPref(
"extensions.activeThemeID",
"default-theme@mozilla.org"
) != "default-theme@mozilla.org"
) {
return;
}
let store = Services.xulStore;
let getValue = attr =>
store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
let width = getValue("width");
let height = getValue("height");
// The clean profile case isn't handled yet. Return early for now.
if (!width || !height) {
return;
}
let browserWindowFeatures =
"chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
"location,toolbar,personalbar";
let win = Services.ww.openWindow(
null,
"about:blank",
null,
browserWindowFeatures,
null
);
// Hide the titlebar if the actual browser window will draw in it.
let hiddenTitlebar = Services.prefs.getBoolPref(
"browser.tabs.drawInTitlebar",
win.matchMedia("(-moz-gtk-csd-hide-titlebar-by-default)").matches
);
if (hiddenTitlebar) {
win.windowUtils.setChromeMargin(0, 2, 2, 2);
}
let docElt = win.document.documentElement;
docElt.setAttribute("screenX", getValue("screenX"));
docElt.setAttribute("screenY", getValue("screenY"));
// The sizemode="maximized" attribute needs to be set before first paint.
let sizemode = getValue("sizemode");
if (sizemode == "maximized") {
docElt.setAttribute("sizemode", sizemode);
// Set the size to use when the user leaves the maximized mode.
// The persisted size is the outer size, but the height/width
// attributes set the inner size.
let appWin = win.docShell.treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIAppWindow);
height -= appWin.outerToInnerHeightDifferenceInCSSPixels;
width -= appWin.outerToInnerWidthDifferenceInCSSPixels;
docElt.setAttribute("height", height);
docElt.setAttribute("width", width);
} else {
// Setting the size of the window in the features string instead of here
// causes the window to grow by the size of the titlebar.
win.resizeTo(width, height);
}
// Set this before showing the window so that graphics code can use it to
// decide to skip some expensive code paths (eg. starting the GPU process).
docElt.setAttribute("windowtype", "navigator:blank");
// The window becomes visible after OnStopRequest, so make this happen now.
win.stop();
ChromeUtils.addProfilerMarker("earlyBlankFirstPaint", startTime);
win.openTime = Cu.now();
let { TelemetryTimestamps } = ChromeUtils.import(
);
TelemetryTimestamps.add("blankWindowShown");
})();
XPCOMUtils.defineLazyGetter(
this,
"WeaveService",
() => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
);
if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyModuleGetters(this, {
UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
});
}
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
return Services.strings.createBundle(
);
});
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
return Services.strings.createBundle(
);
});
XPCOMUtils.defineLazyGetter(this, "gTabbrowserBundle", function() {
return Services.strings.createBundle(
);
});
const global = this;
const listeners = {
observers: {
"update-downloading": ["UpdateListener"],
"update-staged": ["UpdateListener"],
"update-downloaded": ["UpdateListener"],
"update-available": ["UpdateListener"],
"update-error": ["UpdateListener"],
"update-swap": ["UpdateListener"],
"gmp-plugin-crash": ["PluginManager"],
"plugin-crashed": ["PluginManager"],
},
observe(subject, topic, data) {
for (let module of this.observers[topic]) {
try {
global[module].observe(subject, topic, data);
} catch (e) {
Cu.reportError(e);
}
}
},
init() {
for (let observer of Object.keys(this.observers)) {
Services.obs.addObserver(this, observer);
}
},
};
// Seconds of idle before trying to create a bookmarks backup.
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
// Minimum interval between backups. We try to not create more than one backup
// per interval.
const BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS = 1;
// Maximum interval between backups. If the last backup is older than these
// days we will try to create a new one more aggressively.
const BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS = 3;
// Seconds of idle time before the late idle tasks will be scheduled.
const LATE_TASKS_IDLE_TIME_SEC = 20;
// Time after we stop tracking startup crashes.
const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
/*
* OS X has the concept of zero-window sessions and therefore ignores the
* browser-lastwindow-close-* topics.
*/
const OBSERVE_LASTWINDOW_CLOSE_TOPICS = AppConstants.platform != "macosx";
function BrowserGlue() {
XPCOMUtils.defineLazyServiceGetter(
this,
"_userIdleService",
"@mozilla.org/widget/useridleservice;1",
"nsIUserIdleService"
);
XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
const { DistributionCustomizer } = ChromeUtils.import(
);
return new DistributionCustomizer();
});
XPCOMUtils.defineLazyServiceGetter(
this,
"AlertsService",
"@mozilla.org/alerts-service;1",
"nsIAlertsService"
);
this._init();
}
BrowserGlue.prototype = {
_saveSession: false,
_migrationImportsDefaultBookmarks: false,
_placesBrowserInitComplete: false,
_isNewProfile: undefined,
_setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
if (!this._saveSession && !aForce) {
return;
}
if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
Services.prefs.setBoolPref(
"browser.sessionstore.resume_session_once",
true
);
}
// This method can be called via [NSApplication terminate:] on Mac, which
// ends up causing prefs not to be flushed to disk, so we need to do that
// explicitly here. See bug 497652.
Services.prefs.savePrefFile(null);
},
_setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
// Assume that a non-zero value for services.sync.autoconnectDelay should override
if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
let prefDelay = Services.prefs.getIntPref(
"services.sync.autoconnectDelay"
);
if (prefDelay > 0) {
return;
}
}
// delays are in seconds
const MAX_DELAY = 300;
let delay = 3;
for (let win of Services.wm.getEnumerator("navigator:browser")) {
// browser windows without a gBrowser almost certainly means we are
// shutting down, so instead of just ignoring that window we abort.
if (win.closed || !win.gBrowser) {
return;
}
delay += win.gBrowser.tabs.length;
}
delay = delay <= MAX_DELAY ? delay : MAX_DELAY;
const { Weave } = ChromeUtils.import("resource://services-sync/main.js");
Weave.Service.scheduler.delayedAutoConnect(delay);
},
// nsIObserver implementation
observe: async function BG_observe(subject, topic, data) {
switch (topic) {
case "notifications-open-settings":
this._openPreferences("privacy-permissions");
break;
case "final-ui-startup":
this._beforeUIStartup();
break;
case "browser-delayed-startup-finished":
this._onFirstWindowLoaded(subject);
Services.obs.removeObserver(this, "browser-delayed-startup-finished");
break;
case "sessionstore-windows-restored":
this._onWindowsRestored();
break;
case "browser:purge-session-history":
// reset the console service's error buffer
Services.console.logStringMessage(null); // clear the console (in case it's open)
Services.console.reset();
break;
case "restart-in-safe-mode":
this._onSafeModeRestart();
break;
case "quit-application-requested":
this._onQuitRequest(subject, data);
break;
case "quit-application-granted":
this._onQuitApplicationGranted();
break;
case "browser-lastwindow-close-requested":
if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
// The application is not actually quitting, but the last full browser
// window is about to be closed.
this._onQuitRequest(subject, "lastwindow");
}
break;
case "browser-lastwindow-close-granted":
if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
this._setPrefToSaveSession();
}
break;
case "weave:service:ready":
this._setSyncAutoconnectDelay();
break;
case "fxaccounts:onverified":
this._onThisDeviceConnected();
break;
case "fxaccounts:device_connected":
this._onDeviceConnected(data);
break;
case "fxaccounts:verify_login":
this._onVerifyLoginNotification(JSON.parse(data));
break;
case "fxaccounts:device_disconnected":
data = JSON.parse(data);
if (data.isLocalDevice) {
this._onDeviceDisconnected();
}
break;
case "fxaccounts:commands:open-uri":
case "weave:engine:clients:display-uris":
this._onDisplaySyncURIs(subject);
break;
case "session-save":
this._setPrefToSaveSession(true);
subject.QueryInterface(Ci.nsISupportsPRBool);
subject.data = true;
break;
case "places-init-complete":
Services.obs.removeObserver(this, "places-init-complete");
if (!this._migrationImportsDefaultBookmarks) {
this._initPlaces(false);
}
break;
case "idle":
this._backupBookmarks();
break;
case "distribution-customization-complete":
Services.obs.removeObserver(
this,
"distribution-customization-complete"
);
// Customization has finished, we don't need the customizer anymore.
delete this._distributionCustomizer;
break;
case "browser-glue-test": // used by tests
if (data == "force-ui-migration") {
this._migrateUI();
} else if (data == "force-distribution-customization") {
this._distributionCustomizer.applyCustomizations();
// To apply distribution bookmarks use "places-init-complete".
} else if (data == "force-places-init") {
this._initPlaces(false);
} else if (data == "mock-alerts-service") {
Object.defineProperty(this, "AlertsService", {
value: subject.wrappedJSObject,
});
} else if (data == "places-browser-init-complete") {
if (this._placesBrowserInitComplete) {
Services.obs.notifyObservers(null, "places-browser-init-complete");
}
} else if (data == "add-breaches-sync-handler") {
this._addBreachesSyncHandler();
}
break;
case "initial-migration-will-import-default-bookmarks":
this._migrationImportsDefaultBookmarks = true;
break;
case "initial-migration-did-import-default-bookmarks":
this._initPlaces(true);
break;
case "handle-xul-text-link":
let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
if (!linkHandled.data) {
let win = BrowserWindowTracker.getTopWindow();
if (win) {
data = JSON.parse(data);
let where = win.whereToOpenLink(data);
// Preserve legacy behavior of non-modifier left-clicks
// opening in a new selected tab.
if (where == "current") {
where = "tab";
}
win.openTrustedLinkIn(data.href, where);
linkHandled.data = true;
}
}
break;
case "profile-before-change":
// Any component depending on Places should be finalized in
// _onPlacesShutdown. Any component that doesn't need to act after
// the UI has gone should be finalized in _onQuitApplicationGranted.
this._dispose();
break;
case "keyword-search":
// This notification is broadcast by the docshell when it "fixes up" a
// URI that it's been asked to load into a keyword search.
let engine = null;
try {
engine = subject.QueryInterface(Ci.nsISearchEngine);
} catch (ex) {
Cu.reportError(ex);
}
let win = BrowserWindowTracker.getTopWindow();
BrowserSearchTelemetry.recordSearch(
win.gBrowser.selectedBrowser,
engine,
"urlbar"
);
break;
case "browser-search-engine-modified":
// Ensure we cleanup the hiddenOneOffs pref when removing
// an engine, and that newly added engines are visible.
if (data == "engine-added" || data == "engine-removed") {
let engineName = subject.QueryInterface(Ci.nsISearchEngine).name;
let pref = Services.prefs.getStringPref(
"browser.search.hiddenOneOffs"
);
let hiddenList = pref ? pref.split(",") : [];
hiddenList = hiddenList.filter(x => x !== engineName);
Services.prefs.setStringPref(
"browser.search.hiddenOneOffs",
hiddenList.join(",")
);
}
break;
case "flash-plugin-hang":
this._handleFlashHang();
break;
case "xpi-signature-changed":
let disabledAddons = JSON.parse(data).disabled;
let addons = await AddonManager.getAddonsByIDs(disabledAddons);
if (addons.some(addon => addon)) {
this._notifyUnsignedAddonsDisabled();
}
break;
case "sync-ui-state:update":
this._updateFxaBadges();
break;
case "handlersvc-store-initialized":
// Initialize PdfJs when running in-process and remote. This only
// happens once since PdfJs registers global hooks. If the PdfJs
// extension is installed the init method below will be overridden
// leaving initialization to the extension.
// parent only: configure default prefs, set up pref observers, register
// pdf content handler, and initializes parent side message manager
// shim for privileged api access.
PdfJs.init(this._isNewProfile);
// Allow certain viewable internally types to be opened from downloads.
DownloadsViewableInternally.register();
break;
}
},
// initialization (called on application startup)
_init: function BG__init() {
let os = Services.obs;
os.addObserver(this, "notifications-open-settings");
os.addObserver(this, "final-ui-startup");
os.addObserver(this, "browser-delayed-startup-finished");
os.addObserver(this, "sessionstore-windows-restored");
os.addObserver(this, "browser:purge-session-history");
os.addObserver(this, "quit-application-requested");
os.addObserver(this, "quit-application-granted");
if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
os.addObserver(this, "browser-lastwindow-close-requested");
os.addObserver(this, "browser-lastwindow-close-granted");
}
os.addObserver(this, "weave:service:ready");
os.addObserver(this, "fxaccounts:onverified");
os.addObserver(this, "fxaccounts:device_connected");
os.addObserver(this, "fxaccounts:verify_login");
os.addObserver(this, "fxaccounts:device_disconnected");
os.addObserver(this, "fxaccounts:commands:open-uri");
os.addObserver(this, "weave:engine:clients:display-uris");
os.addObserver(this, "session-save");
os.addObserver(this, "places-init-complete");
os.addObserver(this, "distribution-customization-complete");
os.addObserver(this, "handle-xul-text-link");
os.addObserver(this, "profile-before-change");
os.addObserver(this, "keyword-search");
os.addObserver(this, "browser-search-engine-modified");
os.addObserver(this, "restart-in-safe-mode");
os.addObserver(this, "flash-plugin-hang");
os.addObserver(this, "xpi-signature-changed");
os.addObserver(this, "sync-ui-state:update");
os.addObserver(this, "handlersvc-store-initialized");
ActorManagerParent.addJSProcessActors(JSPROCESSACTORS);
ActorManagerParent.addJSWindowActors(JSWINDOWACTORS);
this._flashHangCount = 0;
this._firstWindowReady = new Promise(
resolve => (this._firstWindowLoaded = resolve)
);
if (AppConstants.platform == "win") {
JawsScreenReaderVersionCheck.init();
}
// This value is to limit collecting Places telemetry once per session.
this._placesTelemetryGathered = false;
},
// cleanup (called on application shutdown)
_dispose: function BG__dispose() {
// AboutHomeStartupCache might write to the cache during
// quit-application-granted, so we defer uninitialization
// until here.
AboutHomeStartupCache.uninit();
let os = Services.obs;
os.removeObserver(this, "notifications-open-settings");
os.removeObserver(this, "final-ui-startup");
os.removeObserver(this, "sessionstore-windows-restored");
os.removeObserver(this, "browser:purge-session-history");
os.removeObserver(this, "quit-application-requested");
os.removeObserver(this, "quit-application-granted");
os.removeObserver(this, "restart-in-safe-mode");
if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
os.removeObserver(this, "browser-lastwindow-close-requested");
os.removeObserver(this, "browser-lastwindow-close-granted");
}
os.removeObserver(this, "weave:service:ready");
os.removeObserver(this, "fxaccounts:onverified");
os.removeObserver(this, "fxaccounts:device_connected");
os.removeObserver(this, "fxaccounts:verify_login");
os.removeObserver(this, "fxaccounts:device_disconnected");
os.removeObserver(this, "fxaccounts:commands:open-uri");
os.removeObserver(this, "weave:engine:clients:display-uris");
os.removeObserver(this, "session-save");
if (this._bookmarksBackupIdleTime) {
this._userIdleService.removeIdleObserver(
this,
this._bookmarksBackupIdleTime
);
delete this._bookmarksBackupIdleTime;
}
if (this._lateTasksIdleObserver) {
this._userIdleService.removeIdleObserver(
this._lateTasksIdleObserver,
LATE_TASKS_IDLE_TIME_SEC
);
delete this._lateTasksIdleObserver;
}
if (this._gmpInstallManager) {
this._gmpInstallManager.uninit();
delete this._gmpInstallManager;
}
try {
os.removeObserver(this, "places-init-complete");
} catch (ex) {
/* Could have been removed already */
}
os.removeObserver(this, "handle-xul-text-link");
os.removeObserver(this, "profile-before-change");
os.removeObserver(this, "keyword-search");
os.removeObserver(this, "browser-search-engine-modified");
os.removeObserver(this, "flash-plugin-hang");
os.removeObserver(this, "xpi-signature-changed");
os.removeObserver(this, "sync-ui-state:update");
Services.prefs.removeObserver(
"privacy.trackingprotection",
this._matchCBCategory
);
Services.prefs.removeObserver(
"network.cookie.cookieBehavior",
this._matchCBCategory
);
Services.prefs.removeObserver(
ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY,
this._updateCBCategory
);
Services.prefs.removeObserver(
"privacy.trackingprotection",
this._setPrefExpectations
);
Services.prefs.removeObserver(
"browser.contentblocking.features.strict",
this._setPrefExpectationsAndUpdate
);
},
// runs on startup, before the first command line handler is invoked
// (i.e. before the first window is opened)
_beforeUIStartup: function BG__beforeUIStartup() {
SessionStartup.init();
// check if we're in safe mode
if (Services.appinfo.inSafeMode) {
Services.ww.openWindow(
null,
"_blank",
"chrome,centerscreen,modal,resizable=no",
null
);
}
// apply distribution customizations
this._distributionCustomizer.applyCustomizations();
// handle any UI migration
this._migrateUI();
if (!Services.prefs.prefHasUserValue(PREF_PDFJS_ISDEFAULT_CACHE_STATE)) {
PdfJs.checkIsDefault(this._isNewProfile);
}
listeners.init();
SessionStore.init();
AddonManager.maybeInstallBuiltinAddon(
"firefox-compact-light@mozilla.org",
"1.1",
);
AddonManager.maybeInstallBuiltinAddon(
"firefox-compact-dark@mozilla.org",
"1.1",
);
if (
AppConstants.NIGHTLY_BUILD &&
Services.prefs.getBoolPref("browser.proton.enabled", false)
) {
// Temporarily install a fork of the Dark Theme to do development on for
// Proton. We only make this available if `browser.proton.enabled` is set
// to true, and we make sure to uninstall it again during shutdown.
const kProtonDarkThemeID = "firefox-compact-proton-dark@mozilla.org";
AddonManager.maybeInstallBuiltinAddon(
kProtonDarkThemeID,
"1.0",
);
AsyncShutdown.profileChangeTeardown.addBlocker(
"Uninstall Proton Dark Mode",
async () => {
try {
let addon = await AddonManager.getAddonByID(kProtonDarkThemeID);
await addon.uninstall();
} catch (e) {
Cu.reportError(
"Failed to uninstall firefox-compact-proton-dark on shutdown"
);
}
}
);
}
AddonManager.maybeInstallBuiltinAddon(
"firefox-alpenglow@mozilla.org",
"1.2",
);
if (AppConstants.MOZ_NORMANDY) {
Normandy.init();
}
SaveToPocket.init();
AboutHomeStartupCache.init();
Services.obs.notifyObservers(null, "browser-ui-startup-complete");
},
_checkForOldBuildUpdates() {
// check for update if our build is old
if (
AppConstants.MOZ_UPDATER &&
Services.prefs.getBoolPref("app.update.checkInstallTime")
) {
let buildID = Services.appinfo.appBuildID;
let today = new Date().getTime();
/* eslint-disable no-multi-spaces */
let buildDate = new Date(
buildID.slice(0, 4), // year
buildID.slice(4, 6) - 1, // months are zero-based.
buildID.slice(6, 8), // day
buildID.slice(8, 10), // hour
buildID.slice(10, 12), // min
buildID.slice(12, 14)
) // ms
.getTime();
/* eslint-enable no-multi-spaces */
const millisecondsIn24Hours = 86400000;
let acceptableAge =
Services.prefs.getIntPref("app.update.checkInstallTime.days") *
millisecondsIn24Hours;
if (buildDate + acceptableAge < today) {
Cc["@mozilla.org/updates/update-service;1"]
.getService(Ci.nsIApplicationUpdateService)
.checkForBackgroundUpdates();
}
}
},
_onSafeModeRestart: function BG_onSafeModeRestart() {
// prompt the user to confirm
let strings = gBrowserBundle;
let promptTitle = strings.GetStringFromName("safeModeRestartPromptTitle");
let promptMessage = strings.GetStringFromName(
"safeModeRestartPromptMessage"
);
let restartText = strings.GetStringFromName("safeModeRestartButton");
let buttonFlags =
Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL +
Services.prompt.BUTTON_POS_0_DEFAULT;
let rv = Services.prompt.confirmEx(
null,
promptTitle,
promptMessage,
buttonFlags,
restartText,
null,
null,
null,
{}
);
if (rv != 0) {
return;
}
let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(
Ci.nsISupportsPRBool
);
Services.obs.notifyObservers(
cancelQuit,
"quit-application-requested",
"restart"
);
if (!cancelQuit.data) {
Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit);
}
},
/**
* Show a notification bar offering a reset.
*
* @param reason
* String of either "unused" or "uninstall", specifying the reason
* why a profile reset is offered.
*/
_resetProfileNotification(reason) {
let win = BrowserWindowTracker.getTopWindow();
if (!win) {
return;
}
const { ResetProfile } = ChromeUtils.import(
);
if (!ResetProfile.resetSupported()) {
return;
}
let productName = gBrandBundle.GetStringFromName("brandShortName");
let resetBundle = Services.strings.createBundle(
);
let message;
if (reason == "unused") {
message = resetBundle.formatStringFromName("resetUnusedProfile.message", [
productName,
]);
} else if (reason == "uninstall") {
message = resetBundle.formatStringFromName("resetUninstalled.message", [
productName,
]);
} else {
throw new Error(
`Unknown reason (${reason}) given to _resetProfileNotification.`
);
}
let buttons = [
{
label: resetBundle.formatStringFromName(
"refreshProfile.resetButton.label",
[productName]
),
accessKey: resetBundle.GetStringFromName(
"refreshProfile.resetButton.accesskey"
),
callback() {
ResetProfile.openConfirmationDialog(win);
},
},
];
win.gNotificationBox.appendNotification(
message,
"reset-profile-notification",
win.gNotificationBox.PRIORITY_INFO_LOW,
buttons
);
},
_notifyUnsignedAddonsDisabled() {
let win = BrowserWindowTracker.getTopWindow();
if (!win) {
return;
}
let message = win.gNavigatorBundle.getString(
"unsignedAddonsDisabled.message"
);
let buttons = [
{
label: win.gNavigatorBundle.getString(
"unsignedAddonsDisabled.learnMore.label"
),
accessKey: win.gNavigatorBundle.getString(
"unsignedAddonsDisabled.learnMore.accesskey"
),
callback() {
win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true");
},
},
];
win.gHighPriorityNotificationBox.appendNotification(
message,
"unsigned-addons-disabled",
"",
win.gHighPriorityNotificationBox.PRIORITY_WARNING_MEDIUM,
buttons
);
},
_firstWindowTelemetry(aWindow) {
let scaling = aWindow.devicePixelRatio * 100;
try {
Services.telemetry.getHistogramById("DISPLAY_SCALING").add(scaling);
} catch (ex) {}
},
_collectStartupConditionsTelemetry() {
let nowSeconds = Math.round(Date.now() / 1000);
// Don't include cases where we don't have the pref. This rules out the first install
// as well as the first run of a build since this was introduced. These could by some
// definitions be referred to as "cold" startups, but probably not since we likely
// just wrote many of the files we use to disk. This way we should approximate a lower
// bound to the number of cold startups rather than an upper bound.
let lastCheckSeconds = Services.prefs.getIntPref(
"browser.startup.lastColdStartupCheck",
nowSeconds
);
Services.prefs.setIntPref(
"browser.startup.lastColdStartupCheck",
nowSeconds
);
try {