BrowserGlue.jsm 137 KB
Newer Older
1
2
3
/* 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/. */
4

5
6
var EXPORTED_SYMBOLS = ["BrowserGlue", "ContentPermissionPrompt"];

7
8
const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

9
10
11
12
13
14
15
const { XPCOMUtils } = ChromeUtils.import(
  "resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
  "resource://gre/modules/AppConstants.jsm"
);
16

17
18
19
20
21
ChromeUtils.defineModuleGetter(
  this,
  "ActorManagerParent",
  "resource://gre/modules/ActorManagerParent.jsm"
);
22

23
24
const PREF_PDFJS_ENABLED_CACHE_STATE = "pdfjs.enabledCache.state";

25
let ACTORS = {
26
27
28
29
30
31
32
33
34
35
36
  SubframeCrash: {
    parent: {
      moduleURI: "resource:///actors/SubframeCrashParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/SubframeCrashChild.jsm",
    },

    allFrames: true,
  },
37
38
39
};

let LEGACY_ACTORS = {
40
41
42
43
44
  AboutLogins: {
    child: {
      matches: ["about:logins"],
      module: "resource:///actors/AboutLoginsChild.jsm",
      events: {
45
46
47
48
        AboutLoginsDeleteLogin: { wantUntrusted: true },
        AboutLoginsOpenSite: { wantUntrusted: true },
        AboutLoginsUpdateLogin: { wantUntrusted: true },
        AboutLoginsInit: { wantUntrusted: true },
49
50
51
52
53
54
55
56
57
58
      },
      messages: [
        "AboutLogins:AllLogins",
        "AboutLogins:LoginAdded",
        "AboutLogins:LoginModified",
        "AboutLogins:LoginRemoved",
      ],
    },
  },

59
60
61
62
63
  AboutReader: {
    child: {
      module: "resource:///actors/AboutReaderChild.jsm",
      group: "browsers",
      events: {
64
65
66
67
        AboutReaderContentLoaded: { wantUntrusted: true },
        DOMContentLoaded: {},
        pageshow: { mozSystemGroup: true },
        pagehide: { mozSystemGroup: true },
68
      },
69
      messages: ["Reader:ToggleReaderMode", "Reader:PushState"],
70
71
72
    },
  },

73
74
75
76
  BlockedSite: {
    child: {
      module: "resource:///actors/BlockedSiteChild.jsm",
      events: {
77
78
        AboutBlockedLoaded: { wantUntrusted: true },
        click: {},
79
80
81
      },
      matches: ["about:blocked?*"],
      allFrames: true,
82
      messages: ["DeceptiveBlockedDetails"],
83
84
85
    },
  },

86
87
88
89
90
91
  BrowserTab: {
    child: {
      module: "resource:///actors/BrowserTabChild.jsm",
      group: "browsers",

      events: {
92
93
        DOMWindowCreated: { once: true },
        MozAfterPaint: { once: true },
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
        "MozDOMPointerLock:Entered": {},
        "MozDOMPointerLock:Exited": {},
      },

      messages: [
        "AllowScriptsToClose",
        "Browser:AppTab",
        "Browser:HasSiblings",
        "Browser:Reload",
        "MixedContent:ReenableProtection",
        "SwitchDocumentDirection",
        "UpdateCharacterSet",
      ],
    },
  },
109

110
111
112
113
  ClickHandler: {
    child: {
      module: "resource:///actors/ClickHandlerChild.jsm",
      events: {
114
115
        click: { capture: true, mozSystemGroup: true },
        auxclick: { capture: true, mozSystemGroup: true },
116
      },
117
118
119
    },
  },

120
121
122
123
  ContextMenu: {
    child: {
      module: "resource:///actors/ContextMenuChild.jsm",
      events: {
124
        contextmenu: { mozSystemGroup: true },
125
126
127
128
      },
    },
  },

129
130
131
132
  ContentSearch: {
    child: {
      module: "resource:///actors/ContentSearchChild.jsm",
      group: "browsers",
133
134
135
136
137
138
139
      matches: [
        "about:home",
        "about:newtab",
        "about:welcome",
        "about:privatebrowsing",
        "chrome://mochitests/content/*",
      ],
140
      events: {
141
        ContentSearchClient: { capture: true, wantUntrusted: true },
142
      },
143
      messages: ["ContentSearch"],
144
145
146
    },
  },

147
148
149
150
151
152
153
154
155
156
157
  DOMFullscreen: {
    child: {
      module: "resource:///actors/DOMFullscreenChild.jsm",
      group: "browsers",
      events: {
        "MozDOMFullscreen:Request": {},
        "MozDOMFullscreen:Entered": {},
        "MozDOMFullscreen:NewOrigin": {},
        "MozDOMFullscreen:Exit": {},
        "MozDOMFullscreen:Exited": {},
      },
158
      messages: ["DOMFullscreen:Entered", "DOMFullscreen:CleanUp"],
159
160
161
    },
  },

162
  FormValidation: {
163
    child: {
164
      module: "resource:///actors/FormValidationChild.jsm",
165
      events: {
166
        MozInvalidForm: {},
167
168
169
170
      },
    },
  },

171
172
173
174
175
  LightweightTheme: {
    child: {
      module: "resource:///actors/LightweightThemeChild.jsm",
      matches: ["about:home", "about:newtab", "about:welcome"],
      events: {
176
        pageshow: { mozSystemGroup: true },
177
178
179
180
      },
    },
  },

181
182
183
184
  LinkHandler: {
    child: {
      module: "resource:///actors/LinkHandlerChild.jsm",
      events: {
185
186
187
188
189
        DOMHeadElementParsed: {},
        DOMLinkAdded: {},
        DOMLinkChanged: {},
        pageshow: {},
        pagehide: {},
190
191
192
193
      },
    },
  },

194
195
196
197
  NetError: {
    child: {
      module: "resource:///actors/NetErrorChild.jsm",
      events: {
198
199
200
201
        AboutNetErrorLoad: { wantUntrusted: true },
        AboutNetErrorSetAutomatic: { wantUntrusted: true },
        AboutNetErrorResetPreferences: { wantUntrusted: true },
        click: {},
202
203
204
      },
      matches: ["about:certerror?*", "about:neterror?*"],
      allFrames: true,
205
      messages: ["CertErrorDetails"],
206
207
208
    },
  },

209
210
211
212
  OfflineApps: {
    child: {
      module: "resource:///actors/OfflineAppsChild.jsm",
      events: {
213
        MozApplicationManifest: {},
214
      },
215
      messages: ["OfflineApps:StartFetching"],
216
217
218
    },
  },

219
220
221
222
223
  PageInfo: {
    child: {
      module: "resource:///actors/PageInfoChild.jsm",
      messages: ["PageInfo:getData"],
    },
224
225
  },

226
227
228
229
230
  PageStyle: {
    child: {
      module: "resource:///actors/PageStyleChild.jsm",
      group: "browsers",
      events: {
231
        pageshow: {},
232
      },
233
      messages: ["PageStyle:Switch", "PageStyle:Disable"],
234
235
236
      // Only matching web pages, as opposed to internal about:, chrome: or
      // resource: pages. See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns
      matches: ["*://*/*"],
237
238
    },
  },
239
240
241
242
243

  Plugin: {
    child: {
      module: "resource:///actors/PluginChild.jsm",
      events: {
244
245
246
247
248
249
        PluginBindingAttached: { capture: true, wantUntrusted: true },
        PluginCrashed: { capture: true },
        PluginOutdated: { capture: true },
        PluginInstantiated: { capture: true },
        PluginRemoved: { capture: true },
        HiddenPlugin: { capture: true },
250
251
252
253
254
255
256
257
258
259
      },

      messages: [
        "BrowserPlugins:ActivatePlugins",
        "BrowserPlugins:ContextMenuCommand",
        "BrowserPlugins:NPAPIPluginProcessCrashed",
        "BrowserPlugins:CrashReportSubmitted",
        "BrowserPlugins:Test:ClearCrashData",
      ],

260
      observers: ["decoder-doctor-notification"],
261
262
    },
  },
263

264
265
266
267
268
  RFPHelper: {
    child: {
      module: "resource:///actors/RFPHelperChild.jsm",
      group: "browsers",
      events: {
269
        resize: {},
270
271
272
273
      },
    },
  },

274
275
276
277
278
  SearchTelemetry: {
    child: {
      module: "resource:///actors/SearchTelemetryChild.jsm",
      events: {
        DOMContentLoaded: {},
279
        pageshow: { mozSystemGroup: true },
280
281
282
283
      },
    },
  },

284
285
286
287
  ShieldFrame: {
    child: {
      module: "resource://normandy-content/ShieldFrameChild.jsm",
      events: {
288
        ShieldPageEvent: { wantUntrusted: true },
289
290
291
292
293
      },
      matches: ["about:studies"],
    },
  },

294
295
296
297
  UITour: {
    child: {
      module: "resource:///modules/UITourChild.jsm",
      events: {
298
        mozUITour: { wantUntrusted: true },
299
300
301
302
303
      },
      permissions: ["uitour"],
    },
  },

304
305
306
307
308
309
310
  URIFixup: {
    child: {
      module: "resource:///actors/URIFixupChild.jsm",
      group: "browsers",
      observers: ["keyword-uri-fixup"],
    },
  },
311
312
313
314
315
316
317
318
319
320
321
322
323

  WebRTC: {
    child: {
      module: "resource:///actors/WebRTCChild.jsm",
      messages: [
        "rtcpeer:Allow",
        "rtcpeer:Deny",
        "webrtc:Allow",
        "webrtc:Deny",
        "webrtc:StopSharing",
      ],
    },
  },
324
325
};

326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
if (AppConstants.TOR_BROWSER_UPDATE) {
  LEGACY_ACTORS["AboutTBUpdate"] = {
    child: {
      module: "resource:///actors/AboutTBUpdateChild.jsm",
      events: {
        "AboutTBUpdateLoad": {wantUntrusted: true},
        "pagehide": {capture: true},
      },
      matches: ["about:tbupdate"],
      messages: [
        "AboutTBUpdate:Update",
      ],
    }
  };
}

342
(function earlyBlankFirstPaint() {
343
  if (!Services.prefs.getBoolPref("browser.startup.blankWindow", false)) {
344
    return;
345
  }
346

347
348
  // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
  // using a non-default theme.
349
350
351
352
353
354
  if (
    Services.prefs.getCharPref(
      "extensions.activeThemeID",
      "default-theme@mozilla.org"
    ) != "default-theme@mozilla.org"
  ) {
355
    return;
356
  }
357

358
  let store = Services.xulStore;
359
  let getValue = attr =>
360
    store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
361
362
363
364
  let width = getValue("width");
  let height = getValue("height");

  // The clean profile case isn't handled yet. Return early for now.
365
  if (!width || !height) {
366
    return;
367
  }
368
369
370

  let browserWindowFeatures =
    "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
371
    "location,toolbar,personalbar";
372
373
374
375
376
377
378
  let win = Services.ww.openWindow(
    null,
    "about:blank",
    null,
    browserWindowFeatures,
    null
  );
379
380

  // Hide the titlebar if the actual browser window will draw in it.
381
382
383
384
  let hiddenTitlebar = Services.prefs.getBoolPref(
    "browser.tabs.drawInTitlebar",
    win.matchMedia("(-moz-gtk-csd-hide-titlebar-by-default)").matches
  );
385
  if (hiddenTitlebar) {
386
    win.windowUtils.setChromeMargin(0, 2, 2, 2);
387
388
  }

389
390
391
  let docElt = win.document.documentElement;
  docElt.setAttribute("screenX", getValue("screenX"));
  docElt.setAttribute("screenY", getValue("screenY"));
392
393
394
395
396
397

  // The sizemode="maximized" attribute needs to be set before first paint.
  let sizemode = getValue("sizemode");
  if (sizemode == "maximized") {
    docElt.setAttribute("sizemode", sizemode);

398
399
400
401
    // 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 xulWin = win.docShell.treeOwner
402
403
      .QueryInterface(Ci.nsIInterfaceRequestor)
      .getInterface(Ci.nsIXULWindow);
404
405
    height -= xulWin.outerToInnerHeightDifferenceInCSSPixels;
    width -= xulWin.outerToInnerWidthDifferenceInCSSPixels;
406
407
408
409
410
411
412
413
    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);
  }

414
415
416
417
  // 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");

418
419
420
  // The window becomes visible after OnStopRequest, so make this happen now.
  win.stop();

421
422
423
  let { TelemetryTimestamps } = ChromeUtils.import(
    "resource://gre/modules/TelemetryTimestamps.jsm"
  );
424
  TelemetryTimestamps.add("blankWindowShown");
425
426
})();

427
XPCOMUtils.defineLazyServiceGetters(this, {
428
429
430
431
  aboutNewTabService: [
    "@mozilla.org/browser/aboutnewtab-service;1",
    "nsIAboutNewTabService",
  ],
432
});
433
434
435
436
XPCOMUtils.defineLazyGetter(
  this,
  "WeaveService",
  () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
437
);
438

439
// lazy module getters
440

441
XPCOMUtils.defineLazyModuleGetters(this, {
442
443
444
445
  AboutNetErrorHandler:
    "resource:///modules/aboutpages/AboutNetErrorHandler.jsm",
  AboutPrivateBrowsingHandler:
    "resource:///modules/aboutpages/AboutPrivateBrowsingHandler.jsm",
446
447
448
449
  AddonManager: "resource://gre/modules/AddonManager.jsm",
  AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
  AutoCompletePopup: "resource://gre/modules/AutoCompletePopup.jsm",
450
  Blocklist: "resource://gre/modules/Blocklist.jsm",
451
452
453
  BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.jsm",
  BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.jsm",
  BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
454
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
455
456
  ContextualIdentityService:
    "resource://gre/modules/ContextualIdentityService.jsm",
457
  Corroborate: "resource://gre/modules/Corroborate.jsm",
458
  DateTimePickerParent: "resource://gre/modules/DateTimePickerParent.jsm",
459
  Discovery: "resource:///modules/Discovery.jsm",
460
  ExtensionsUI: "resource:///modules/ExtensionsUI.jsm",
461
  FileSource: "resource://gre/modules/L10nRegistry.jsm",
462
  FxAccounts: "resource://gre/modules/FxAccounts.jsm",
463
  HomePage: "resource:///modules/HomePage.jsm",
464
  HybridContentTelemetry: "resource://gre/modules/HybridContentTelemetry.jsm",
465
  Integration: "resource://gre/modules/Integration.jsm",
466
  L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
467
  LiveBookmarkMigrator: "resource:///modules/LiveBookmarkMigrator.jsm",
468
  NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
469
  Normandy: "resource://normandy/Normandy.jsm",
470
  ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
471
472
473
474
475
  OS: "resource://gre/modules/osfile.jsm",
  PageActions: "resource:///modules/PageActions.jsm",
  PageThumbs: "resource://gre/modules/PageThumbs.jsm",
  PdfJs: "resource://pdf.js/PdfJs.jsm",
  PermissionUI: "resource:///modules/PermissionUI.jsm",
476
  PingCentre: "resource:///modules/PingCentre.jsm",
477
478
479
480
481
  PlacesBackups: "resource://gre/modules/PlacesBackups.jsm",
  PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
  PluralForm: "resource://gre/modules/PluralForm.jsm",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
  ProcessHangMonitor: "resource:///modules/ProcessHangMonitor.jsm",
482
  RemoteSettings: "resource://services-settings/remote-settings.js",
483
  RFPHelper: "resource://gre/modules/RFPHelper.jsm",
484
  SafeBrowsing: "resource://gre/modules/SafeBrowsing.jsm",
485
  Sanitizer: "resource:///modules/Sanitizer.jsm",
486
  SaveToPocket: "chrome://pocket/content/SaveToPocket.jsm",
487
  SearchTelemetry: "resource:///modules/SearchTelemetry.jsm",
488
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.jsm",
489
490
491
  SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
  ShellService: "resource:///modules/ShellService.jsm",
  TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
492
  TabUnloader: "resource:///modules/TabUnloader.jsm",
493
494
495
496
497
  UIState: "resource://services-sync/UIState.jsm",
  UITour: "resource:///modules/UITour.jsm",
  WebChannel: "resource://gre/modules/WebChannel.jsm",
  WindowsRegistry: "resource://gre/modules/WindowsRegistry.jsm",
});
498

499
500
// eslint-disable-next-line no-unused-vars
XPCOMUtils.defineLazyModuleGetters(this, {
501
  AboutLoginsParent: "resource:///modules/AboutLoginsParent.jsm",
502
503
504
505
506
507
508
509
510
  AsyncPrefs: "resource://gre/modules/AsyncPrefs.jsm",
  ContentClick: "resource:///modules/ContentClick.jsm",
  FormValidationHandler: "resource:///modules/FormValidationHandler.jsm",
  LoginManagerParent: "resource://gre/modules/LoginManagerParent.jsm",
  PictureInPicture: "resource://gre/modules/PictureInPicture.jsm",
  ReaderParent: "resource:///modules/ReaderParent.jsm",
  RemotePrompt: "resource:///modules/RemotePrompt.jsm",
});

511
/* global ContentPrefServiceParent:false, ContentSearch:false,
512
          UpdateListener:false, webrtcUI:false */
513

514
515
516
517
518
/**
 * IF YOU ADD OR REMOVE FROM THIS LIST, PLEASE UPDATE THE LIST ABOVE AS WELL.
 * XXX Bug 1325373 is for making eslint detect these automatically.
 */

519
520
let initializedModules = {};

521
[
522
523
524
525
526
  [
    "ContentPrefServiceParent",
    "resource://gre/modules/ContentPrefServiceParent.jsm",
    "alwaysInit",
  ],
527
  ["ContentSearch", "resource:///modules/ContentSearch.jsm", "init"],
528
  ["UpdateListener", "resource://gre/modules/UpdateListener.jsm", "init"],
529
530
  ["webrtcUI", "resource:///modules/webrtcUI.jsm", "init"],
].forEach(([name, resource, init]) => {
531
  XPCOMUtils.defineLazyGetter(this, name, () => {
532
    ChromeUtils.import(resource, initializedModules);
533
534
535
    initializedModules[name][init]();
    return initializedModules[name];
  });
536
});
537

538
if (AppConstants.MOZ_CRASHREPORTER) {
539
540
541
542
  XPCOMUtils.defineLazyModuleGetters(this, {
    PluginCrashReporter: "resource:///modules/ContentCrashHandlers.jsm",
    UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
  });
543
}
544

545
546
547
548
549
if (AppConstants.TOR_BROWSER_UPDATE) {
  XPCOMUtils.defineLazyModuleGetter(this, "AboutTBUpdate",
                                    "resource:///modules/AboutTBUpdate.jsm");
}

550
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
551
552
553
  return Services.strings.createBundle(
    "chrome://branding/locale/brand.properties"
  );
554
555
556
});

XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
557
558
559
  return Services.strings.createBundle(
    "chrome://browser/locale/browser.properties"
  );
560
561
});

562
XPCOMUtils.defineLazyGetter(this, "gTabbrowserBundle", function() {
563
564
565
  return Services.strings.createBundle(
    "chrome://browser/locale/tabbrowser.properties"
  );
566
567
});

568
569
570
const global = this;

const listeners = {
571
  observers: {
572
    "update-downloading": ["UpdateListener"],
573
574
575
576
577
578
    "update-staged": ["UpdateListener"],
    "update-downloaded": ["UpdateListener"],
    "update-available": ["UpdateListener"],
    "update-error": ["UpdateListener"],
  },

579
  ppmm: {
580
581
582
583
584
    // PLEASE KEEP THIS LIST IN SYNC WITH THE LISTENERS ADDED IN ContentPrefServiceParent.init
    "ContentPrefs:FunctionCall": ["ContentPrefServiceParent"],
    "ContentPrefs:AddObserverForName": ["ContentPrefServiceParent"],
    "ContentPrefs:RemoveObserverForName": ["ContentPrefServiceParent"],
    // PLEASE KEEP THIS LIST IN SYNC WITH THE LISTENERS ADDED IN ContentPrefServiceParent.init
585
586
587
588
589
590

    // PLEASE KEEP THIS LIST IN SYNC WITH THE LISTENERS ADDED IN AsyncPrefs.init
    "AsyncPrefs:SetPref": ["AsyncPrefs"],
    "AsyncPrefs:ResetPref": ["AsyncPrefs"],
    // PLEASE KEEP THIS LIST IN SYNC WITH THE LISTENERS ADDED IN AsyncPrefs.init

591
592
593
594
595
    "webrtc:UpdateGlobalIndicators": ["webrtcUI"],
    "webrtc:UpdatingIndicators": ["webrtcUI"],
  },

  mm: {
596
    "AboutLogins:DeleteLogin": ["AboutLoginsParent"],
597
    "AboutLogins:OpenSite": ["AboutLoginsParent"],
598
    "AboutLogins:Subscribe": ["AboutLoginsParent"],
599
    "AboutLogins:UpdateLogin": ["AboutLoginsParent"],
600
    "Content:Click": ["ContentClick"],
601
    ContentSearch: ["ContentSearch"],
602
603
    "FormValidation:ShowPopup": ["FormValidationHandler"],
    "FormValidation:HidePopup": ["FormValidationHandler"],
604
605
    "PictureInPicture:Request": ["PictureInPicture"],
    "PictureInPicture:Close": ["PictureInPicture"],
606
607
    "PictureInPicture:Playing": ["PictureInPicture"],
    "PictureInPicture:Paused": ["PictureInPicture"],
608
    "Prompt:Open": ["RemotePrompt"],
609
610
    "Reader:FaviconRequest": ["ReaderParent"],
    "Reader:UpdateReaderButton": ["ReaderParent"],
611
    // PLEASE KEEP THIS LIST IN SYNC WITH THE MOBILE LISTENERS IN BrowserCLH.js
612
613
614
615
616
617
    "PasswordManager:findLogins": ["LoginManagerParent"],
    "PasswordManager:findRecipes": ["LoginManagerParent"],
    "PasswordManager:onFormSubmit": ["LoginManagerParent"],
    "PasswordManager:autoCompleteLogins": ["LoginManagerParent"],
    "PasswordManager:removeLogin": ["LoginManagerParent"],
    "PasswordManager:insecureLoginFormPresent": ["LoginManagerParent"],
618
    "PasswordManager:OpenPreferences": ["LoginManagerParent"],
619
    // PLEASE KEEP THIS LIST IN SYNC WITH THE MOBILE LISTENERS IN BrowserCLH.js
620
621
622
623
624
625
626
627
    "rtcpeer:CancelRequest": ["webrtcUI"],
    "rtcpeer:Request": ["webrtcUI"],
    "webrtc:CancelRequest": ["webrtcUI"],
    "webrtc:Request": ["webrtcUI"],
    "webrtc:StopRecording": ["webrtcUI"],
    "webrtc:UpdateBrowserIndicators": ["webrtcUI"],
  },

628
629
630
631
632
633
634
635
636
637
  observe(subject, topic, data) {
    for (let module of this.observers[topic]) {
      try {
        global[module].observe(subject, topic, data);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  },

638
  receiveMessage(modules, data) {
639
    let val;
640
641
    for (let module of modules[data.name]) {
      try {
642
        val = global[module].receiveMessage(data) || val;
643
644
645
646
      } catch (e) {
        Cu.reportError(e);
      }
    }
647
    return val;
648
649
650
  },

  init() {
651
652
653
654
    for (let observer of Object.keys(this.observers)) {
      Services.obs.addObserver(this, observer);
    }

655
656
657
658
659
660
661
662
663
    let receiveMessageMM = this.receiveMessage.bind(this, this.mm);
    for (let message of Object.keys(this.mm)) {
      Services.mm.addMessageListener(message, receiveMessageMM);
    }

    let receiveMessagePPMM = this.receiveMessage.bind(this, this.ppmm);
    for (let message of Object.keys(this.ppmm)) {
      Services.ppmm.addMessageListener(message, receiveMessagePPMM);
    }
664
  },
665
666
};

667
// Seconds of idle before trying to create a bookmarks backup.
668
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
669
670
671
672
673
// 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.
674
const BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS = 3;
675
676
// Seconds of idle time before the late idle tasks will be scheduled.
const LATE_TASKS_IDLE_TIME_SEC = 20;
677
678
// Time after we stop tracking startup crashes.
const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
679

680
681
682
683
684
/*
 * 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";
685
686

function BrowserGlue() {
687
688
689
690
691
692
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "_idleService",
    "@mozilla.org/widget/idleservice;1",
    "nsIIdleService"
  );
693

694
  XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
695
696
697
698
699
    const { DistributionCustomizer } = ChromeUtils.import(
      "resource:///modules/distribution.js"
    );
    return new DistributionCustomizer();
  });
700

701
702
703
704
705
706
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "AlertsService",
    "@mozilla.org/alerts-service;1",
    "nsIAlertsService"
  );
707

708
709
710
711
  this._init();
}

BrowserGlue.prototype = {
712
  _saveSession: false,
713
  _migrationImportsDefaultBookmarks: false,
714
  _placesBrowserInitComplete: false,
715

716
  _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
717
    if (!this._saveSession && !aForce) {
718
      return;
719
    }
720

721
    if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
722
723
724
725
      Services.prefs.setBoolPref(
        "browser.sessionstore.resume_session_once",
        true
      );
726
    }
727
728
729
730

    // 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.
731
    Services.prefs.savePrefFile(null);
732
733
  },

734
735
736
  _setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
    // Assume that a non-zero value for services.sync.autoconnectDelay should override
    if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
737
738
739
      let prefDelay = Services.prefs.getIntPref(
        "services.sync.autoconnectDelay"
      );
740

741
      if (prefDelay > 0) {
742
        return;
743
      }
744
745
746
747
748
    }

    // delays are in seconds
    const MAX_DELAY = 300;
    let delay = 3;
749
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
750
751
752
753
754
      // 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;
      }
755
      delay += win.gBrowser.tabs.length;
756
757
758
    }
    delay = delay <= MAX_DELAY ? delay : MAX_DELAY;

759
    const { Weave } = ChromeUtils.import("resource://services-sync/main.js");
760
    Weave.Service.scheduler.delayedAutoConnect(delay);
761
762
  },

763
764
765
766
767
768
  /**
   * Lazily initialize PingCentre
   */
  get pingCentre() {
    const MAIN_TOPIC_ID = "main";
    Object.defineProperty(this, "pingCentre", {
769
      value: new PingCentre({ topic: MAIN_TOPIC_ID }),
770
771
772
773
774
    });
    return this.pingCentre;
  },

  _sendMainPingCentrePing() {
775
776
777
778
779
780
781
782
783
784
785
786
787
788
    let newTabSetting;
    let homePageSetting;

    // Check whether or not about:home and about:newtab have been overridden at this point.
    // Different settings are encoded as follows:
    //   * Value 0: default
    //   * Value 1: about:blank
    //   * Value 2: web extension
    //   * Value 3: other custom URL(s)
    // Settings for about:newtab and about:home are combined in a bitwise manner.

    // Note that a user could use about:blank and web extension at the same time
    // to overwrite the about:newtab, but the web extension takes priority, so the
    // ordering matters in the following check.
789
790
791
792
    if (
      Services.prefs.getBoolPref("browser.newtabpage.enabled") &&
      !aboutNewTabService.overridden
    ) {
793
794
795
796
797
798
799
800
801
      newTabSetting = 0;
    } else if (aboutNewTabService.newTabURL.startsWith("moz-extension://")) {
      newTabSetting = 2;
    } else if (!Services.prefs.getBoolPref("browser.newtabpage.enabled")) {
      newTabSetting = 1;
    } else {
      newTabSetting = 3;
    }

802
    const homePageURL = HomePage.get();
803
804
805
806
807
808
809
810
811
812
    if (homePageURL === "about:home") {
      homePageSetting = 0;
    } else if (homePageURL === "about:blank") {
      homePageSetting = 1;
    } else if (homePageURL.startsWith("moz-extension://")) {
      homePageSetting = 2;
    } else {
      homePageSetting = 3;
    }

813
814
    const payload = {
      event: "AS_ENABLED",
815
      value: newTabSetting | (homePageSetting << 2),
816
    };
817
    const ACTIVITY_STREAM_ID = "activity-stream";
818
    const options = { filter: ACTIVITY_STREAM_ID };
819
820
821
    this.pingCentre.sendPing(payload, options);
  },

822
  // nsIObserver implementation
823
  observe: async function BG_observe(subject, topic, data) {
824
    switch (topic) {
825
      case "notifications-open-settings":
826
        this._openPreferences("privacy-permissions");
827
        break;
828
      case "final-ui-startup":
829
        this._beforeUIStartup();
830
        break;
831
      case "browser-delayed-startup-finished":
832
        this._onFirstWindowLoaded(subject);
833
834
        Services.obs.removeObserver(this, "browser-delayed-startup-finished");
        break;
835
      case "sessionstore-windows-restored":
836
        this._onWindowsRestored();
837
        break;
838
839
      case "browser:purge-session-history":
        // reset the console service's error buffer
840
841
        Services.console.logStringMessage(null); // clear the console (in case it's open)
        Services.console.reset();
842
        break;
843
844
845
      case "restart-in-safe-mode":
        this._onSafeModeRestart();
        break;
846
      case "quit-application-requested":
847
        this._onQuitRequest(subject, data);
848
849
        break;
      case "quit-application-granted":
850
        this._onQuitApplicationGranted();
851
        break;
852
      case "browser-lastwindow-close-requested":
853
854
855
856
857
        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");
        }
858
859
        break;
      case "browser-lastwindow-close-granted":
860
861
862
        if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
          this._setPrefToSaveSession();
        }
863
        break;
864
865
866
      case "weave:service:ready":
        this._setSyncAutoconnectDelay();
        break;
867
868
869
      case "fxaccounts:onverified":
        this._showSyncStartedDoorhanger();
        break;
870
871
872
      case "fxaccounts:device_connected":
        this._onDeviceConnected(data);
        break;
873
874
875
      case "fxaccounts:verify_login":
        this._onVerifyLoginNotification(JSON.parse(data));
        break;
876
      case "fxaccounts:device_disconnected":
877
878
879
880
        data = JSON.parse(data);
        if (data.isLocalDevice) {
          this._onDeviceDisconnected();
        }
881
        break;
882
      case "fxaccounts:commands:open-uri":
883
884
      case "weave:engine:clients:display-uris":
        this._onDisplaySyncURIs(subject);
885
        break;
886
      case "session-save":
887
        this._setPrefToSaveSession(true);
888
889
890
        subject.QueryInterface(Ci.nsISupportsPRBool);
        subject.data = true;
        break;
891
      case "places-init-complete":
892
        Services.obs.removeObserver(this, "places-init-complete");
893
        if (!this._migrationImportsDefaultBookmarks) {
894
          this._initPlaces(false);
895
        }
896
        break;
897
      case "idle":
898
        this._backupBookmarks();
899
        break;
900
      case "distribution-customization-complete":
901
902
903
904
        Services.obs.removeObserver(
          this,
          "distribution-customization-complete"
        );
905
906
907
        // Customization has finished, we don't need the customizer anymore.
        delete this._distributionCustomizer;
        break;
908
909
      case "browser-glue-test": // used by tests
        if (data == "post-update-notification") {
910
          if (Services.prefs.prefHasUserValue("app.update.postupdate")) {
911
            this._showUpdateNotification();
912
          }
913
        } else if (data == "force-ui-migration") {
914
          this._migrateUI();
915
        } else if (data == "force-distribution-customization") {
916
          this._distributionCustomizer.applyCustomizations();
917
          // To apply distribution bookmarks use "places-init-complete".
918
        } else if (data == "force-places-init") {
919
          this._initPlaces(false);
920
921
        } else if (data == "mock-alerts-service") {
          Object.defineProperty(this, "AlertsService", {
922
            value: subject.wrappedJSObject,
923
          });
924
925
926
927
        } else if (data == "places-browser-init-complete") {
          if (this._placesBrowserInitComplete) {
            Services.obs.notifyObservers(null, "places-browser-init-complete");
          }
928
929
        } else if (data == "migrateMatchBucketsPrefForUI66") {
          this._migrateMatchBucketsPrefForUI66().then(() => {
930
931
932
933
934
            Services.obs.notifyObservers(
              null,
              "browser-glue-test",
              "migrateMatchBucketsPrefForUI66-done"
            );
935
          });
936
        }
937
        break;
938
939
940
941
942
      case "initial-migration-will-import-default-bookmarks":
        this._migrationImportsDefaultBookmarks = true;
        break;
      case "initial-migration-did-import-default-bookmarks":
        this._initPlaces(true);
943
        break;
944
945
946
      case "handle-xul-text-link":
        let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
        if (!linkHandled.data) {
947
          let win = BrowserWindowTracker.getTopWindow();
948
          if (win) {
949
950
            data = JSON.parse(data);
            let where = win.whereToOpenLink(data);
951
952
953
954
955
            // Preserve legacy behavior of non-modifier left-clicks
            // opening in a new selected tab.
            if (where == "current") {
              where = "tab";
            }
956
            win.openTrustedLinkIn(data.href, where);
957
958
959
960
            linkHandled.data = true;
          }
        }
        break;
961
      case "profile-before-change":
962
963
964
        // 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.
965
        this._dispose();
966
        break;
967
      case "keyword-search":
968
969
        // This notification is broadcast by the docshell when it "fixes up" a
        // URI that it's been asked to load into a keyword search.
970
971
972
973
974
975
        let engine = null;
        try {
          engine = subject.QueryInterface(Ci.nsISearchEngine);
        } catch (ex) {
          Cu.reportError(ex);
        }
976
        let win = BrowserWindowTracker.getTopWindow();
977
        win.BrowserSearch.recordSearchInTelemetry(engine, "urlbar");
978
        break;
979
      case "browser-search-engine-modified":
980
981
982
983
        // 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;
984
985
986
          let pref = Services.prefs.getStringPref(
            "browser.search.hiddenOneOffs"
          );
987
988
          let hiddenList = pref ? pref.split(",") : [];
          hiddenList = hiddenList.filter(x => x !== engineName);
989
990
991
992
          Services.prefs.setStringPref(
            "browser.search.hiddenOneOffs",
            hiddenList.join(",")
          );
993
        }
994
        break;
995
996
997
      case "flash-plugin-hang":
        this._handleFlashHang();
        break;
998
      case "xpi-signature-changed":
999
        let disabledAddons = JSON.parse(data).disabled;
1000
1001
1002
1003
        let addons = await AddonManager.getAddonsByIDs(disabledAddons);
        if (addons.some(addon => addon)) {
          this._notifyUnsignedAddonsDisabled();
        }
1004
        break;
1005
1006
1007
      case "sync-ui-state:update":
        this._updateFxaBadges();
        break;
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
      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(true);
        break;
1018
      case "shield-init-complete":
1019
        this._shieldInitComplete = true;
1020
1021
        this._sendMainPingCentrePing();
        break;
1022
1023
1024
    }
  },

1025
  // initialization (called on application startup)
1026
  _init: function BG__init() {
1027
    let os = Services.obs;
1028
1029
1030
1031
1032
1033
1034
    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");
1035
    if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
1036
1037
      os.addObserver(this, "browser-lastwindow-close-requested");
      os.addObserver(this, "browser-lastwindow-close-granted");
1038
    }
1039
1040
1041
    os.addObserver(this, "weave:service:ready");
    os.addObserver(this, "fxaccounts:onverified");
    os.addObserver(this, "fxaccounts:device_connected");