summaryrefslogtreecommitdiffstats
path: root/webbrowser/modules/BrowserNewTabPreloader.jsm
blob: 778698fbaa1109905c97f7a2383fb5d20ba0c323 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/* 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/. */

"use strict";

this.EXPORTED_SYMBOLS = ["BrowserNewTabPreloader"];

const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Promise.jsm");

const HTML_NS = "http://www.w3.org/1999/xhtml";
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const XUL_PAGE = "data:application/vnd.mozilla.xul+xml;charset=utf-8,<window%20id='win'/>";
const NEWTAB_URL = "about:newtab";
const PREF_BRANCH = "browser.newtab.";

// The interval between swapping in a preload docShell and kicking off the
// next preload in the background.
const PRELOADER_INTERVAL_MS = 600;
// The initial delay before we start preloading our first new tab page. The
// timer is started after the first 'browser-delayed-startup' has been sent.
const PRELOADER_INIT_DELAY_MS = 5000;
// The number of miliseconds we'll wait after we received a notification that
// causes us to update our list of browsers and tabbrowser sizes. This acts as
// kind of a damper when too many events are occuring in quick succession.
const PRELOADER_UPDATE_DELAY_MS = 3000;

const TOPIC_TIMER_CALLBACK = "timer-callback";
const TOPIC_DELAYED_STARTUP = "browser-delayed-startup-finished";
const TOPIC_XUL_WINDOW_CLOSED = "xul-window-destroyed";

function createTimer(obj, delay) {
  let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.init(obj, delay, Ci.nsITimer.TYPE_ONE_SHOT);
  return timer;
}

function clearTimer(timer) {
  if (timer) {
    timer.cancel();
  }
  return null;
}

this.BrowserNewTabPreloader = {
  init: function Preloader_init() {
    Initializer.start();
  },

  uninit: function Preloader_uninit() {
    Initializer.stop();
    HostFrame.destroy();
    Preferences.uninit();
    HiddenBrowsers.uninit();
  },

  newTab: function Preloader_newTab(aTab) {
    let win = aTab.ownerDocument.defaultView;
    if (win.gBrowser) {
      let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindowUtils);

      let {width, height} = utils.getBoundsWithoutFlushing(win.gBrowser);
      let hiddenBrowser = HiddenBrowsers.get(width, height)
      if (hiddenBrowser) {
        return hiddenBrowser.swapWithNewTab(aTab);
      }
    }

    return false;
  }
};

Object.freeze(BrowserNewTabPreloader);

var Initializer = {
  _timer: null,
  _observing: false,

  start: function Initializer_start() {
    Services.obs.addObserver(this, TOPIC_DELAYED_STARTUP, false);
    this._observing = true;
  },

  stop: function Initializer_stop() {
    this._timer = clearTimer(this._timer);

    if (this._observing) {
      Services.obs.removeObserver(this, TOPIC_DELAYED_STARTUP);
      this._observing = false;
    }
  },

  observe: function Initializer_observe(aSubject, aTopic, aData) {
    if (aTopic == TOPIC_DELAYED_STARTUP) {
      Services.obs.removeObserver(this, TOPIC_DELAYED_STARTUP);
      this._observing = false;
      this._startTimer();
    } else if (aTopic == TOPIC_TIMER_CALLBACK) {
      this._timer = null;
      this._startPreloader();
    }
  },

  _startTimer: function Initializer_startTimer() {
    this._timer = createTimer(this, PRELOADER_INIT_DELAY_MS);
  },

  _startPreloader: function Initializer_startPreloader() {
    Preferences.init();
    if (Preferences.enabled) {
      HiddenBrowsers.init();
    }
  }
};

var Preferences = {
  _enabled: null,
  _branch: null,

  get enabled() {
    if (this._enabled === null) {
      this._enabled = this._branch.getBoolPref("preload") &&
                      !this._branch.prefHasUserValue("url");
    }

    return this._enabled;
  },

  init: function Preferences_init() {
    this._branch = Services.prefs.getBranch(PREF_BRANCH);
    this._branch.addObserver("", this, false);
  },

  uninit: function Preferences_uninit() {
    if (this._branch) {
      this._branch.removeObserver("", this);
      this._branch = null;
    }
  },

  observe: function Preferences_observe() {
    let prevEnabled = this._enabled;
    this._enabled = null;

    if (prevEnabled && !this.enabled) {
      HiddenBrowsers.uninit();
    } else if (!prevEnabled && this.enabled) {
      HiddenBrowsers.init();
    }
  },
};

var HiddenBrowsers = {
  _browsers: null,
  _updateTimer: null,

  _topics: [
    TOPIC_DELAYED_STARTUP,
    TOPIC_XUL_WINDOW_CLOSED
  ],

  init: function () {
    this._browsers = new Map();
    this._updateBrowserSizes();
    this._topics.forEach(t => Services.obs.addObserver(this, t, false));
  },

  uninit: function () {
    if (this._browsers) {
      this._topics.forEach(t => Services.obs.removeObserver(this, t, false));
      this._updateTimer = clearTimer(this._updateTimer);

      for (let [key, browser] of this._browsers) {
        browser.destroy();
      }
      this._browsers = null;
    }
  },

  get: function (width, height) {
    // We haven't been initialized, yet.
    if (!this._browsers) {
      return null;
    }

    let key = width + "x" + height;
    if (!this._browsers.has(key)) {
      // Update all browsers' sizes if we can't find a matching one.
      this._updateBrowserSizes();
    }

    // We should now have a matching browser.
    if (this._browsers.has(key)) {
      return this._browsers.get(key);
    }

    // We should never be here. Return the first browser we find.
    Cu.reportError("NewTabPreloader: no matching browser found after updating");
    for (let [size, browser] of this._browsers) {
      return browser;
    }

    // We should really never be here.
    Cu.reportError("NewTabPreloader: not even a single browser was found?");
    return null;
  },

  observe: function (subject, topic, data) {
    if (topic === TOPIC_TIMER_CALLBACK) {
      this._updateTimer = null;
      this._updateBrowserSizes();
    } else {
      this._updateTimer = clearTimer(this._updateTimer);
      this._updateTimer = createTimer(this, PRELOADER_UPDATE_DELAY_MS);
    }
  },

  _updateBrowserSizes: function () {
    let sizes = this._collectTabBrowserSizes();
    let toRemove = [];

    // Iterate all browsers and check that they
    // each can be assigned to one of the sizes.
    for (let [key, browser] of this._browsers) {
      if (sizes.has(key)) {
        // We already have a browser for that size, great!
        sizes.delete(key);
      } else {
        // This browser is superfluous or needs to be resized.
        toRemove.push(browser);
        this._browsers.delete(key);
      }
    }

    // Iterate all sizes that we couldn't find a browser for.
    for (let [key, {width, height}] of sizes) {
      let browser;
      if (toRemove.length) {
        // Let's just resize one of the superfluous
        // browsers and put it back into the map.
        browser = toRemove.shift();
        browser.resize(width, height);
      } else {
        // No more browsers to reuse, create a new one.
        browser = new HiddenBrowser(width, height);
      }

      this._browsers.set(key, browser);
    }

    // Finally, remove all browsers we don't need anymore.
    toRemove.forEach(b => b.destroy());
  },

  _collectTabBrowserSizes: function () {
    let sizes = new Map();

    function tabBrowserBounds() {
      let wins = Services.ww.getWindowEnumerator("navigator:browser");
      while (wins.hasMoreElements()) {
        let win = wins.getNext();
        if (win.gBrowser) {
          let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
                         .getInterface(Ci.nsIDOMWindowUtils);
          yield utils.getBoundsWithoutFlushing(win.gBrowser);
        }
      }
    }

    // Collect the sizes of all <tabbrowser>s out there.
    for (let {width, height} of tabBrowserBounds()) {
      if (width > 0 && height > 0) {
        let key = width + "x" + height;
        if (!sizes.has(key)) {
          sizes.set(key, {width: width, height: height});
        }
      }
    }

    return sizes;
  }
};

function HiddenBrowser(width, height) {
  this.resize(width, height);

  HostFrame.get().then(aFrame => {
    let doc = aFrame.document;
    this._browser = doc.createElementNS(XUL_NS, "browser");
    this._browser.setAttribute("type", "content");
    this._browser.setAttribute("src", NEWTAB_URL);
    this._applySize();
    doc.getElementById("win").appendChild(this._browser);
  });
}

HiddenBrowser.prototype = {
  _width: null,
  _height: null,
  _timer: null,
  _needsFrameScripts: true,

  get isPreloaded() {
    return this._browser &&
           this._browser.contentDocument &&
           this._browser.contentDocument.readyState === "complete" &&
           this._browser.currentURI.spec === NEWTAB_URL;
  },

  swapWithNewTab: function (aTab) {
    if (!this.isPreloaded || this._timer) {
      return false;
    }

    let win = aTab.ownerDocument.defaultView;
    let tabbrowser = win.gBrowser;

    if (!tabbrowser) {
      return false;
    }

    // Swap docShells.
    tabbrowser.swapNewTabWithBrowser(aTab, this._browser);

    // Load all default frame scripts.
    if (this._needsFrameScripts) {
      this._needsFrameScripts = false;

      let mm = aTab.linkedBrowser.messageManager;
      mm.loadFrameScript("chrome://browser/content/content.js", true);
      mm.loadFrameScript("chrome://browser/content/content-sessionStore.js", true);

      if ("TabView" in win) {
        mm.loadFrameScript("chrome://browser/content/tabview-content.js", true);
      }
    }

    // Start a timer that will kick off preloading the next newtab page.
    this._timer = createTimer(this, PRELOADER_INTERVAL_MS);

    // Signal that we swapped docShells.
    return true;
  },

  observe: function () {
    this._timer = null;

    // Start pre-loading the new tab page.
    this._browser.loadURI(NEWTAB_URL);
  },

  resize: function (width, height) {
    this._width = width;
    this._height = height;
    this._applySize();
  },

  _applySize: function () {
    if (this._browser) {
      this._browser.style.width = this._width + "px";
      this._browser.style.height = this._height + "px";
    }
  },

  destroy: function () {
    if (this._browser) {
      this._browser.remove();
      this._browser = null;
    }

    this._timer = clearTimer(this._timer);
  }
};

var HostFrame = {
  _frame: null,
  _deferred: null,

  get hiddenDOMDocument() {
    return Services.appShell.hiddenDOMWindow.document;
  },

  get isReady() {
    return this.hiddenDOMDocument.readyState === "complete";
  },

  get: function () {
    if (!this._deferred) {
      this._deferred = Promise.defer();
      this._create();
    }

    return this._deferred.promise;
  },

  destroy: function () {
    if (this._frame) {
      if (!Cu.isDeadWrapper(this._frame)) {
        this._frame.removeEventListener("load", this, true);
        this._frame.remove();
      }

      this._frame = null;
      this._deferred = null;
    }
  },

  handleEvent: function () {
    let contentWindow = this._frame.contentWindow;
    if (contentWindow.location.href === XUL_PAGE) {
      this._frame.removeEventListener("load", this, true);
      this._deferred.resolve(contentWindow);
    } else {
      contentWindow.location = XUL_PAGE;
    }
  },

  _create: function () {
    if (this.isReady) {
      let doc = this.hiddenDOMDocument;
      this._frame = doc.createElementNS(HTML_NS, "iframe");
      this._frame.addEventListener("load", this, true);
      doc.documentElement.appendChild(this._frame);
    } else {
      let flags = Ci.nsIThread.DISPATCH_NORMAL;
      Services.tm.currentThread.dispatch(() => this._create(), flags);
    }
  }
};