BrowserGlue.jsm 176 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
var EXPORTED_SYMBOLS = [
6
  "AboutHomeStartupCache",
7
8
9
10
  "BrowserGlue",
  "ContentPermissionPrompt",
  "DefaultBrowserCheck",
];
11

12
13
14
15
16
17
18
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"
);
19

20
21
22
23
24
25
26
27
const { TorProtocolService } = ChromeUtils.import(
  "resource:///modules/TorProtocolService.jsm"
);

const { TorConnect } = ChromeUtils.import(
  "resource:///modules/TorConnect.jsm"
);

28
29
30
31
32
ChromeUtils.defineModuleGetter(
  this,
  "ActorManagerParent",
  "resource://gre/modules/ActorManagerParent.jsm"
);
33

34
35
36
37
38
39
ChromeUtils.defineModuleGetter(
  this,
  "CustomizableUI",
  "resource:///modules/CustomizableUI.jsm"
);

40
41
42
43
44
45
46
47
48
49
50
51
52
53
ChromeUtils.defineModuleGetter(
  this,
  "E10SUtils",
  "resource://gre/modules/E10SUtils.jsm"
);

ChromeUtils.defineModuleGetter(this, "Log", "resource://gre/modules/Log.jsm");

ChromeUtils.defineModuleGetter(
  this,
  "NetUtil",
  "resource://gre/modules/NetUtil.jsm"
);

54
55
56
57
58
59
ChromeUtils.defineModuleGetter(
  this,
  "DeferredTask",
  "resource://gre/modules/DeferredTask.jsm"
);

60
61
62
63
64
65
66
XPCOMUtils.defineLazyServiceGetter(
  this,
  "PushService",
  "@mozilla.org/push/Service;1",
  "nsIPushService"
);

67
68
69
70
71
72
73
XPCOMUtils.defineLazyServiceGetters(this, {
  resProto: [
    "@mozilla.org/network/protocol;1?name=resource",
    "nsISubstitutingProtocolHandler",
  ],
});

74
const PREF_PDFJS_ISDEFAULT_CACHE_STATE = "pdfjs.enabledCache.state";
75

76
77
78
79
80
81
82
83
/**
 * Fission-compatible JSProcess implementations.
 * Each actor options object takes the form of a ProcessActorOptions dictionary.
 * Detailed documentation of these options is in dom/docs/Fission.rst,
 * available at https://firefox-source-docs.mozilla.org/dom/Fission.html#jsprocessactor
 */
let JSPROCESSACTORS = {};

84
85
86
87
88
/**
 * Fission-compatible JSWindowActor implementations.
 * Detailed documentation of these is in dom/docs/Fission.rst,
 * available at https://firefox-source-docs.mozilla.org/dom/Fission.html#jswindowactor
 */
89
let JSWINDOWACTORS = {
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
  AboutLogins: {
    parent: {
      moduleURI: "resource:///actors/AboutLoginsParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutLoginsChild.jsm",
      events: {
        AboutLoginsCopyLoginDetail: { wantUntrusted: true },
        AboutLoginsCreateLogin: { wantUntrusted: true },
        AboutLoginsDeleteLogin: { wantUntrusted: true },
        AboutLoginsDismissBreachAlert: { wantUntrusted: true },
        AboutLoginsHideFooter: { wantUntrusted: true },
        AboutLoginsImport: { wantUntrusted: true },
        AboutLoginsInit: { wantUntrusted: true },
        AboutLoginsGetHelp: { wantUntrusted: true },
        AboutLoginsOpenMobileAndroid: { wantUntrusted: true },
        AboutLoginsOpenMobileIos: { wantUntrusted: true },
        AboutLoginsOpenPreferences: { wantUntrusted: true },
        AboutLoginsOpenSite: { wantUntrusted: true },
        AboutLoginsRecordTelemetryEvent: { wantUntrusted: true },
        AboutLoginsSortChanged: { wantUntrusted: true },
        AboutLoginsSyncEnable: { wantUntrusted: true },
        AboutLoginsSyncOptions: { wantUntrusted: true },
        AboutLoginsUpdateLogin: { wantUntrusted: true },
114
        AboutLoginsExportPasswords: { wantUntrusted: true },
115
116
117
118
119
      },
    },
    matches: ["about:logins", "about:logins?*"],
  },

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
  AboutNewInstall: {
    parent: {
      moduleURI: "resource:///actors/AboutNewInstallParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutNewInstallChild.jsm",

      events: {
        DOMWindowCreated: { capture: true },
      },
    },

    matches: ["about:newinstall"],
  },

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  AboutPlugins: {
    parent: {
      moduleURI: "resource:///actors/AboutPluginsParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutPluginsChild.jsm",

      events: {
        DOMWindowCreated: { capture: true },
      },
    },

    matches: ["about:plugins"],
  },

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
  AboutPrivateBrowsing: {
    parent: {
      moduleURI: "resource:///actors/AboutPrivateBrowsingParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutPrivateBrowsingChild.jsm",

      events: {
        DOMWindowCreated: { capture: true },
      },
    },

    matches: ["about:privatebrowsing"],
  },

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  AboutProtections: {
    parent: {
      moduleURI: "resource:///actors/AboutProtectionsParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutProtectionsChild.jsm",

      events: {
        DOMWindowCreated: { capture: true },
      },
    },

    matches: ["about:protections"],
  },

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
  AboutTabCrashed: {
    parent: {
      moduleURI: "resource:///actors/AboutTabCrashedParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutTabCrashedChild.jsm",

      events: {
        DOMWindowCreated: { capture: true },
      },
    },

    matches: ["about:tabcrashed*"],
  },

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
  AboutWelcome: {
    parent: {
      moduleURI: "resource:///actors/AboutWelcomeParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/AboutWelcomeChild.jsm",
      events: {
        // This is added so the actor instantiates immediately and makes
        // methods available to the page js on load.
        DOMWindowCreated: {},
      },
    },
    matches: ["about:welcome"],

    // See Bug 1618306
    // Remove this preference check when we turn on separate about:welcome for all users.
    enablePreference: "browser.aboutwelcome.enabled",
  },

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
  BlockedSite: {
    parent: {
      moduleURI: "resource:///actors/BlockedSiteParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/BlockedSiteChild.jsm",
      events: {
        AboutBlockedLoaded: { wantUntrusted: true },
        click: {},
      },
    },
    matches: ["about:blocked?*"],
    allFrames: true,
  },

229
230
231
232
233
234
235
236
  BrowserTab: {
    parent: {
      moduleURI: "resource:///actors/BrowserTabParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/BrowserTabChild.jsm",

      events: {
237
238
        DOMWindowCreated: {},
        MozAfterPaint: {},
239
240
241
242
243
244
        "MozDOMPointerLock:Entered": {},
        "MozDOMPointerLock:Exited": {},
      },
    },
  },

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
  ClickHandler: {
    parent: {
      moduleURI: "resource:///actors/ClickHandlerParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/ClickHandlerChild.jsm",
      events: {
        click: { capture: true, mozSystemGroup: true },
        auxclick: { capture: true, mozSystemGroup: true },
      },
    },

    allFrames: true,
  },

260
261
262
263
264
265
266
267
268
269
270
271
272
273
  // Collects description and icon information from meta tags.
  ContentMeta: {
    parent: {
      moduleURI: "resource:///actors/ContentMetaParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/ContentMetaChild.jsm",
      events: {
        DOMMetaAdded: {},
      },
    },
  },

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
  ContentSearch: {
    parent: {
      moduleURI: "resource:///actors/ContentSearchParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/ContentSearchChild.jsm",
      matches: [
        "about:home",
        "about:newtab",
        "about:welcome",
        "about:privatebrowsing",
        "chrome://mochitests/content/*",
      ],
      events: {
        ContentSearchClient: { capture: true, wantUntrusted: true },
      },
    },
  },

293
294
295
296
297
298
299
300
  ContextMenu: {
    parent: {
      moduleURI: "resource:///actors/ContextMenuParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/ContextMenuChild.jsm",
      events: {
301
        contextmenu: { mozSystemGroup: true },
302
303
304
305
306
307
      },
    },

    allFrames: true,
  },

sanketh's avatar
sanketh committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
  CryptoSafety: {
    parent: {
      moduleURI: "resource:///actors/CryptoSafetyParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/CryptoSafetyChild.jsm",
      group: "browsers",
      events: {
        copy: { mozSystemGroup: true },
        cut: { mozSystemGroup: true },
      },
    },

    allFrames: true,
  },

325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
  DOMFullscreen: {
    parent: {
      moduleURI: "resource:///actors/DOMFullscreenParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/DOMFullscreenChild.jsm",
      group: "browsers",
      events: {
        "MozDOMFullscreen:Request": {},
        "MozDOMFullscreen:Entered": {},
        "MozDOMFullscreen:NewOrigin": {},
        "MozDOMFullscreen:Exit": {},
        "MozDOMFullscreen:Exited": {},
      },
    },

    allFrames: true,
  },

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  FormValidation: {
    parent: {
      moduleURI: "resource:///actors/FormValidationParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/FormValidationChild.jsm",
      events: {
        MozInvalidForm: {},
      },
    },

    allFrames: true,
  },

360
361
362
363
364
365
366
367
368
369
370
371
372
373
  LightweightTheme: {
    child: {
      moduleURI: "resource:///actors/LightweightThemeChild.jsm",
      events: {
        pageshow: { mozSystemGroup: true },
      },
    },
    includeChrome: true,
    allFrames: true,
    matches: [
      "about:home",
      "about:newtab",
      "about:welcome",
      "chrome://browser/content/syncedtabs/sidebar.xhtml",
374
375
      "chrome://browser/content/places/historySidebar.xhtml",
      "chrome://browser/content/places/bookmarksSidebar.xhtml",
376
377
378
    ],
  },

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
  LinkHandler: {
    parent: {
      moduleURI: "resource:///actors/LinkHandlerParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/LinkHandlerChild.jsm",
      events: {
        DOMHeadElementParsed: {},
        DOMLinkAdded: {},
        DOMLinkChanged: {},
        pageshow: {},
        pagehide: {},
      },
    },
  },

395
396
397
398
399
400
401
  NetError: {
    parent: {
      moduleURI: "resource:///actors/NetErrorParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/NetErrorChild.jsm",
      events: {
402
        DOMWindowCreated: {},
403
404
405
406
407
408
409
410
        click: {},
      },
    },

    matches: ["about:certerror?*", "about:neterror?*"],
    allFrames: true,
  },

411
412
413
414
415
416
417
418
  PageInfo: {
    child: {
      moduleURI: "resource:///actors/PageInfoChild.jsm",
    },

    allFrames: true,
  },

419
420
421
422
423
424
425
426
427
428
429
430
431
432
  PageStyle: {
    parent: {
      moduleURI: "resource:///actors/PageStyleParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/PageStyleChild.jsm",
      events: {
        pageshow: {},
      },
    },

    // 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: ["*://*/*"],
433
    messageManagerGroups: ["browsers"],
434
435
436
    allFrames: true,
  },

437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
  Plugin: {
    parent: {
      moduleURI: "resource:///actors/PluginParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/PluginChild.jsm",
      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,
  },

458
459
460
461
  Prompt: {
    parent: {
      moduleURI: "resource:///actors/PromptParent.jsm",
    },
462
    includeChrome: true,
463
464
465
    allFrames: true,
  },

466
467
468
469
470
471
472
473
474
475
476
477
478
479
  SearchTelemetry: {
    parent: {
      moduleURI: "resource:///actors/SearchTelemetryParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/SearchTelemetryChild.jsm",
      events: {
        DOMContentLoaded: {},
        pageshow: { mozSystemGroup: true },
        unload: {},
      },
    },
  },

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
  ShieldFrame: {
    parent: {
      moduleURI: "resource://normandy-content/ShieldFrameParent.jsm",
    },
    child: {
      moduleURI: "resource://normandy-content/ShieldFrameChild.jsm",
      events: {
        pageshow: {},
        pagehide: {},
        ShieldPageEvent: { wantUntrusted: true },
      },
    },
    matches: ["about:studies"],
  },

495
496
497
498
499
500
501
  SwitchDocumentDirection: {
    child: {
      moduleURI: "resource:///actors/SwitchDocumentDirectionChild.jsm",
    },

    allFrames: true,
  },
502

503
504
505
506
507
508
509
510
511
512
513
  SiteSpecificBrowser: {
    parent: {
      moduleURI: "resource:///actors/SiteSpecificBrowserParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/SiteSpecificBrowserChild.jsm",
    },

    allFrames: true,
  },

514
515
516
517
518
519
520
521
522
523
524
525
526
527
  TorConnect: {
    parent: {
      moduleURI: "resource:///modules/TorConnectParent.jsm",
    },
    child: {
      moduleURI: "resource:///modules/TorConnectChild.jsm",
      events: {
        DOMWindowCreated: {},
      },
    },

    matches: ["about:torconnect"],
  },

528
529
530
531
532
533
534
535
  Translation: {
    parent: {
      moduleURI: "resource:///modules/translation/TranslationParent.jsm",
    },
    child: {
      moduleURI: "resource:///modules/translation/TranslationChild.jsm",
      events: {
        pageshow: {},
536
        load: { mozSystemGroup: true, capture: true },
537
538
539
540
541
      },
    },
    enablePreference: "browser.translation.detectLanguage",
  },

542
543
544
545
546
547
548
549
550
551
552
  UITour: {
    parent: {
      moduleURI: "resource:///modules/UITourParent.jsm",
    },
    child: {
      moduleURI: "resource:///modules/UITourChild.jsm",
      events: {
        mozUITour: { wantUntrusted: true },
      },
    },
  },
553
554
555
556
557
558
559
560
561
562
563

  WebRTC: {
    parent: {
      moduleURI: "resource:///actors/WebRTCParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/WebRTCChild.jsm",
    },

    allFrames: true,
  },
564
565
566
};

let LEGACY_ACTORS = {
567
568
569
570
571
572
573
574
575
576
577
578
579
580
  AboutReader: {
    child: {
      module: "resource:///actors/AboutReaderChild.jsm",
      group: "browsers",
      events: {
        AboutReaderContentLoaded: { wantUntrusted: true },
        DOMContentLoaded: {},
        pageshow: { mozSystemGroup: true },
        pagehide: { mozSystemGroup: true },
      },
      messages: ["Reader:ToggleReaderMode", "Reader:PushState"],
    },
  },

581
582
583
584
585
586
587
  URIFixup: {
    child: {
      module: "resource:///actors/URIFixupChild.jsm",
      group: "browsers",
      observers: ["keyword-uri-fixup"],
    },
  },
588
589
590
591
592
593
594
  OnionLocation: {
    child: {
      module: "resource:///modules/OnionLocationChild.jsm",
      events: { pageshow: {} },
      messages: ["OnionLocation:Refresh"],
    },
  },
595
596
};

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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",
      ],
    }
  };
}

613
(function earlyBlankFirstPaint() {
614
615
616
617
  if (
    AppConstants.platform == "macosx" ||
    !Services.prefs.getBoolPref("browser.startup.blankWindow", false)
  ) {
618
    return;
619
  }
620

621
622
  // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
  // using a non-default theme.
623
624
625
626
627
628
  if (
    Services.prefs.getCharPref(
      "extensions.activeThemeID",
      "default-theme@mozilla.org"
    ) != "default-theme@mozilla.org"
  ) {
629
    return;
630
  }
631

632
  let store = Services.xulStore;
633
  let getValue = attr =>
634
    store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
635
636
637
638
  let width = getValue("width");
  let height = getValue("height");

  // The clean profile case isn't handled yet. Return early for now.
639
  if (!width || !height) {
640
    return;
641
  }
642
643
644

  let browserWindowFeatures =
    "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
645
    "location,toolbar,personalbar";
646
647
648
649
650
651
652
  let win = Services.ww.openWindow(
    null,
    "about:blank",
    null,
    browserWindowFeatures,
    null
  );
653
654

  // Hide the titlebar if the actual browser window will draw in it.
655
656
657
658
  let hiddenTitlebar = Services.prefs.getBoolPref(
    "browser.tabs.drawInTitlebar",
    win.matchMedia("(-moz-gtk-csd-hide-titlebar-by-default)").matches
  );
659
  if (hiddenTitlebar) {
660
    win.windowUtils.setChromeMargin(0, 2, 2, 2);
661
662
  }

663
664
665
  let docElt = win.document.documentElement;
  docElt.setAttribute("screenX", getValue("screenX"));
  docElt.setAttribute("screenY", getValue("screenY"));
666
667
668
669
670
671

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

672
673
674
    // 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.
675
    let appWin = win.docShell.treeOwner
676
      .QueryInterface(Ci.nsIInterfaceRequestor)
677
678
679
      .getInterface(Ci.nsIAppWindow);
    height -= appWin.outerToInnerHeightDifferenceInCSSPixels;
    width -= appWin.outerToInnerWidthDifferenceInCSSPixels;
680
681
682
683
684
685
686
687
    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);
  }

688
689
690
691
  // 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");

692
693
694
  // The window becomes visible after OnStopRequest, so make this happen now.
  win.stop();

695
696
697
  let { TelemetryTimestamps } = ChromeUtils.import(
    "resource://gre/modules/TelemetryTimestamps.jsm"
  );
698
  TelemetryTimestamps.add("blankWindowShown");
699
700
})();

701
702
703
704
XPCOMUtils.defineLazyGetter(
  this,
  "WeaveService",
  () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
705
);
706

707
// lazy module getters
708

709
XPCOMUtils.defineLazyModuleGetters(this, {
710
  AboutCertViewerHandler: "resource://gre/modules/AboutCertViewerHandler.jsm",
711
712
713
  AddonManager: "resource://gre/modules/AddonManager.jsm",
  AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
714
  Blocklist: "resource://gre/modules/Blocklist.jsm",
715
716
717
  BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.jsm",
  BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.jsm",
  BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
718
  BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
719
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
720
721
  ContextualIdentityService:
    "resource://gre/modules/ContextualIdentityService.jsm",
722
  Corroborate: "resource://gre/modules/Corroborate.jsm",
723
  Discovery: "resource:///modules/Discovery.jsm",
724
  ExtensionData: "resource://gre/modules/Extension.jsm",
725
  ExtensionsUI: "resource:///modules/ExtensionsUI.jsm",
726
  FirefoxMonitor: "resource:///modules/FirefoxMonitor.jsm",
727
  FxAccounts: "resource://gre/modules/FxAccounts.jsm",
728
  HomePage: "resource:///modules/HomePage.jsm",
729
  Integration: "resource://gre/modules/Integration.jsm",
730
  LoginBreaches: "resource:///modules/LoginBreaches.jsm",
731
  LiveBookmarkMigrator: "resource:///modules/LiveBookmarkMigrator.jsm",
732
  NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
733
  Normandy: "resource://normandy/Normandy.jsm",
734
  ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
735
736
737
738
739
740
741
742
743
744
  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",
  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",
745
  RemoteSettings: "resource://services-settings/remote-settings.js",
746
747
  RemoteSecuritySettings:
    "resource://gre/modules/psm/RemoteSecuritySettings.jsm",
748
  RFPHelper: "resource://gre/modules/RFPHelper.jsm",
749
  SafeBrowsing: "resource://gre/modules/SafeBrowsing.jsm",
750
  Sanitizer: "resource:///modules/Sanitizer.jsm",
751
  SaveToPocket: "chrome://pocket/content/SaveToPocket.jsm",
752
  SearchTelemetry: "resource:///modules/SearchTelemetry.jsm",
753
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.jsm",
754
755
756
  SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
  ShellService: "resource:///modules/ShellService.jsm",
  TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
757
  TabUnloader: "resource:///modules/TabUnloader.jsm",
758
  TRRRacer: "resource:///modules/TRRPerformance.jsm",
759
  OnionAliasStore: "resource:///modules/OnionAliasStore.jsm",
760
761
762
763
  UIState: "resource://services-sync/UIState.jsm",
  WebChannel: "resource://gre/modules/WebChannel.jsm",
  WindowsRegistry: "resource://gre/modules/WindowsRegistry.jsm",
});
764

765
766
// eslint-disable-next-line no-unused-vars
XPCOMUtils.defineLazyModuleGetters(this, {
767
  AboutLoginsParent: "resource:///modules/AboutLoginsParent.jsm",
768
  AsyncPrefs: "resource://gre/modules/AsyncPrefs.jsm",
769
  OnionLocationParent: "resource:///modules/OnionLocationParent.jsm",
770
  PluginManager: "resource:///actors/PluginParent.jsm",
771
  ReaderParent: "resource:///modules/ReaderParent.jsm",
772
773
});

774
775
776
777
778
/**
 * 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.
 */

779
780
let initializedModules = {};

781
[
782
783
784
785
786
  [
    "ContentPrefServiceParent",
    "resource://gre/modules/ContentPrefServiceParent.jsm",
    "alwaysInit",
  ],
787
  ["UpdateListener", "resource://gre/modules/UpdateListener.jsm", "init"],
788
].forEach(([name, resource, init]) => {
789
  XPCOMUtils.defineLazyGetter(this, name, () => {
790
    ChromeUtils.import(resource, initializedModules);
791
792
793
    initializedModules[name][init]();
    return initializedModules[name];
  });
794
});
795

796
if (AppConstants.MOZ_CRASHREPORTER) {
797
798
799
  XPCOMUtils.defineLazyModuleGetters(this, {
    UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
  });
800
}
801

802
803
804
805
806
if (AppConstants.TOR_BROWSER_UPDATE) {
  XPCOMUtils.defineLazyModuleGetter(this, "AboutTBUpdate",
                                    "resource:///modules/AboutTBUpdate.jsm");
}

807
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
808
809
810
  return Services.strings.createBundle(
    "chrome://branding/locale/brand.properties"
  );
811
812
813
});

XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
814
815
816
  return Services.strings.createBundle(
    "chrome://browser/locale/browser.properties"
  );
817
818
});

819
XPCOMUtils.defineLazyGetter(this, "gTabbrowserBundle", function() {
820
821
822
  return Services.strings.createBundle(
    "chrome://browser/locale/tabbrowser.properties"
  );
823
824
});

825
826
827
const global = this;

const listeners = {
828
  observers: {
829
    "update-downloading": ["UpdateListener"],
830
831
832
833
    "update-staged": ["UpdateListener"],
    "update-downloaded": ["UpdateListener"],
    "update-available": ["UpdateListener"],
    "update-error": ["UpdateListener"],
834
835
    "gmp-plugin-crash": ["PluginManager"],
    "plugin-crashed": ["PluginManager"],
836
837
  },

838
  ppmm: {
839
840
841
842
843
    // 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
844
845
846
847
848

    // 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
849
850
851
  },

  mm: {
852
    "AboutLogins:CreateLogin": ["AboutLoginsParent"],
853
    "AboutLogins:DeleteLogin": ["AboutLoginsParent"],
854
    "AboutLogins:DismissBreachAlert": ["AboutLoginsParent"],
855
    "AboutLogins:HideFooter": ["AboutLoginsParent"],
856
    "AboutLogins:Import": ["AboutLoginsParent"],
857
    "AboutLogins:MasterPasswordRequest": ["AboutLoginsParent"],
858
    "AboutLogins:OpenFAQ": ["AboutLoginsParent"],
859
    "AboutLogins:GetHelp": ["AboutLoginsParent"],
860
    "AboutLogins:OpenPreferences": ["AboutLoginsParent"],
861
862
    "AboutLogins:OpenMobileAndroid": ["AboutLoginsParent"],
    "AboutLogins:OpenMobileIos": ["AboutLoginsParent"],
863
    "AboutLogins:OpenSite": ["AboutLoginsParent"],
864
    "AboutLogins:SortChanged": ["AboutLoginsParent"],
865
    "AboutLogins:Subscribe": ["AboutLoginsParent"],
866
867
    "AboutLogins:SyncEnable": ["AboutLoginsParent"],
    "AboutLogins:SyncOptions": ["AboutLoginsParent"],
868
    "AboutLogins:TestOnlyResetOSAuth": ["AboutLoginsParent"],
869
    "AboutLogins:UpdateLogin": ["AboutLoginsParent"],
870
    "AboutLogins:VulnerableLogins": ["AboutLoginsParent"],
871
872
    "Reader:FaviconRequest": ["ReaderParent"],
    "Reader:UpdateReaderButton": ["ReaderParent"],
873
    "OnionLocation:Set": ["OnionLocationParent"],
874
875
  },

876
877
878
879
880
881
882
883
884
885
  observe(subject, topic, data) {
    for (let module of this.observers[topic]) {
      try {
        global[module].observe(subject, topic, data);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  },

886
  receiveMessage(modules, data) {
887
    let val;
888
889
    for (let module of modules[data.name]) {
      try {
890
        val = global[module].receiveMessage(data) || val;
891
892
893
894
      } catch (e) {
        Cu.reportError(e);
      }
    }
895
    return val;
896
897
898
  },

  init() {
899
900
901
902
    for (let observer of Object.keys(this.observers)) {
      Services.obs.addObserver(this, observer);
    }

903
904
905
906
907
908
909
910
911
    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);
    }
912
  },
913
914
};

915
// Seconds of idle before trying to create a bookmarks backup.
916
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
917
918
919
920
921
// 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.
922
const BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS = 3;
923
924
// Seconds of idle time before the late idle tasks will be scheduled.
const LATE_TASKS_IDLE_TIME_SEC = 20;
925
926
// Time after we stop tracking startup crashes.
const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
927

928
929
930
931
932
/*
 * 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";
933
934

function BrowserGlue() {
935
936
937
938
939
940
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "_idleService",
    "@mozilla.org/widget/idleservice;1",
    "nsIIdleService"
  );
941

942
  XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
943
944
945
946
947
    const { DistributionCustomizer } = ChromeUtils.import(
      "resource:///modules/distribution.js"
    );
    return new DistributionCustomizer();
  });
948

949
950
951
952
953
954
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "AlertsService",
    "@mozilla.org/alerts-service;1",
    "nsIAlertsService"
  );
955

956
957
958
959
  this._init();
}

BrowserGlue.prototype = {
960
  _saveSession: false,
961
  _migrationImportsDefaultBookmarks: false,
962
  _placesBrowserInitComplete: false,
963
  _isNewProfile: undefined,
964

965
  _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
966
    if (!this._saveSession && !aForce) {
967
      return;
968
    }
969

970
    if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
971
972
973
974
      Services.prefs.setBoolPref(
        "browser.sessionstore.resume_session_once",
        true
      );
975
    }
976
977
978
979

    // 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.
980
    Services.prefs.savePrefFile(null);
981
982
  },

983
984
985
  _setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
    // Assume that a non-zero value for services.sync.autoconnectDelay should override
    if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
986
987
988
      let prefDelay = Services.prefs.getIntPref(
        "services.sync.autoconnectDelay"
      );
989

990
      if (prefDelay > 0) {
991
        return;
992
      }
993
994
995
996
997
    }

    // delays are in seconds
    const MAX_DELAY = 300;
    let delay = 3;
998
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
999
1000
1001
1002
1003
      // 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;
      }
1004
      delay += win.gBrowser.tabs.length;
1005
1006
1007
    }
    delay = delay <= MAX_DELAY ? delay : MAX_DELAY;

1008
    const { Weave } = ChromeUtils.import("resource://services-sync/main.js");
1009
    Weave.Service.scheduler.delayedAutoConnect(delay);
1010
1011
  },

1012
  // nsIObserver implementation
1013
  observe: async function BG_observe(subject, topic, data) {
1014
    switch (topic) {
1015
      case "notifications-open-settings":
1016
        this._openPreferences("privacy-permissions");
1017
        break;
1018
      case "final-ui-startup":
1019
        this._beforeUIStartup();
1020
        break;
1021
      case "browser-delayed-startup-finished":
1022
        this._onFirstWindowLoaded(subject);
1023
1024
        Services.obs.removeObserver(this, "browser-delayed-startup-finished");
        break;
1025
      case "sessionstore-windows-restored":
1026
        this._onWindowsRestored();
1027
        break;
1028
1029
      case "browser:purge-session-history":
        // reset the console service's error buffer
1030
1031
        Services.console.logStringMessage(null); // clear the console (in case it's open)
        Services.console.reset();
1032
        break;
1033
1034
1035
      case "restart-in-safe-mode":
        this._onSafeModeRestart();
        break;
1036
      case "quit-application-requested":
1037
        this._onQuitRequest(subject, data);
1038
1039
        break;
      case "quit-application-granted":
1040
        this._onQuitApplicationGranted();
1041
        break;
1042
      case "browser-lastwindow-close-requested":
1043
1044
1045
1046
1047
        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");
        }
1048
1049
        break;
      case "browser-lastwindow-close-granted":
1050
1051
1052
        if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
          this._setPrefToSaveSession();
        }
1053
        break;
1054
1055
1056
      case "weave:service:ready":
        this._setSyncAutoconnectDelay();
        break;
1057
      case "fxaccounts:onverified":
1058
        this._onThisDeviceConnected();
1059
        break;
1060
1061
1062
      case "fxaccounts:device_connected":
        this._onDeviceConnected(data);
        break;
1063
1064
1065
      case "fxaccounts:verify_login":
        this._onVerifyLoginNotification(JSON.parse(data));
        break;
1066
      case "fxaccounts:device_disconnected":
1067
1068
1069
1070
        data = JSON.parse(data);
        if (data.isLocalDevice) {
          this._onDeviceDisconnected();
        }
1071
        break;
1072
      case "fxaccounts:commands:open-uri":
1073
1074
      case "weave:engine:clients:display-uris":
        this._onDisplaySyncURIs(subject);
1075
        break;
1076
      case "session-save":
1077
        this._setPrefToSaveSession(true);
1078
1079
1080
        subject.QueryInterface(Ci.nsISupportsPRBool);
        subject.data = true;
        break;
1081
      case "places-init-complete":
1082
        Services.obs.removeObserver(this, "places-init-complete");
1083
        if (!this._migrationImportsDefaultBookmarks) {
1084
          this._initPlaces(false);
1085
        }
1086
        break;
1087
      case "idle":
1088
        this._backupBookmarks();
1089
        break;
1090
      case "distribution-customization-complete":
1091
1092
1093
1094
        Services.obs.removeObserver(
          this,
          "distribution-customization-complete"
        );
1095
1096
1097
        // Customization has finished, we don't need the customizer anymore.
        delete this._distributionCustomizer;
        break;
1098
      case "browser-glue-test": // used by tests
1099
        if (data == "force-ui-migration") {
1100
          this._migrateUI();
1101
        } else if (data == "force-distribution-customization") {
1102
          this._distributionCustomizer.applyCustomizations();
1103
          // To apply distribution bookmarks use "places-init-complete".
1104
        } else if (data == "force-places-init") {
1105
          this._initPlaces(false);
1106
1107
        } else if (data == "mock-alerts-service") {
          Object.defineProperty(this, "AlertsService", {
1108
            value: subject.wrappedJSObject,
1109
          });
1110
1111
1112
1113
        } else if (data == "places-browser-init-complete") {
          if (this._placesBrowserInitComplete) {
            Services.obs.notifyObservers(null, "places-browser-init-complete");
          }
1114
1115
        } else if (data == "migrateMatchBucketsPrefForUI66") {
          this._migrateMatchBucketsPrefForUI66().then(() => {
1116
1117
1118
1119
1120
            Services.obs.notifyObservers(
              null,
              "browser-glue-test",
              "migrateMatchBucketsPrefForUI66-done"
            );
1121
          });
1122
1123
        } else if (data == "add-breaches-sync-handler") {
          this._addBreachesSyncHandler();
1124
        }
1125
        break;
1126
1127
1128
1129
1130
      case "initial-migration-will-import-default-bookmarks":
        this._migrationImportsDefaultBookmarks = true;
        break;
      case "initial-migration-did-import-default-bookmarks":
        this._initPlaces(true);
1131
        break;
1132
1133
1134
      case "handle-xul-text-link":
        let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
        if (!linkHandled.data) {
1135
          let win = BrowserWindowTracker.getTopWindow();
1136
          if (win) {
1137
1138
            data = JSON.parse(data);
            let where = win.whereToOpenLink(data);
1139
1140
1141
1142
1143
            // Preserve legacy behavior of non-modifier left-clicks
            // opening in a new selected tab.
            if (where == "current") {
              where = "tab";
            }
1144
            win.openTrustedLinkIn(data.href, where);
1145
1146
1147
1148
            linkHandled.data = true;
          }
        }
        break;
1149
      case "profile-before-change":
1150
1151
1152
        // 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.
1153
        this._dispose();
1154
        break;
1155
      case "keyword-search":
1156
1157
        // This notification is broadcast by the docshell when it "fixes up" a
        // URI that it's been asked to load into a keyword search.
1158
1159
1160
1161
1162
1163
        let engine = null;
        try {
          engine = subject.QueryInterface(Ci.nsISearchEngine);
        } catch (ex) {
          Cu.reportError(ex);
        }
1164
        let win = BrowserWindowTracker.getTopWindow();
1165
        win.BrowserSearch.recordSearchInTelemetry(engine, "urlbar");
1166
        break;
1167
      case "browser-search-engine-modified":
1168
1169
1170
1171
        // 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;
1172
1173
1174
          let pref = Services.prefs.getStringPref(
            "browser.search.hiddenOneOffs"
          );
1175
1176
          let hiddenList = pref ? pref.split(",") : [];
          hiddenList = hiddenList.filter(x => x !== engineName);
1177
1178
1179
1180
          Services.prefs.setStringPref(
            "browser.search.hiddenOneOffs",
            hiddenList.join(",")
          );
1181
        }
1182
        break;
1183
1184
1185
      case "flash-plugin-hang":
        this._handleFlashHang();
        break;
1186
      case "xpi-signature-changed":
1187
        let disabledAddons = JSON.parse(data).disabled;
1188
1189
1190
1191
        let addons = await AddonManager.getAddonsByIDs(disabledAddons);
        if (addons.some(addon => addon)) {
          this._notifyUnsignedAddonsDisabled();
        }
1192
        break;
1193
1194
1195
      case "sync-ui-state:update":
        this._updateFxaBadges();
        break;
1196
1197
1198
1199
1200
1201
1202
1203
      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.
1204
        PdfJs.init(this._isNewProfile);
1205
        break;
1206
      case "shield-init-complete":
1207
        this._shieldInitComplete = true;
1208
        break;
1209
1210
1211
    }
  },

1212
  // initialization (called on application startup)
1213
  _init: function BG__init() {
1214
    let os = Services.obs;
1215
1216
1217
1218
1219
1220
1221
    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");