BrowserGlue.jsm 142 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
25
26
27
28
ChromeUtils.defineModuleGetter(
  this,
  "CustomizableUI",
  "resource:///modules/CustomizableUI.jsm"
);

29
30
31
32
33
34
35
XPCOMUtils.defineLazyServiceGetter(
  this,
  "PushService",
  "@mozilla.org/push/Service;1",
  "nsIPushService"
);

36
37
const PREF_PDFJS_ENABLED_CACHE_STATE = "pdfjs.enabledCache.state";

38
39
40
41
42
/**
 * 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
 */
43
let ACTORS = {
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  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 },
      },
    },
    matches: ["about:logins", "about:logins?*"],
  },

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

88
89
90
91
92
93
94
95
  BrowserTab: {
    parent: {
      moduleURI: "resource:///actors/BrowserTabParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/BrowserTabChild.jsm",

      events: {
96
97
        DOMWindowCreated: {},
        MozAfterPaint: {},
98
99
100
101
102
103
        "MozDOMPointerLock:Entered": {},
        "MozDOMPointerLock:Exited": {},
      },
    },
  },

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
  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,
  },

119
120
121
122
123
124
125
126
127
128
129
130
131
132
  // Collects description and icon information from meta tags.
  ContentMeta: {
    parent: {
      moduleURI: "resource:///actors/ContentMetaParent.jsm",
    },

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

133
134
135
136
137
138
139
140
  ContextMenu: {
    parent: {
      moduleURI: "resource:///actors/ContextMenuParent.jsm",
    },

    child: {
      moduleURI: "resource:///actors/ContextMenuChild.jsm",
      events: {
141
        contextmenu: { mozSystemGroup: true },
142
143
144
145
146
147
      },
    },

    allFrames: true,
  },

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
  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,
  },

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
  FormValidation: {
    parent: {
      moduleURI: "resource:///actors/FormValidationParent.jsm",
    },

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

    allFrames: true,
  },

183
184
185
186
187
188
189
190
191
192
193
194
195
196
  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",
197
198
      "chrome://browser/content/places/historySidebar.xhtml",
      "chrome://browser/content/places/bookmarksSidebar.xhtml",
199
200
201
    ],
  },

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  LinkHandler: {
    parent: {
      moduleURI: "resource:///actors/LinkHandlerParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/LinkHandlerChild.jsm",
      events: {
        DOMHeadElementParsed: {},
        DOMLinkAdded: {},
        DOMLinkChanged: {},
        pageshow: {},
        pagehide: {},
      },
    },
  },

218
219
220
221
222
223
224
  NetError: {
    parent: {
      moduleURI: "resource:///actors/NetErrorParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/NetErrorChild.jsm",
      events: {
225
        DOMWindowCreated: {},
226
227
228
229
230
231
232
233
        click: {},
      },
    },

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

234
235
236
237
238
239
240
241
  PageInfo: {
    child: {
      moduleURI: "resource:///actors/PageInfoChild.jsm",
    },

    allFrames: true,
  },

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
  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: ["*://*/*"],
    allFrames: true,
  },

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  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,
  },

280
281
282
283
284
285
286
287
  Prompt: {
    parent: {
      moduleURI: "resource:///actors/PromptParent.jsm",
    },

    allFrames: true,
  },

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
  ShieldFrame: {
    parent: {
      moduleURI: "resource://normandy-content/ShieldFrameParent.jsm",
    },
    child: {
      moduleURI: "resource://normandy-content/ShieldFrameChild.jsm",
      events: {
        pageshow: {},
        pagehide: {},
        ShieldPageEvent: { wantUntrusted: true },
      },
    },
    matches: ["about:studies"],
  },

303
304
305
306
307
308
309
  SwitchDocumentDirection: {
    child: {
      moduleURI: "resource:///actors/SwitchDocumentDirectionChild.jsm",
    },

    allFrames: true,
  },
310

311
312
313
314
315
316
317
318
319
320
321
  SiteSpecificBrowser: {
    parent: {
      moduleURI: "resource:///actors/SiteSpecificBrowserParent.jsm",
    },
    child: {
      moduleURI: "resource:///actors/SiteSpecificBrowserChild.jsm",
    },

    allFrames: true,
  },

322
323
324
325
326
327
328
329
330
331
332
  UITour: {
    parent: {
      moduleURI: "resource:///modules/UITourParent.jsm",
    },
    child: {
      moduleURI: "resource:///modules/UITourChild.jsm",
      events: {
        mozUITour: { wantUntrusted: true },
      },
    },
  },
333
334
335
336
337
338
339
340
341
342
343

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

    allFrames: true,
  },
344
345
346
};

let LEGACY_ACTORS = {
347
348
349
350
351
  AboutReader: {
    child: {
      module: "resource:///actors/AboutReaderChild.jsm",
      group: "browsers",
      events: {
352
353
354
355
        AboutReaderContentLoaded: { wantUntrusted: true },
        DOMContentLoaded: {},
        pageshow: { mozSystemGroup: true },
        pagehide: { mozSystemGroup: true },
356
      },
357
      messages: ["Reader:ToggleReaderMode", "Reader:PushState"],
358
359
360
    },
  },

361
362
363
364
  ContentSearch: {
    child: {
      module: "resource:///actors/ContentSearchChild.jsm",
      group: "browsers",
365
366
367
368
369
370
371
      matches: [
        "about:home",
        "about:newtab",
        "about:welcome",
        "about:privatebrowsing",
        "chrome://mochitests/content/*",
      ],
372
      events: {
373
        ContentSearchClient: { capture: true, wantUntrusted: true },
374
      },
375
      messages: ["ContentSearch"],
376
377
378
    },
  },

379
380
381
382
  OfflineApps: {
    child: {
      module: "resource:///actors/OfflineAppsChild.jsm",
      events: {
383
        MozApplicationManifest: {},
384
      },
385
      messages: ["OfflineApps:StartFetching"],
386
387
388
    },
  },

389
390
391
392
393
  SearchTelemetry: {
    child: {
      module: "resource:///actors/SearchTelemetryChild.jsm",
      events: {
        DOMContentLoaded: {},
394
        pageshow: { mozSystemGroup: true },
395
396
397
398
      },
    },
  },

399
400
401
402
403
404
405
  URIFixup: {
    child: {
      module: "resource:///actors/URIFixupChild.jsm",
      group: "browsers",
      observers: ["keyword-uri-fixup"],
    },
  },
406
407
};

408
(function earlyBlankFirstPaint() {
409
410
411
412
  if (
    AppConstants.platform == "macosx" ||
    !Services.prefs.getBoolPref("browser.startup.blankWindow", false)
  ) {
413
    return;
414
  }
415

416
417
  // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
  // using a non-default theme.
418
419
420
421
422
423
  if (
    Services.prefs.getCharPref(
      "extensions.activeThemeID",
      "default-theme@mozilla.org"
    ) != "default-theme@mozilla.org"
  ) {
424
    return;
425
  }
426

427
  let store = Services.xulStore;
428
  let getValue = attr =>
429
    store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
430
431
432
433
  let width = getValue("width");
  let height = getValue("height");

  // The clean profile case isn't handled yet. Return early for now.
434
  if (!width || !height) {
435
    return;
436
  }
437
438
439

  let browserWindowFeatures =
    "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
440
    "location,toolbar,personalbar";
441
442
443
444
445
446
447
  let win = Services.ww.openWindow(
    null,
    "about:blank",
    null,
    browserWindowFeatures,
    null
  );
448
449

  // Hide the titlebar if the actual browser window will draw in it.
450
451
452
453
  let hiddenTitlebar = Services.prefs.getBoolPref(
    "browser.tabs.drawInTitlebar",
    win.matchMedia("(-moz-gtk-csd-hide-titlebar-by-default)").matches
  );
454
  if (hiddenTitlebar) {
455
    win.windowUtils.setChromeMargin(0, 2, 2, 2);
456
457
  }

458
459
460
  let docElt = win.document.documentElement;
  docElt.setAttribute("screenX", getValue("screenX"));
  docElt.setAttribute("screenY", getValue("screenY"));
461
462
463
464
465
466

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

467
468
469
    // 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.
470
    let appWin = win.docShell.treeOwner
471
      .QueryInterface(Ci.nsIInterfaceRequestor)
472
473
474
      .getInterface(Ci.nsIAppWindow);
    height -= appWin.outerToInnerHeightDifferenceInCSSPixels;
    width -= appWin.outerToInnerWidthDifferenceInCSSPixels;
475
476
477
478
479
480
481
482
    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);
  }

483
484
485
486
  // 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");

487
488
489
  // The window becomes visible after OnStopRequest, so make this happen now.
  win.stop();

490
491
492
  let { TelemetryTimestamps } = ChromeUtils.import(
    "resource://gre/modules/TelemetryTimestamps.jsm"
  );
493
  TelemetryTimestamps.add("blankWindowShown");
494
495
})();

496
497
498
499
XPCOMUtils.defineLazyGetter(
  this,
  "WeaveService",
  () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
500
);
501

502
// lazy module getters
503

504
XPCOMUtils.defineLazyModuleGetters(this, {
505
506
507
508
  AboutPrivateBrowsingHandler:
    "resource:///modules/aboutpages/AboutPrivateBrowsingHandler.jsm",
  AboutProtectionsHandler:
    "resource:///modules/aboutpages/AboutProtectionsHandler.jsm",
509
510
511
  AddonManager: "resource://gre/modules/AddonManager.jsm",
  AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
512
  Blocklist: "resource://gre/modules/Blocklist.jsm",
513
514
515
  BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.jsm",
  BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.jsm",
  BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
516
  BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
517
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
518
519
  ContextualIdentityService:
    "resource://gre/modules/ContextualIdentityService.jsm",
520
  Corroborate: "resource://gre/modules/Corroborate.jsm",
521
  Discovery: "resource:///modules/Discovery.jsm",
522
  ExtensionsUI: "resource:///modules/ExtensionsUI.jsm",
523
  FirefoxMonitor: "resource:///modules/FirefoxMonitor.jsm",
524
  FxAccounts: "resource://gre/modules/FxAccounts.jsm",
525
  HomePage: "resource:///modules/HomePage.jsm",
526
  Integration: "resource://gre/modules/Integration.jsm",
527
  LoginBreaches: "resource:///modules/LoginBreaches.jsm",
528
  LiveBookmarkMigrator: "resource:///modules/LiveBookmarkMigrator.jsm",
529
  NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
530
  Normandy: "resource://normandy/Normandy.jsm",
531
  ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
532
533
534
535
536
537
538
539
540
541
  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",
542
  PublicSuffixList: "resource://gre/modules/netwerk-dns/PublicSuffixList.jsm",
543
  RemoteSettings: "resource://services-settings/remote-settings.js",
544
545
  RemoteSecuritySettings:
    "resource://gre/modules/psm/RemoteSecuritySettings.jsm",
546
  RFPHelper: "resource://gre/modules/RFPHelper.jsm",
547
  SafeBrowsing: "resource://gre/modules/SafeBrowsing.jsm",
548
  Sanitizer: "resource:///modules/Sanitizer.jsm",
549
  SaveToPocket: "chrome://pocket/content/SaveToPocket.jsm",
550
  SearchTelemetry: "resource:///modules/SearchTelemetry.jsm",
551
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.jsm",
552
553
554
  SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
  ShellService: "resource:///modules/ShellService.jsm",
  TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
555
  TabUnloader: "resource:///modules/TabUnloader.jsm",
556
  TRRRacer: "resource:///modules/TRRPerformance.jsm",
557
558
559
560
  UIState: "resource://services-sync/UIState.jsm",
  WebChannel: "resource://gre/modules/WebChannel.jsm",
  WindowsRegistry: "resource://gre/modules/WindowsRegistry.jsm",
});
561

562
563
// eslint-disable-next-line no-unused-vars
XPCOMUtils.defineLazyModuleGetters(this, {
564
  AboutLoginsParent: "resource:///modules/AboutLoginsParent.jsm",
565
  AsyncPrefs: "resource://gre/modules/AsyncPrefs.jsm",
566
  PluginManager: "resource:///actors/PluginParent.jsm",
567
568
569
  ReaderParent: "resource:///modules/ReaderParent.jsm",
});

570
571
572
573
574
/**
 * 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.
 */

575
576
let initializedModules = {};

577
[
578
579
580
581
582
  [
    "ContentPrefServiceParent",
    "resource://gre/modules/ContentPrefServiceParent.jsm",
    "alwaysInit",
  ],
583
  ["ContentSearch", "resource:///modules/ContentSearch.jsm", "init"],
584
  ["UpdateListener", "resource://gre/modules/UpdateListener.jsm", "init"],
585
].forEach(([name, resource, init]) => {
586
  XPCOMUtils.defineLazyGetter(this, name, () => {
587
    ChromeUtils.import(resource, initializedModules);
588
589
590
    initializedModules[name][init]();
    return initializedModules[name];
  });
591
});
592

593
if (AppConstants.MOZ_CRASHREPORTER) {
594
595
596
  XPCOMUtils.defineLazyModuleGetters(this, {
    UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
  });
597
}
598

599
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
600
601
602
  return Services.strings.createBundle(
    "chrome://branding/locale/brand.properties"
  );
603
604
605
});

XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
606
607
608
  return Services.strings.createBundle(
    "chrome://browser/locale/browser.properties"
  );
609
610
});

611
XPCOMUtils.defineLazyGetter(this, "gTabbrowserBundle", function() {
612
613
614
  return Services.strings.createBundle(
    "chrome://browser/locale/tabbrowser.properties"
  );
615
616
});

617
618
619
const global = this;

const listeners = {
620
621
622
623
624
  observers: {
    "update-staged": ["UpdateListener"],
    "update-downloaded": ["UpdateListener"],
    "update-available": ["UpdateListener"],
    "update-error": ["UpdateListener"],
625
626
    "gmp-plugin-crash": ["PluginManager"],
    "plugin-crashed": ["PluginManager"],
627
628
  },

629
  ppmm: {
630
631
632
633
634
    // 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
635
636
637
638
639

    // 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
640
641
642
  },

  mm: {
643
    "AboutLogins:CreateLogin": ["AboutLoginsParent"],
644
    "AboutLogins:DeleteLogin": ["AboutLoginsParent"],
645
    "AboutLogins:DismissBreachAlert": ["AboutLoginsParent"],
646
    "AboutLogins:HideFooter": ["AboutLoginsParent"],
647
    "AboutLogins:Import": ["AboutLoginsParent"],
648
    "AboutLogins:MasterPasswordRequest": ["AboutLoginsParent"],
649
    "AboutLogins:OpenFAQ": ["AboutLoginsParent"],
650
    "AboutLogins:GetHelp": ["AboutLoginsParent"],
651
    "AboutLogins:OpenPreferences": ["AboutLoginsParent"],
652
653
    "AboutLogins:OpenMobileAndroid": ["AboutLoginsParent"],
    "AboutLogins:OpenMobileIos": ["AboutLoginsParent"],
654
    "AboutLogins:OpenSite": ["AboutLoginsParent"],
655
    "AboutLogins:SortChanged": ["AboutLoginsParent"],
656
    "AboutLogins:Subscribe": ["AboutLoginsParent"],
657
658
    "AboutLogins:SyncEnable": ["AboutLoginsParent"],
    "AboutLogins:SyncOptions": ["AboutLoginsParent"],
659
    "AboutLogins:UpdateLogin": ["AboutLoginsParent"],
660
    ContentSearch: ["ContentSearch"],
661
662
    "Reader:FaviconRequest": ["ReaderParent"],
    "Reader:UpdateReaderButton": ["ReaderParent"],
663
664
  },

665
666
667
668
669
670
671
672
673
674
  observe(subject, topic, data) {
    for (let module of this.observers[topic]) {
      try {
        global[module].observe(subject, topic, data);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  },

675
  receiveMessage(modules, data) {
676
    let val;
677
678
    for (let module of modules[data.name]) {
      try {
679
        val = global[module].receiveMessage(data) || val;
680
681
682
683
      } catch (e) {
        Cu.reportError(e);
      }
    }
684
    return val;
685
686
687
  },

  init() {
688
689
690
691
    for (let observer of Object.keys(this.observers)) {
      Services.obs.addObserver(this, observer);
    }

692
693
694
695
696
697
698
699
700
    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);
    }
701
  },
702
703
};

704
// Seconds of idle before trying to create a bookmarks backup.
705
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
706
707
708
709
710
// 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.
711
const BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS = 3;
712
713
// Seconds of idle time before the late idle tasks will be scheduled.
const LATE_TASKS_IDLE_TIME_SEC = 20;
714
715
// Time after we stop tracking startup crashes.
const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
716

717
718
719
720
721
/*
 * 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";
722
723

function BrowserGlue() {
724
725
726
727
728
729
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "_idleService",
    "@mozilla.org/widget/idleservice;1",
    "nsIIdleService"
  );
730

731
  XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
732
733
734
735
736
    const { DistributionCustomizer } = ChromeUtils.import(
      "resource:///modules/distribution.js"
    );
    return new DistributionCustomizer();
  });
737

738
739
740
741
742
743
  XPCOMUtils.defineLazyServiceGetter(
    this,
    "AlertsService",
    "@mozilla.org/alerts-service;1",
    "nsIAlertsService"
  );
744

745
746
747
748
  this._init();
}

BrowserGlue.prototype = {
749
  _saveSession: false,
750
  _migrationImportsDefaultBookmarks: false,
751
  _placesBrowserInitComplete: false,
752
  _isNewProfile: undefined,
753

754
  _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
755
    if (!this._saveSession && !aForce) {
756
      return;
757
    }
758

759
    if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
760
761
762
763
      Services.prefs.setBoolPref(
        "browser.sessionstore.resume_session_once",
        true
      );
764
    }
765
766
767
768

    // 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.
769
    Services.prefs.savePrefFile(null);
770
771
  },

772
773
774
  _setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
    // Assume that a non-zero value for services.sync.autoconnectDelay should override
    if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
775
776
777
      let prefDelay = Services.prefs.getIntPref(
        "services.sync.autoconnectDelay"
      );
778

779
      if (prefDelay > 0) {
780
        return;
781
      }
782
783
784
785
786
    }

    // delays are in seconds
    const MAX_DELAY = 300;
    let delay = 3;
787
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
788
789
790
791
792
      // 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;
      }
793
      delay += win.gBrowser.tabs.length;
794
795
796
    }
    delay = delay <= MAX_DELAY ? delay : MAX_DELAY;

797
    const { Weave } = ChromeUtils.import("resource://services-sync/main.js");
798
    Weave.Service.scheduler.delayedAutoConnect(delay);
799
800
  },

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

For faster browsing, not all history is shown. View entire blame