BrowserGlue.jsm 131 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
  AboutReader: {
    child: {
      module: "resource:///actors/AboutReaderChild.jsm",
      group: "browsers",
      events: {
        "AboutReaderContentLoaded": {wantUntrusted: true},
        "DOMContentLoaded": {},
26
27
        "pageshow": {mozSystemGroup: true},
        "pagehide": {mozSystemGroup: true},
28
29
30
31
32
33
34
35
      },
      messages: [
        "Reader:ToggleReaderMode",
        "Reader:PushState",
      ],
    },
  },

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  BlockedSite: {
    child: {
      module: "resource:///actors/BlockedSiteChild.jsm",
      events: {
        "AboutBlockedLoaded": {wantUntrusted: true},
        "click": {},
      },
      matches: ["about:blocked?*"],
      allFrames: true,
      messages: [
        "DeceptiveBlockedDetails",
      ],
    },
  },

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  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",
      ],
    },
  },
74

75
76
77
78
79
  ClickHandler: {
    child: {
      module: "resource:///actors/ClickHandlerChild.jsm",
      events: {
        "click": {capture: true, mozSystemGroup: true},
80
      },
81
82
83
    },
  },

84
85
86
87
88
89
90
91
92
  ContextMenu: {
    child: {
      module: "resource:///actors/ContextMenuChild.jsm",
      events: {
        "contextmenu": {mozSystemGroup: true},
      },
    },
  },

93
94
95
96
  ContentSearch: {
    child: {
      module: "resource:///actors/ContentSearchChild.jsm",
      group: "browsers",
97
      matches: ["about:home", "about:newtab", "about:welcome", "about:privatebrowsing",
98
99
100
101
102
103
                "chrome://mochitests/content/*"],
      events: {
        "ContentSearchClient": {capture: true, wantUntrusted: true},
      },
      messages: [
        "ContentSearch",
104
      ],
105
106
107
    },
  },

108
109
110
111
112
113
114
115
116
117
118
119
120
121
  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",
122
      ],
123
124
125
    },
  },

126
  FormValidation: {
127
    child: {
128
      module: "resource:///actors/FormValidationChild.jsm",
129
130
131
132
133
134
      events: {
        "MozInvalidForm": {},
      },
    },
  },

135
136
137
138
139
140
141
142
143
144
145
  LightWeightThemeInstall: {
    child: {
      module: "resource:///actors/LightWeightThemeInstallChild.jsm",
      events: {
        "InstallBrowserTheme": {wantUntrusted: true},
        "PreviewBrowserTheme": {wantUntrusted: true},
        "ResetBrowserThemePreview": {wantUntrusted: true},
      },
    },
  },

146
147
148
149
150
151
152
153
154
155
  LightweightTheme: {
    child: {
      module: "resource:///actors/LightweightThemeChild.jsm",
      matches: ["about:home", "about:newtab", "about:welcome"],
      events: {
        "pageshow": {mozSystemGroup: true},
      },
    },
  },

156
157
158
159
160
161
162
163
164
165
166
167
168
  LinkHandler: {
    child: {
      module: "resource:///actors/LinkHandlerChild.jsm",
      events: {
        "DOMHeadElementParsed": {},
        "DOMLinkAdded": {},
        "DOMLinkChanged": {},
        "pageshow": {},
        "pagehide": {},
      },
    },
  },

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
  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",
      ],
    },
  },

188
189
190
191
192
193
194
195
196
197
198
199
  OfflineApps: {
    child: {
      module: "resource:///actors/OfflineAppsChild.jsm",
      events: {
        "MozApplicationManifest": {},
      },
      messages: [
        "OfflineApps:StartFetching",
      ],
    },
  },

200
201
202
203
204
  PageInfo: {
    child: {
      module: "resource:///actors/PageInfoChild.jsm",
      messages: ["PageInfo:getData"],
    },
205
206
  },

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

  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",
      ],
    },
  },
249

250
251
252
253
254
255
256
257
258
259
  RFPHelper: {
    child: {
      module: "resource:///actors/RFPHelperChild.jsm",
      group: "browsers",
      events: {
        "resize": {},
      },
    },
  },

260
261
262
263
264
265
266
267
268
269
  SearchTelemetry: {
    child: {
      module: "resource:///actors/SearchTelemetryChild.jsm",
      events: {
        DOMContentLoaded: {},
        "pageshow": {mozSystemGroup: true},
      },
    },
  },

270
271
272
273
274
275
276
277
278
279
  ShieldFrame: {
    child: {
      module: "resource://normandy-content/ShieldFrameChild.jsm",
      events: {
        "ShieldPageEvent": {wantUntrusted: true},
      },
      matches: ["about:studies"],
    },
  },

280
281
282
283
284
285
286
287
288
289
  UITour: {
    child: {
      module: "resource:///modules/UITourChild.jsm",
      events: {
        "mozUITour": {wantUntrusted: true},
      },
      permissions: ["uitour"],
    },
  },

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

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

312
313
314
315
(function earlyBlankFirstPaint() {
  if (!Services.prefs.getBoolPref("browser.startup.blankWindow", false))
    return;

316
317
318
319
320
321
  // Until bug 1450626 and bug 1488384 are fixed, skip the blank window when
  // using a non-default theme.
  if (Services.prefs.getCharPref("lightweightThemes.selectedThemeID", "") !=
        "default-theme@mozilla.org")
    return;

322
  let store = Services.xulStore;
323
  let getValue = attr =>
324
    store.getValue(AppConstants.BROWSER_CHROME_URL, "main-window", attr);
325
326
327
328
329
330
331
332
333
  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," +
334
    "location,toolbar,personalbar";
335
336
337
338
  let win = Services.ww.openWindow(null, "about:blank", null,
                                   browserWindowFeatures, null);

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

346
347
348
  let docElt = win.document.documentElement;
  docElt.setAttribute("screenX", getValue("screenX"));
  docElt.setAttribute("screenY", getValue("screenY"));
349
350
351
352
353
354

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

355
356
357
358
359
360
361
362
    // 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;
363
364
365
366
367
368
369
370
    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);
  }

371
372
373
374
  // 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");

375
376
377
  // The window becomes visible after OnStopRequest, so make this happen now.
  win.stop();

378
  let { TelemetryTimestamps } =
379
    ChromeUtils.import("resource://gre/modules/TelemetryTimestamps.jsm");
380
  TelemetryTimestamps.add("blankWindowShown");
381
382
})();

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

390
// lazy module getters
391

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

446
447
448
449
450
451
452
453
454
455
456
// 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",
});

457
/* global ContentPrefServiceParent:false, ContentSearch:false,
458
          UpdateListener:false, webrtcUI:false */
459

460
461
462
463
464
/**
 * 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.
 */

465
466
let initializedModules = {};

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

480
if (AppConstants.MOZ_CRASHREPORTER) {
481
482
483
484
  XPCOMUtils.defineLazyModuleGetters(this, {
    PluginCrashReporter: "resource:///modules/ContentCrashHandlers.jsm",
    UnsubmittedCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
  });
485
}
486

487
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
488
  return Services.strings.createBundle("chrome://branding/locale/brand.properties");
489
490
491
});

XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
492
  return Services.strings.createBundle("chrome://browser/locale/browser.properties");
493
494
});

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

499
500
501
const global = this;

const listeners = {
502
503
504
505
506
507
508
  observers: {
    "update-staged": ["UpdateListener"],
    "update-downloaded": ["UpdateListener"],
    "update-available": ["UpdateListener"],
    "update-error": ["UpdateListener"],
  },

509
  ppmm: {
510
511
512
513
514
    // 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
515
516
517
518
519
520

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

521
522
523
524
525
    "webrtc:UpdateGlobalIndicators": ["webrtcUI"],
    "webrtc:UpdatingIndicators": ["webrtcUI"],
  },

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

552
553
554
555
556
557
558
559
560
561
  observe(subject, topic, data) {
    for (let module of this.observers[topic]) {
      try {
        global[module].observe(subject, topic, data);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  },

562
  receiveMessage(modules, data) {
563
    let val;
564
565
    for (let module of modules[data.name]) {
      try {
566
        val = global[module].receiveMessage(data) || val;
567
568
569
570
      } catch (e) {
        Cu.reportError(e);
      }
    }
571
    return val;
572
573
574
  },

  init() {
575
576
577
578
    for (let observer of Object.keys(this.observers)) {
      Services.obs.addObserver(this, observer);
    }

579
580
581
582
583
584
585
586
587
    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);
    }
588
  },
589
590
};

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

604
605
606
607
608
/*
 * 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";
609
610

function BrowserGlue() {
611
612
613
614
  XPCOMUtils.defineLazyServiceGetter(this, "_idleService",
                                     "@mozilla.org/widget/idleservice;1",
                                     "nsIIdleService");

615
  XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
616
                                const {DistributionCustomizer} = ChromeUtils.import("resource:///modules/distribution.js");
617
618
619
                                return new DistributionCustomizer();
                              });

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

622
623
624
625
  this._init();
}

BrowserGlue.prototype = {
626
  _saveSession: false,
627
  _migrationImportsDefaultBookmarks: false,
628
  _placesBrowserInitComplete: false,
629

630
  _setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
631
632
633
    if (!this._saveSession && !aForce)
      return;

634
635
636
    if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
      Services.prefs.setBoolPref("browser.sessionstore.resume_session_once", true);
    }
637
638
639
640

    // 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.
641
    Services.prefs.savePrefFile(null);
642
643
  },

644
645
646
647
648
649
650
651
652
653
654
655
  _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;
656
    for (let win of Services.wm.getEnumerator("navigator:browser")) {
657
658
659
660
661
      // 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;
      }
662
      delay += win.gBrowser.tabs.length;
663
664
665
    }
    delay = delay <= MAX_DELAY ? delay : MAX_DELAY;

666
    const {Weave} = ChromeUtils.import("resource://services-sync/main.js");
667
    Weave.Service.scheduler.delayedAutoConnect(delay);
668
669
  },

670
671
672
673
674
675
  /**
   * Lazily initialize PingCentre
   */
  get pingCentre() {
    const MAIN_TOPIC_ID = "main";
    Object.defineProperty(this, "pingCentre", {
676
      value: new PingCentre({ topic: MAIN_TOPIC_ID }),
677
678
679
680
681
    });
    return this.pingCentre;
  },

  _sendMainPingCentrePing() {
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
    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;
    }

707
    const homePageURL = HomePage.get();
708
709
710
711
712
713
714
715
716
717
    if (homePageURL === "about:home") {
      homePageSetting = 0;
    } else if (homePageURL === "about:blank") {
      homePageSetting = 1;
    } else if (homePageURL.startsWith("moz-extension://")) {
      homePageSetting = 2;
    } else {
      homePageSetting = 3;
    }

718
719
    const payload = {
      event: "AS_ENABLED",
720
      value: newTabSetting | (homePageSetting << 2),
721
    };
722
    const ACTIVITY_STREAM_ID = "activity-stream";
723
724
725
726
    const options = {filter: ACTIVITY_STREAM_ID};
    this.pingCentre.sendPing(payload, options);
  },

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

917
  // initialization (called on application startup)
918
  _init: function BG__init() {
919
    let os = Services.obs;
920
921
922
923
924
925
926
    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");
927
    if (OBSERVE_LASTWINDOW_CLOSE_TOPICS) {
928
929
      os.addObserver(this, "browser-lastwindow-close-requested");
      os.addObserver(this, "browser-lastwindow-close-granted");
930
    }
931
932
933
    os.addObserver(this, "weave:service:ready");
    os.addObserver(this, "fxaccounts:onverified");
    os.addObserver(this, "fxaccounts:device_connected");
934
    os.addObserver(this, "fxaccounts:verify_login");
935
    os.addObserver(this, "fxaccounts:device_disconnected");
936
    os.addObserver(this, "fxaccounts:commands:open-uri");
937
938
939
940
941
942
    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");
943
    os.addObserver(this, "keyword-search");
944
945
946
947
    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");
948
    os.addObserver(this, "sync-ui-state:update");
949
    os.addObserver(this, "handlersvc-store-initialized");
950
    os.addObserver(this, "shield-init-complete");
951

952
953
954
    ActorManagerParent.addActors(ACTORS);
    ActorManagerParent.flush();

955
    this._flashHangCount = 0;
956
    this._firstWindowReady = new Promise(resolve => this._firstWindowLoaded = resolve);
957
958
959
    if (AppConstants.platform == "win") {
      JawsScreenReaderVersionCheck.init();
    }
960
961
962
  },

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

1008
    Services.prefs.removeObserver("privacy.trackingprotection", this._matchCBCategory);
1009
1010
1011
    Services.prefs.removeObserver("urlclassifier.trackingTable", this._matchCBCategory);
    Services.prefs.removeObserver("network.cookie.cookieBehavior", this._matchCBCategory);
    Services.prefs.removeObserver(ContentBlockingCategoriesPrefs.PREF_CB_CATEGORY, this._updateCBCategory);
1012
1013
  },

1014
1015
  // runs on startup, before the first command line handler is invoked
  // (i.e. before the first window is opened)
1016
  _beforeUIStartup: function BG__beforeUIStartup() {
1017
1018
    SessionStartup.init();

1019
1020
1021
1022
1023
1024
1025
    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();
    }
1026

1027
1028
1029
1030
1031
1032
1033
1034
    // 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);

1035
    // check if we're in safe mode
1036
    if (Services.appinfo.inSafeMode) {
1037
      Services.ww.openWindow(null, "chrome://browser/content/safeMode.xul",
1038
                             "_blank", "chrome,centerscreen,modal,resizable=no", null);
1039
    }
1040

1041
    // apply distribution customizations
1042
    this._distributionCustomizer.applyCustomizations();
1043

1044
    // handle any UI migration
1045
    this._migrateUI();
1046

1047
1048
    listeners.init();

1049
    SessionStore.init();