summaryrefslogtreecommitdiffstats
path: root/browser/base/content/browser-thumbnails.js
blob: e17f5aa05b321d3f6e4c2421f68b3ea8b2a12198 (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
/* 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/. */

// This file is loaded into the browser window scope.
/* eslint-env mozilla/browser-window */

/**
 * Keeps thumbnails of open web pages up-to-date.
 */
var gBrowserThumbnails = {
  /**
   * Pref that controls whether we can store SSL content on disk
   */
  PREF_DISK_CACHE_SSL: "browser.cache.disk_cache_ssl",

  _captureDelayMS: 1000,

  /**
   * Used to keep track of disk_cache_ssl preference
   */
  _sslDiskCacheEnabled: null,

  /**
   * Map of capture() timeouts assigned to their browsers.
   */
  _timeouts: null,

  /**
   * Top site URLs refresh timer.
   */
  _topSiteURLsRefreshTimer: null,

  /**
   * List of tab events we want to listen for.
   */
  _tabEvents: ["TabClose", "TabSelect"],

  init: function Thumbnails_init() {
    gBrowser.addTabsProgressListener(this);
    Services.prefs.addObserver(this.PREF_DISK_CACHE_SSL, this);

    this._sslDiskCacheEnabled = Services.prefs.getBoolPref(
      this.PREF_DISK_CACHE_SSL
    );

    this._tabEvents.forEach(function (aEvent) {
      gBrowser.tabContainer.addEventListener(aEvent, this);
    }, this);

    this._timeouts = new WeakMap();
  },

  uninit: function Thumbnails_uninit() {
    gBrowser.removeTabsProgressListener(this);
    Services.prefs.removeObserver(this.PREF_DISK_CACHE_SSL, this);

    if (this._topSiteURLsRefreshTimer) {
      this._topSiteURLsRefreshTimer.cancel();
      this._topSiteURLsRefreshTimer = null;
    }

    this._tabEvents.forEach(function (aEvent) {
      gBrowser.tabContainer.removeEventListener(aEvent, this);
    }, this);
  },

  handleEvent: function Thumbnails_handleEvent(aEvent) {
    switch (aEvent.type) {
      case "scroll":
        let browser = aEvent.currentTarget;
        if (this._timeouts.has(browser)) {
          this._delayedCapture(browser);
        }
        break;
      case "TabSelect":
        this._delayedCapture(aEvent.target.linkedBrowser);
        break;
      case "TabClose": {
        this._cancelDelayedCapture(aEvent.target.linkedBrowser);
        break;
      }
    }
  },

  observe: function Thumbnails_observe(subject, topic, data) {
    switch (data) {
      case this.PREF_DISK_CACHE_SSL:
        this._sslDiskCacheEnabled = Services.prefs.getBoolPref(
          this.PREF_DISK_CACHE_SSL
        );
        break;
    }
  },

  clearTopSiteURLCache: function Thumbnails_clearTopSiteURLCache() {
    if (this._topSiteURLsRefreshTimer) {
      this._topSiteURLsRefreshTimer.cancel();
      this._topSiteURLsRefreshTimer = null;
    }
    // Delete the defined property
    delete this._topSiteURLs;
    XPCOMUtils.defineLazyGetter(this, "_topSiteURLs", getTopSiteURLs);
  },

  notify: function Thumbnails_notify(timer) {
    gBrowserThumbnails._topSiteURLsRefreshTimer = null;
    gBrowserThumbnails.clearTopSiteURLCache();
  },

  /**
   * State change progress listener for all tabs.
   */
  onStateChange: function Thumbnails_onStateChange(
    aBrowser,
    aWebProgress,
    aRequest,
    aStateFlags,
    aStatus
  ) {
    if (
      aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
      aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK
    ) {
      this._delayedCapture(aBrowser);
    }
  },

  async _capture(aBrowser) {
    // Only capture about:newtab top sites.
    const topSites = await this._topSiteURLs;
    if (!aBrowser.currentURI || !topSites.includes(aBrowser.currentURI.spec)) {
      return;
    }
    if (await this._shouldCapture(aBrowser)) {
      await PageThumbs.captureAndStoreIfStale(aBrowser);
    }
  },

  _delayedCapture: function Thumbnails_delayedCapture(aBrowser) {
    if (this._timeouts.has(aBrowser)) {
      this._cancelDelayedCallbacks(aBrowser);
    } else {
      aBrowser.addEventListener("scroll", this, true);
    }

    let idleCallback = () => {
      this._cancelDelayedCapture(aBrowser);
      this._capture(aBrowser);
    };

    // setTimeout to set a guarantee lower bound for the requestIdleCallback
    // (and therefore the delayed capture)
    let timeoutId = setTimeout(() => {
      let idleCallbackId = requestIdleCallback(idleCallback, {
        timeout: this._captureDelayMS * 30,
      });
      this._timeouts.set(aBrowser, { isTimeout: false, id: idleCallbackId });
    }, this._captureDelayMS);

    this._timeouts.set(aBrowser, { isTimeout: true, id: timeoutId });
  },

  _shouldCapture: async function Thumbnails_shouldCapture(aBrowser) {
    // Capture only if it's the currently selected tab and not an about: page.
    if (
      aBrowser != gBrowser.selectedBrowser ||
      gBrowser.currentURI.schemeIs("about")
    ) {
      return false;
    }
    return PageThumbs.shouldStoreThumbnail(aBrowser);
  },

  _cancelDelayedCapture: function Thumbnails_cancelDelayedCapture(aBrowser) {
    if (this._timeouts.has(aBrowser)) {
      aBrowser.removeEventListener("scroll", this);
      this._cancelDelayedCallbacks(aBrowser);
      this._timeouts.delete(aBrowser);
    }
  },

  _cancelDelayedCallbacks: function Thumbnails_cancelDelayedCallbacks(
    aBrowser
  ) {
    let timeoutData = this._timeouts.get(aBrowser);

    if (timeoutData.isTimeout) {
      clearTimeout(timeoutData.id);
    } else {
      // idle callback dispatched
      window.cancelIdleCallback(timeoutData.id);
    }
  },
};

async function getTopSiteURLs() {
  // The _topSiteURLs getter can be expensive to run, but its return value can
  // change frequently on new profiles, so as a compromise we cache its return
  // value as a lazy getter for 1 minute every time it's called.
  gBrowserThumbnails._topSiteURLsRefreshTimer = Cc[
    "@mozilla.org/timer;1"
  ].createInstance(Ci.nsITimer);
  gBrowserThumbnails._topSiteURLsRefreshTimer.initWithCallback(
    gBrowserThumbnails,
    60 * 1000,
    Ci.nsITimer.TYPE_ONE_SHOT
  );
  let sites = [];
  // Get both the top sites returned by the query, and also any pinned sites
  // that the user might have added manually that also need a screenshot.
  // Also include top sites that don't have rich icons
  let topSites = await NewTabUtils.activityStreamLinks.getTopSites();
  sites.push(...topSites.filter(link => !(link.faviconSize >= 96)));
  sites.push(...NewTabUtils.pinnedLinks.links);
  return sites.reduce((urls, link) => {
    if (link) {
      urls.push(link.url);
    }
    return urls;
  }, []);
}

XPCOMUtils.defineLazyGetter(gBrowserThumbnails, "_topSiteURLs", getTopSiteURLs);