BrowserGlue.jsm 133 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
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");
12

13
14
15
ChromeUtils.defineModuleGetter(this, "ActorManagerParent",
                               "resource://gre/modules/ActorManagerParent.jsm");

16
17
const PREF_PDFJS_ENABLED_CACHE_STATE = "pdfjs.enabledCache.state";

18
let ACTORS = {
19
20
21
22
23
24
25
26
27
28
29
  SubframeCrash: {
    parent: {
      moduleURI: "resource:///actors/SubframeCrashParent.jsm",
    },

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

    allFrames: true,
  },
30
31
32
};

let LEGACY_ACTORS = {
33
34
35
36
37
38
39
  AboutReader: {
    child: {
      module: "resource:///actors/AboutReaderChild.jsm",
      group: "browsers",
      events: {
        "AboutReaderContentLoaded": {wantUntrusted: true},
        "DOMContentLoaded": {},
40
41
        "pageshow": {mozSystemGroup: true},
        "pagehide": {mozSystemGroup: true},
42
43
44
45
46
47
48
49
      },
      messages: [
        "Reader:ToggleReaderMode",
        "Reader:PushState",
      ],
    },
  },

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  BlockedSite: {
    child: {
      module: "resource:///actors/BlockedSiteChild.jsm",
      events: {
        "AboutBlockedLoaded": {wantUntrusted: true},
        "click": {},
      },
      matches: ["about:blocked?*"],
      allFrames: true,
      messages: [
        "DeceptiveBlockedDetails",
      ],
    },
  },

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  BrowserTab: {
    child: {
      module: "resource:///actors/BrowserTabChild.jsm",
      group: "browsers",

      events: {
        "DOMWindowCreated": {once: true},
        "MozAfterPaint": {once: true},
        "MozDOMPointerLock:Entered": {},
        "MozDOMPointerLock:Exited": {},
      },

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

89
90
91
92
93
  ClickHandler: {
    child: {
      module: "resource:///actors/ClickHandlerChild.jsm",
      events: {
        "click": {capture: true, mozSystemGroup: true},
94
        "auxclick": {capture: true, mozSystemGroup: true},
95
      },
96
97
98
    },
  },

99
100
101
102
103
104
105
106
107
  ContextMenu: {
    child: {
      module: "resource:///actors/ContextMenuChild.jsm",
      events: {
        "contextmenu": {mozSystemGroup: true},
      },
    },
  },

108
109
110
111
  ContentSearch: {
    child: {
      module: "resource:///actors/ContentSearchChild.jsm",
      group: "browsers",
112
      matches: ["about:home", "about:newtab", "about:welcome", "about:privatebrowsing",
113
114
115
116
117
118
                "chrome://mochitests/content/*"],
      events: {
        "ContentSearchClient": {capture: true, wantUntrusted: true},
      },
      messages: [
        "ContentSearch",
119
      ],
120
121
122
    },
  },

123
124
125
126
127
128
129
130
131
132
133
134
135
136
  DOMFullscreen: {
    child: {
      module: "resource:///actors/DOMFullscreenChild.jsm",
      group: "browsers",
      events: {
        "MozDOMFullscreen:Request": {},
        "MozDOMFullscreen:Entered": {},
        "MozDOMFullscreen:NewOrigin": {},
        "MozDOMFullscreen:Exit": {},
        "MozDOMFullscreen:Exited": {},
      },
      messages: [
        "DOMFullscreen:Entered",
        "DOMFullscreen:CleanUp",
137
      ],
138
139
140
    },
  },

141
  FormValidation: {
142
    child: {
143
      module: "resource:///actors/FormValidationChild.jsm",
144
145
146
147
148
149
      events: {
        "MozInvalidForm": {},
      },
    },
  },

150
151
152
153
154
155
156
157
158
159
  LightweightTheme: {
    child: {
      module: "resource:///actors/LightweightThemeChild.jsm",
      matches: ["about:home", "about:newtab", "about:welcome"],
      events: {
        "pageshow": {mozSystemGroup: true},
      },
    },
  },

160
161
162
163
164
165
166
167
168
169
170
171
172
  LinkHandler: {
    child: {
      module: "resource:///actors/LinkHandlerChild.jsm",
      events: {
        "DOMHeadElementParsed": {},
        "DOMLinkAdded": {},
        "DOMLinkChanged": {},
        "pageshow": {},
        "pagehide": {},
      },
    },
  },

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
  NetError: {
    child: {
      module: "resource:///actors/NetErrorChild.jsm",
      events: {
        "AboutNetErrorLoad": {wantUntrusted: true},
        "AboutNetErrorOpenCaptivePortal": {wantUntrusted: true},
        "AboutNetErrorSetAutomatic": {wantUntrusted: true},
        "AboutNetErrorResetPreferences": {wantUntrusted: true},
        "click": {},
      },
      matches: ["about:certerror?*", "about:neterror?*"],
      allFrames: true,
      messages: [
        "Browser:CaptivePortalFreed",
        "CertErrorDetails",
      ],
    },
  },

192
193
194
195
196
197
198
199
200
201
202
203
  OfflineApps: {
    child: {
      module: "resource:///actors/OfflineAppsChild.jsm",
      events: {
        "MozApplicationManifest": {},
      },
      messages: [
        "OfflineApps:StartFetching",
      ],
    },
  },

204
205
206
207
208
  PageInfo: {
    child: {
      module: "resource:///actors/PageInfoChild.jsm",
      messages: ["PageInfo:getData"],
    },
209
210
  },

211
212
213
214
215
216
217
218
219
220
  PageStyle: {
    child: {
      module: "resource:///actors/PageStyleChild.jsm",
      group: "browsers",
      events: {
        "pageshow": {},
      },
      messages: [
        "PageStyle:Switch",
        "PageStyle:Disable",
221
      ],
222
223
224
      // 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: ["*://*/*"],
225
226
    },
  },
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

  Plugin: {
    child: {
      module: "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},
      },

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

      observers: [
        "decoder-doctor-notification",
      ],
    },
  },
253

254
255
256
257
258
259
260
261
262
263
  RFPHelper: {
    child: {
      module: "resource:///actors/RFPHelperChild.jsm",
      group: "browsers",
      events: {
        "resize": {},
      },
    },
  },

264
265
266
267
268
269
270
271
272
273
  SearchTelemetry: {
    child: {
      module: "resource:///actors/SearchTelemetryChild.jsm",
      events: {
        DOMContentLoaded: {},
        "pageshow": {mozSystemGroup: true},
      },
    },
  },

274
275
276
277
278
279
280
281
282
283
  ShieldFrame: {
    child: {
      module: "resource://normandy-content/ShieldFrameChild.jsm",
      events: {
        "ShieldPageEvent": {wantUntrusted: true},
      },
      matches: ["about:studies"],
    },
  },

284
285
286
287
288
289
290
291
292
293
  UITour: {
    child: {
      module: "resource:///modules/UITourChild.jsm",
      events: {
        "mozUITour": {wantUntrusted: true},
      },
      permissions: ["uitour"],
    },
  },

294
295
296
297
298
299
300
  URIFixup: {
    child: {
      module: "resource:///actors/URIFixupChild.jsm",
      group: "browsers",
      observers: ["keyword-uri-fixup"],
    },
  },
301
302
303
304
305
306
307
308
309
310
311
312
313

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

316
317
318
319
(function earlyBlankFirstPaint() {
  if (!Services.prefs.getBoolPref("browser.startup.blankWindow", false))
    return;

320
321
  // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
  // using a non-default theme.
322
  if (Services.prefs.getCharPref("extensions.activeThemeID", "default-theme@mozilla.org") !=
323
324
325
        "default-theme@mozilla.org")
    return;

326
  let store = Services.xulStore;
327
  let getValue = attr =>
328
    store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
329
330
331
332
333
334
335
336
337
  let width = getValue("width");
  let height = getValue("height");

  // The clean profile case isn't handled yet. Return early for now.
  if (!width || !height)
    return;

  let browserWindowFeatures =
    "chrome,all,dialog=no,extrachrome,menubar,resizable,scrollbars,status," +
338
    "location,toolbar,personalbar";
339
340
341
342
  let win = Services.ww.openWindow(null, "about:blank", null,
                                   browserWindowFeatures, null);

  // Hide the titlebar if the actual browser window will draw in it.
343
344
345
346
  let hiddenTitlebar =
    Services.prefs.getBoolPref("browser.tabs.drawInTitlebar",
      win.matchMedia("(-moz-gtk-csd-hide-titlebar-by-default)").matches);
  if (hiddenTitlebar) {
347
    win.windowUtils.setChromeMargin(0, 2, 2, 2);
348
349
  }

350
351
352
  let docElt = win.document.documentElement;
  docElt.setAttribute("screenX", getValue("screenX"));
  docElt.setAttribute("screenY", getValue("screenY"));
353
354
355
356
357
358

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

359
360
361
362
363
364
365
366
    // 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
                    .QueryInterface(Ci.nsIInterfaceRequestor)
                    .getInterface(Ci.nsIXULWindow);
    height -= xulWin.outerToInnerHeightDifferenceInCSSPixels;
    width -= xulWin.outerToInnerWidthDifferenceInCSSPixels;
367
368
369
370
371
372
373
374
    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);
  }

375
376
377
378
  // 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");

379
380
381
  // The window becomes visible after OnStopRequest, so make this happen now.
  win.stop();

382
  let { TelemetryTimestamps } =
383
    ChromeUtils.import("resource://gre/modules/TelemetryTimestamps.jsm");
384
  TelemetryTimestamps.add("blankWindowShown");
385
386
})();

387
XPCOMUtils.defineLazyServiceGetters(this, {
388
  aboutNewTabService: ["@mozilla.org/browser/aboutnewtab-service;1", "nsIAboutNewTabService"],
389
});
390
391
392
XPCOMUtils.defineLazyGetter(this, "WeaveService", () =>
  Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject
);
393

394
// lazy module getters
395

396
XPCOMUtils.defineLazyModuleGetters(this, {
397
  AboutPrivateBrowsingHandler: "resource:///modules/aboutpages/AboutPrivateBrowsingHandler.jsm",
398
399
400
401
  AddonManager: "resource://gre/modules/AddonManager.jsm",
  AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
  AutoCompletePopup: "resource://gre/modules/AutoCompletePopup.jsm",
402
  Blocklist: "resource://gre/modules/Blocklist.jsm",
403
404
405
  BookmarkHTMLUtils: "resource://gre/modules/BookmarkHTMLUtils.jsm",
  BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.jsm",
  BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
406
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
407
  ContextualIdentityService: "resource://gre/modules/ContextualIdentityService.jsm",
408
  Corroborate: "resource://gre/modules/Corroborate.jsm",
409
  DateTimePickerParent: "resource://gre/modules/DateTimePickerParent.jsm",
410
  Discovery: "resource:///modules/Discovery.jsm",
411
  ExtensionsUI: "resource:///modules/ExtensionsUI.jsm",
412
  FileSource: "resource://gre/modules/L10nRegistry.jsm",
413
  FxAccounts: "resource://gre/modules/FxAccounts.jsm",
414
  HomePage: "resource:///modules/HomePage.jsm",
415
  HybridContentTelemetry: "resource://gre/modules/HybridContentTelemetry.jsm",
416
  Integration: "resource://gre/modules/Integration.jsm",
417
  L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
418
  LiveBookmarkMigrator: "resource:///modules/LiveBookmarkMigrator.jsm",
419
  NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
420
  Normandy: "resource://normandy/Normandy.jsm",
421
  ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
422
423
424
425
426
  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",
427
  PingCentre: "resource:///modules/PingCentre.jsm",
428
429
430
431
432
  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",
433
  RemoteSettings: "resource://services-settings/remote-settings.js",
434
  RFPHelper: "resource://gre/modules/RFPHelper.jsm",
435
  SafeBrowsing: "resource://gre/modules/SafeBrowsing.jsm",
436
  Sanitizer: "resource:///modules/Sanitizer.jsm",
437
  SaveToPocket: "chrome://pocket/content/SaveToPocket.jsm",
438
  SearchTelemetry: "resource:///modules/SearchTelemetry.jsm",
439
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.jsm",
440
441
442
  SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
  ShellService: "resource:///modules/ShellService.jsm",
  TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
443
  TabUnloader: "resource:///modules/TabUnloader.jsm",
444
445
446
447
448
  UIState: "resource://services-sync/UIState.jsm",
  UITour: "resource:///modules/UITour.jsm",
  WebChannel: "resource://gre/modules/WebChannel.jsm",
  WindowsRegistry: "resource://gre/modules/WindowsRegistry.jsm",
});
449

450
451
452
453
454
455
456
457
458
459
460
// eslint-disable-next-line no-unused-vars
XPCOMUtils.defineLazyModuleGetters(this, {
  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",
});

461
/* global ContentPrefServiceParent:false, ContentSearch:false,
462
          UpdateListener:false, webrtcUI:false */
463

464
465
466
467
468
/**
 * 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.
 */

469
470
let initializedModules = {};

471
[
472
  ["ContentPrefServiceParent", "resource://gre/modules/ContentPrefServiceParent.jsm", "alwaysInit"],
473
  ["ContentSearch", "resource:///modules/ContentSearch.jsm", "init"],
474
  ["UpdateListener", "resource://gre/modules/UpdateListener.jsm", "init"],
475
476
  ["webrtcUI", "resource:///modules/webrtcUI.jsm", "init"],
].forEach(([name, resource, init]) => {
477
  XPCOMUtils.defineLazyGetter(this, name, () => {
478
    ChromeUtils.import(resource, initializedModules);
479
480
481
    initializedModules[name][init]();
    return initializedModules[name];
  });
482
});
483

484
if (AppConstants.MOZ_CRASHREPORTER) {
485
486
487
488
  XPCOMUtils.defineLazyModuleGetters(this, {
    PluginCrashReporter: "resource:///modules/ContentCrashHandlers.jsm",
    UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
  });
489
}
490

491
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
492
  return Services.strings.createBundle("chrome://branding/locale/brand.properties");
493
494
495
});

XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
496
  return Services.strings.createBundle("chrome://browser/locale/browser.properties");
497
498
});

499
500
501
502
XPCOMUtils.defineLazyGetter(this, "gTabbrowserBundle", function() {
  return Services.strings.createBundle("chrome://browser/locale/tabbrowser.properties");
});

503
504
505
const global = this;

const listeners = {
506
507
508
509
510
511
512
  observers: {
    "update-staged": ["UpdateListener"],
    "update-downloaded": ["UpdateListener"],
    "update-available": ["UpdateListener"],
    "update-error": ["UpdateListener"],
  },

513
  ppmm: {
514
515
516
517
518
    // 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
519
520
521
522
523
524

    // 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

525
526
527
528
529
    "webrtc:UpdateGlobalIndicators": ["webrtcUI"],
    "webrtc:UpdatingIndicators": ["webrtcUI"],
  },

  mm: {
530
    "Content:Click": ["ContentClick"],
531
    "ContentSearch": ["ContentSearch"],
532
533
    "FormValidation:ShowPopup": ["FormValidationHandler"],
    "FormValidation:HidePopup": ["FormValidationHandler"],
534
535
    "PictureInPicture:Request": ["PictureInPicture"],
    "PictureInPicture:Close": ["PictureInPicture"],
536
537
    "PictureInPicture:Playing": ["PictureInPicture"],
    "PictureInPicture:Paused": ["PictureInPicture"],
538
    "Prompt:Open": ["RemotePrompt"],
539
540
    "Reader:FaviconRequest": ["ReaderParent"],
    "Reader:UpdateReaderButton": ["ReaderParent"],
541
    // PLEASE KEEP THIS LIST IN SYNC WITH THE MOBILE LISTENERS IN BrowserCLH.js
542
543
544
545
546
547
    "PasswordManager:findLogins": ["LoginManagerParent"],
    "PasswordManager:findRecipes": ["LoginManagerParent"],
    "PasswordManager:onFormSubmit": ["LoginManagerParent"],
    "PasswordManager:autoCompleteLogins": ["LoginManagerParent"],
    "PasswordManager:removeLogin": ["LoginManagerParent"],
    "PasswordManager:insecureLoginFormPresent": ["LoginManagerParent"],
548
    "PasswordManager:OpenPreferences": ["LoginManagerParent"],
549
    // PLEASE KEEP THIS LIST IN SYNC WITH THE MOBILE LISTENERS IN BrowserCLH.js
550
551
552
553
554
555
556
557
    "rtcpeer:CancelRequest": ["webrtcUI"],
    "rtcpeer:Request": ["webrtcUI"],
    "webrtc:CancelRequest": ["webrtcUI"],
    "webrtc:Request": ["webrtcUI"],
    "webrtc:StopRecording": ["webrtcUI"],
    "webrtc:UpdateBrowserIndicators": ["webrtcUI"],
  },

558
559
560
561
562
563
564
565
566
567
  observe(subject, topic, data) {
    for (let module of this.observers[topic]) {
      try {
        global[module].observe(subject, topic, data);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  },

568
  receiveMessage(modules, data) {
569
    let val;
570
571
    for (let module of modules[data.name]) {
      try {
572
        val = global[module].receiveMessage(data) || val;
573
574
575
576
      } catch (e) {
        Cu.reportError(e);
      }
    }
577
    return val;
578
579
580
  },

  init() {
581
582
583
584
    for (let observer of Object.keys(this.observers)) {
      Services.obs.addObserver(this, observer);
    }

585
586
587
588
589
590
591
592
593
    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);
    }
594
  },
595
596
};

597
// Seconds of idle before trying to create a bookmarks backup.
598
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
599
600
601
602
603
// 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.
604
const BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS = 3;
605
606
// Seconds of idle time before the late idle tasks will be scheduled.
const LATE_TASKS_IDLE_TIME_SEC = 20;
607
608
// Time after we stop tracking startup crashes.
const STARTUP_CRASHES_END_DELAY_MS = 30 * 1000;
609

610
611
612
613
614
/*
 * 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";
615
616

function BrowserGlue() {
617
618
619
620
  XPCOMUtils.defineLazyServiceGetter(this, "_idleService",
                                     "@mozilla.org/widget/idleservice;1",
                                     "nsIIdleService");

621
  XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
622
                                const {DistributionCustomizer} = ChromeUtils.import("resource:///modules/distribution.js");
623
624
625
                                return new DistributionCustomizer();
                              });

626
  XPCOMUtils.defineLazyServiceGetter(this, "AlertsService", "@mozilla.org/alerts-service;1", "nsIAlertsService");
627

628
629
630
631
  this._init();
}

BrowserGlue.prototype = {
632
  _saveSession: false,
633
  _migrationImportsDefaultBookmarks: false,
634
  _placesBrowserInitComplete: false,
635

636
  _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
637
638
639
    if (!this._saveSession && !aForce)
      return;

640
641
642
    if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
      Services.prefs.setBoolPref("browser.sessionstore.resume_session_once", true);
    }
643
644
645
646

    // 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.
647
    Services.prefs.savePrefFile(null);
648
649
  },

650
651
652
653
654
655
656
657
658
659
660
661
  _setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
    // Assume that a non-zero value for services.sync.autoconnectDelay should override
    if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
      let prefDelay = Services.prefs.getIntPref("services.sync.autoconnectDelay");

      if (prefDelay > 0)
        return;
    }

    // delays are in seconds
    const MAX_DELAY = 300;
    let delay = 3;
662
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
663
664
665
666
667
      // 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;
      }
668
      delay += win.gBrowser.tabs.length;
669
670
671
    }
    delay = delay <= MAX_DELAY ? delay : MAX_DELAY;

672
    const {Weave} = ChromeUtils.import("resource://services-sync/main.js");
673
    Weave.Service.scheduler.delayedAutoConnect(delay);
674
675
  },

676
677
678
679
680
681
  /**
   * Lazily initialize PingCentre
   */
  get pingCentre() {
    const MAIN_TOPIC_ID = "main";
    Object.defineProperty(this, "pingCentre", {
682
      value: new PingCentre({ topic: MAIN_TOPIC_ID }),
683
684
685
686
687
    });
    return this.pingCentre;
  },

  _sendMainPingCentrePing() {
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    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.
    if (Services.prefs.getBoolPref("browser.newtabpage.enabled") &&
                                   !aboutNewTabService.overridden) {
      newTabSetting = 0;
    } else if (aboutNewTabService.newTabURL.startsWith("moz-extension://")) {
      newTabSetting = 2;
    } else if (!Services.prefs.getBoolPref("browser.newtabpage.enabled")) {
      newTabSetting = 1;
    } else {
      newTabSetting = 3;
    }

713
    const homePageURL = HomePage.get();
714
715
716
717
718
719
720
721
722
723
    if (homePageURL === "about:home") {
      homePageSetting = 0;
    } else if (homePageURL === "about:blank") {
      homePageSetting = 1;
    } else if (homePageURL.startsWith("moz-extension://")) {
      homePageSetting = 2;
    } else {
      homePageSetting = 3;
    }

724
725
    const payload = {
      event: "AS_ENABLED",
726
      value: newTabSetting | (homePageSetting << 2),
727
    };
728
    const ACTIVITY_STREAM_ID = "activity-stream";
729
730
731
732
    const options = {filter: ACTIVITY_STREAM_ID};
    this.pingCentre.sendPing(payload, options);
  },

733
  // nsIObserver implementation
734
  observe: async function BG_observe(subject, topic, data) {
735
    switch (topic) {
736
      case "notifications-open-settings":
737
        this._openPreferences("privacy-permissions");
738
        break;
739
      case "final-ui-startup":
740
        this._beforeUIStartup();
741
        break;
742
      case "browser-delayed-startup-finished":
743
        this._onFirstWindowLoaded(subject);
744
745
        Services.obs.removeObserver(this, "browser-delayed-startup-finished");
        break;
746
      case "sessionstore-windows-restored":
747
        this._onWindowsRestored();
748
        break;
749
750
      case "browser:purge-session-history":
        // reset the console service's error buffer
751
752
        Services.console.logStringMessage(null); // clear the console (in case it's open)
        Services.console.reset();
753
        break;
754
755
756
      case "restart-in-safe-mode":
        this._onSafeModeRestart();
        break;
757
      case "quit-application-requested":
758
        this._onQuitRequest(subject, data);
759
760
        break;
      case "quit-application-granted":
761
        this._onQuitApplicationGranted();
762
        break;
763
      case "browser-lastwindow-close-requested":
764
765
766
767
768
        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");
        }
769
770
        break;
      case "browser-lastwindow-close-granted":
771
772
773
        if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
          this._setPrefToSaveSession();
        }
774
        break;
775
776
777
      case "weave:service:ready":
        this._setSyncAutoconnectDelay();
        break;
778
779
780
      case "fxaccounts:onverified":
        this._showSyncStartedDoorhanger();
        break;
781
782
783
      case "fxaccounts:device_connected":
        this._onDeviceConnected(data);
        break;
784
785
786
      case "fxaccounts:verify_login":
        this._onVerifyLoginNotification(JSON.parse(data));
        break;
787
      case "fxaccounts:device_disconnected":
788
789
790
791
        data = JSON.parse(data);
        if (data.isLocalDevice) {
          this._onDeviceDisconnected();
        }
792
        break;
793
      case "fxaccounts:commands:open-uri":
794
795
      case "weave:engine:clients:display-uris":
        this._onDisplaySyncURIs(subject);
796
        break;
797
      case "session-save":
798
        this._setPrefToSaveSession(true);
799
800
801
        subject.QueryInterface(Ci.nsISupportsPRBool);
        subject.data = true;
        break;
802
      case "places-init-complete":
803
        Services.obs.removeObserver(this, "places-init-complete");
804
805
        if (!this._migrationImportsDefaultBookmarks)
          this._initPlaces(false);
806
        break;
807
      case "idle":
808
        this._backupBookmarks();
809
        break;
810
      case "distribution-customization-complete":
811
        Services.obs.removeObserver(this, "distribution-customization-complete");
812
813
814
        // Customization has finished, we don't need the customizer anymore.
        delete this._distributionCustomizer;
        break;
815
816
      case "browser-glue-test": // used by tests
        if (data == "post-update-notification") {
817
          if (Services.prefs.prefHasUserValue("app.update.postupdate"))
818
            this._showUpdateNotification();
819
        } else if (data == "force-ui-migration") {
820
          this._migrateUI();
821
        } else if (data == "force-distribution-customization") {
822
          this._distributionCustomizer.applyCustomizations();
823
          // To apply distribution bookmarks use "places-init-complete".
824
        } else if (data == "force-places-init") {
825
          this._initPlaces(false);
826
827
        } else if (data == "mock-alerts-service") {
          Object.defineProperty(this, "AlertsService", {
828
            value: subject.wrappedJSObject,
829
          });
830
831
832
833
        } else if (data == "places-browser-init-complete") {
          if (this._placesBrowserInitComplete) {
            Services.obs.notifyObservers(null, "places-browser-init-complete");
          }
834
835
836
837
838
        } else if (data == "migrateMatchBucketsPrefForUI66") {
          this._migrateMatchBucketsPrefForUI66().then(() => {
            Services.obs.notifyObservers(null, "browser-glue-test",
                                         "migrateMatchBucketsPrefForUI66-done");
          });
839
        }
840
        break;
841
842
843
844
845
      case "initial-migration-will-import-default-bookmarks":
        this._migrationImportsDefaultBookmarks = true;
        break;
      case "initial-migration-did-import-default-bookmarks":
        this._initPlaces(true);
846
        break;
847
848
849
      case "handle-xul-text-link":
        let linkHandled = subject.QueryInterface(Ci.nsISupportsPRBool);
        if (!linkHandled.data) {
850
          let win = BrowserWindowTracker.getTopWindow();
851
          if (win) {
852
853
            data = JSON.parse(data);
            let where = win.whereToOpenLink(data);
854
855
856
857
858
            // Preserve legacy behavior of non-modifier left-clicks
            // opening in a new selected tab.
            if (where == "current") {
              where = "tab";
            }
859
            win.openTrustedLinkIn(data.href, where);
860
861
862
863
            linkHandled.data = true;
          }
        }
        break;
864
      case "profile-before-change":
865
866
867
868
         // Any component depending on Places should be finalized in
         // _onPlacesShutdown.  Any component that doesn't need to act after
         // the UI has gone should be finalized in _onQuitApplicationGranted.
        this._dispose();
869
        break;
870
      case "keyword-search":
871
872
        // This notification is broadcast by the docshell when it "fixes up" a
        // URI that it's been asked to load into a keyword search.
873
874
875
876
877
878
        let engine = null;
        try {
          engine = subject.QueryInterface(Ci.nsISearchEngine);
        } catch (ex) {
          Cu.reportError(ex);
        }
879
        let win = BrowserWindowTracker.getTopWindow();
880
        win.BrowserSearch.recordSearchInTelemetry(engine, "urlbar");
881
        break;
882
      case "browser-search-engine-modified":
883
884
885
886
        // 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;
887
          let pref = Services.prefs.getStringPref("browser.search.hiddenOneOffs");
888
889
          let hiddenList = pref ? pref.split(",") : [];
          hiddenList = hiddenList.filter(x => x !== engineName);
890
          Services.prefs.setStringPref("browser.search.hiddenOneOffs", hiddenList.join(","));
891
        }
892
        break;
893
894
895
      case "flash-plugin-hang":
        this._handleFlashHang();
        break;
896
      case "xpi-signature-changed":
897
        let disabledAddons = JSON.parse(data).disabled;
898
899
900
901
        let addons = await AddonManager.getAddonsByIDs(disabledAddons);
        if (addons.some(addon => addon)) {
          this._notifyUnsignedAddonsDisabled();
        }
902
        break;
903
904
905
      case "sync-ui-state:update":
        this._updateFxaBadges();
        break;
906
907
908
909
910
911
912
913
914
915
      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;
916
      case "shield-init-complete":
917
        this._shieldInitComplete = true;
918
919
        this._sendMainPingCentrePing();
        break;
920
921
922
    }
  },

923
  // initialization (called on application startup)
924
  _init: function BG__init() {
925
    let os = Services.obs;
926
927
928
929
930
931
932
    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");
933
    if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
934
935
      os.addObserver(this, "browser-lastwindow-close-requested");
      os.addObserver(this, "browser-lastwindow-close-granted");
936
    }
937
938
939
    os.addObserver(this, "weave:service:ready");
    os.addObserver(this, "fxaccounts:onverified");
    os.addObserver(this, "fxaccounts:device_connected");
940
    os.addObserver(this, "fxaccounts:verify_login");
941
    os.addObserver(this, "fxaccounts:device_disconnected");
942
    os.addObserver(this, "fxaccounts:commands:open-uri");
943
944
945
946
947
948
    os.addObserver(this, "weave:engine:clients:display-uris");
    os.addObserver(this, "session-save");
    os.addObserver(this, "places-init-complete");
    os.addObserver(this, "distribution-customization-complete");
    os.addObserver(this, "handle-xul-text-link");
    os.addObserver(this, "profile-before-change");
949
    os.addObserver(this, "keyword-search");
950
951
952
953
    os.addObserver(this, "browser-search-engine-modified");
    os.addObserver(this, "restart-in-safe-mode");
    os.addObserver(this, "flash-plugin-hang");
    os.addObserver(this, "xpi-signature-changed");
954
    os.addObserver(this, "sync-ui-state:update");
955
    os.addObserver(this, "handlersvc-store-initialized");
956
    os.addObserver(this, "shield-init-complete");
957

958
    ActorManagerParent.addActors(ACTORS);
959
    ActorManagerParent.addLegacyActors(LEGACY_ACTORS);
960
961
    ActorManagerParent.flush();

962
    this._flashHangCount = 0;
963
    this._firstWindowReady = new Promise(resolve => this._firstWindowLoaded = resolve);
964
965
966
    if (AppConstants.platform == "win") {
      JawsScreenReaderVersionCheck.init();
    }
967
968
969
  },

  // cleanup (called on application shutdown)
970
  _dispose: function BG__dispose() {
971
    let os = Services.obs;
972
    os.removeObserver(this, "notifications-open-settings");
973
974
975
976
977
    os.removeObserver(this, "final-ui-startup");
    os.removeObserver(this, "sessionstore-windows-restored");
    os.removeObserver(this, "browser:purge-session-history");
    os.removeObserver(this, "quit-application-requested");
    os.removeObserver(this, "quit-application-granted");
978
    os.removeObserver(this, "restart-in-safe-mode");
979
980
981
982
    if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
      os.removeObserver(this, "browser-lastwindow-close-requested");
      os.removeObserver(this, "browser-lastwindow-close-granted");
    }
983
    os.removeObserver(this, "weave:service:ready");
984
    os.removeObserver(this, "fxaccounts:onverified");
985
    os.removeObserver(this, "fxaccounts:device_connected");
986
    os.removeObserver(this, "fxaccounts:verify_login");
987
    os.removeObserver(this, "fxaccounts:device_disconnected");
988
    os.removeObserver(this, "fxaccounts:commands:open-uri");
989
    os.removeObserver(this, "weave:engine:clients:display-uris");
990
    os.removeObserver(this, "session-save");
991
992
993
994
    if (this._bookmarksBackupIdleTime) {
      this._idleService.removeIdleObserver(this, this._bookmarksBackupIdleTime);
      delete this._bookmarksBackupIdleTime;
    }
995
996
997
998
    if (this._lateTasksIdleObserver) {
      this._idleService.removeIdleObserver(this._lateTasksIdleObserver, LATE_TASKS_IDLE_TIME_SEC);
      delete this._lateTasksIdleObserver;
    }
999
1000
1001
1002
    if (this._gmpInstallManager) {
      this._gmpInstallManager.uninit();
      delete this._gmpInstallManager;
    }
1003
    try {
1004
      os.removeObserver(this, "places-init-complete");
1005
    } catch (ex) { /* Could have been removed already */ }
1006
    os.removeObserver(this, "handle-xul-text-link");
1007
    os.removeObserver(this, "profile-before-change");
1008
    os.removeObserver(this, "keyword-search");
1009
    os.removeObserver(this, "browser-search-engine-modified");
1010
    os.removeObserver(this, "flash-plugin-hang");
1011
    os.removeObserver(this, "xpi-signature-changed");
1012
    os.removeObserver(this, "sync-ui-state:update");
1013
    os.removeObserver(this, "shield-init-complete");
1014

1015
    Services.prefs.removeObserver("permissions.eventTelemetry.enabled", this._togglePermissionPromptTelemetry);
1016
    Services.prefs.removeObserver("privacy.trackingprotection", this._matchCBCategory);
1017
1018
    Services.prefs.removeObserver("network.cookie.cookieBehavior", this._matchCBCategory);
    Services.prefs.removeObserver(ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY, this._updateCBCategory);
1019
1020
    Services.prefs.removeObserver("browser.contentblocking.features.standard", this._setPrefExpectations);
    Services.prefs.removeObserver("browser.contentblocking.features.strict", this._setPrefExpectations);
1021
1022
  },

1023
1024
  // runs on startup, before the first command line handler is invoked
  // (i.e. before the first window is opened)
1025
  _beforeUIStartup: function BG__beforeUIStartup() {
1026
1027
    SessionStartup.init();

1028
1029
1030
1031
1032
1033
1034
    if (Services.prefs.prefHasUserValue(PREF_PDFJS_ENABLED_CACHE_STATE)) {
      Services.ppmm.sharedData.set(
        "pdfjs.enabled",
        Services.prefs.getBoolPref(PREF_PDFJS_ENABLED_CACHE_STATE));
    } else {
      PdfJs.earlyInit();
    }
1035

1036
1037
1038
1039
1040
1041
1042
1043
    // Initialize the default l10n resource sources for L10nRegistry.
    let locales = Services.locale.packagedLocales;
    const greSource = new FileSource("toolkit", locales, "resource://gre/localization/{locale}/");
    L10nRegistry.registerSource(greSource);

    const appSource = new FileSource("app", locales, "resource://app/localization/{locale}/");
    L10nRegistry.registerSource(appSource);

1044
    // check if we're in safe mode
1045
    if (Services.appinfo.inSafeMode) {
1046
      Services.ww.openWindow(null, "chrome://browser/content/safeMode.xul",
1047
                             "_blank", "chrome,centerscreen,modal,resizable=no", null);
mconnor%steelgryphon.com's avatar