PageRenderTime 29ms CodeModel.GetById 12ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/services/sync/modules/engines/tabs.js

http://github.com/zpao/v8monkey
JavaScript | 361 lines | 224 code | 55 blank | 82 comment | 44 complexity | c6224f9fd673034ff00bd8c68c3962dc MD5 | raw file
  1/* ***** BEGIN LICENSE BLOCK *****
  2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3 *
  4 * The contents of this file are subject to the Mozilla Public License Version
  5 * 1.1 (the "License"); you may not use this file except in compliance with
  6 * the License. You may obtain a copy of the License at
  7 * http://www.mozilla.org/MPL/
  8 *
  9 * Software distributed under the License is distributed on an "AS IS" basis,
 10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 11 * for the specific language governing rights and limitations under the
 12 * License.
 13 *
 14 * The Original Code is Bookmarks Sync.
 15 *
 16 * The Initial Developer of the Original Code is Mozilla.
 17 * Portions created by the Initial Developer are Copyright (C) 2008
 18 * the Initial Developer. All Rights Reserved.
 19 *
 20 * Contributor(s):
 21 *  Myk Melez <myk@mozilla.org>
 22 *  Jono DiCarlo <jdicarlo@mozilla.com>
 23 *  Philipp von Weitershausen <philipp@weitershausen.de>
 24 *
 25 * Alternatively, the contents of this file may be used under the terms of
 26 * either the GNU General Public License Version 2 or later (the "GPL"), or
 27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 28 * in which case the provisions of the GPL or the LGPL are applicable instead
 29 * of those above. If you wish to allow use of your version of this file only
 30 * under the terms of either the GPL or the LGPL, and not to allow others to
 31 * use your version of this file under the terms of the MPL, indicate your
 32 * decision by deleting the provisions above and replace them with the notice
 33 * and other provisions required by the GPL or the LGPL. If you do not delete
 34 * the provisions above, a recipient may use your version of this file under
 35 * the terms of any one of the MPL, the GPL or the LGPL.
 36 *
 37 * ***** END LICENSE BLOCK ***** */
 38
 39const EXPORTED_SYMBOLS = ['TabEngine', 'TabSetRecord'];
 40
 41const Cc = Components.classes;
 42const Ci = Components.interfaces;
 43const Cu = Components.utils;
 44
 45const TABS_TTL = 604800; // 7 days
 46
 47Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 48Cu.import("resource://services-sync/engines.js");
 49Cu.import("resource://services-sync/engines/clients.js");
 50Cu.import("resource://services-sync/record.js");
 51Cu.import("resource://services-sync/resource.js");
 52Cu.import("resource://services-sync/util.js");
 53Cu.import("resource://services-sync/constants.js");
 54Cu.import("resource://services-sync/ext/Preferences.js");
 55
 56// It is safer to inspect the private browsing preferences rather than
 57// the flags of nsIPrivateBrowsingService.  The user may have turned on
 58// "Never remember history" in the same session, or Firefox was started
 59// with the -private command line argument.  In both cases, the
 60// "autoStarted" flag of nsIPrivateBrowsingService will be wrong.
 61const PBPrefs = new Preferences("browser.privatebrowsing.");
 62
 63
 64function TabSetRecord(collection, id) {
 65  CryptoWrapper.call(this, collection, id);
 66}
 67TabSetRecord.prototype = {
 68  __proto__: CryptoWrapper.prototype,
 69  _logName: "Sync.Record.Tabs",
 70  ttl: TABS_TTL
 71};
 72
 73Utils.deferGetSet(TabSetRecord, "cleartext", ["clientName", "tabs"]);
 74
 75
 76function TabEngine() {
 77  SyncEngine.call(this, "Tabs");
 78
 79  // Reset the client on every startup so that we fetch recent tabs
 80  this._resetClient();
 81}
 82TabEngine.prototype = {
 83  __proto__: SyncEngine.prototype,
 84  _storeObj: TabStore,
 85  _trackerObj: TabTracker,
 86  _recordObj: TabSetRecord,
 87
 88  getChangedIDs: function getChangedIDs() {
 89    // No need for a proper timestamp (no conflict resolution needed).
 90    let changedIDs = {};
 91    if (this._tracker.modified)
 92      changedIDs[Clients.localID] = 0;
 93    return changedIDs;
 94  },
 95
 96  // API for use by Weave UI code to give user choices of tabs to open:
 97  getAllClients: function TabEngine_getAllClients() {
 98    return this._store._remoteClients;
 99  },
100
101  getClientById: function TabEngine_getClientById(id) {
102    return this._store._remoteClients[id];
103  },
104
105  _resetClient: function TabEngine__resetClient() {
106    SyncEngine.prototype._resetClient.call(this);
107    this._store.wipe();
108    this._tracker.modified = true;
109  },
110
111  removeClientData: function removeClientData() {
112    new Resource(this.engineURL + "/" + Clients.localID).delete();
113  },
114
115  /* The intent is not to show tabs in the menu if they're already
116   * open locally.  There are a couple ways to interpret this: for
117   * instance, we could do it by removing a tab from the list when
118   * you open it -- but then if you close it, you can't get back to
119   * it.  So the way I'm doing it here is to not show a tab in the menu
120   * if you have a tab open to the same URL, even though this means
121   * that as soon as you navigate anywhere, the original tab will
122   * reappear in the menu.
123   */
124  locallyOpenTabMatchesURL: function TabEngine_localTabMatches(url) {
125    return this._store.getAllTabs().some(function(tab) {
126      return tab.urlHistory[0] == url;
127    });
128  }
129};
130
131
132function TabStore(name) {
133  Store.call(this, name);
134}
135TabStore.prototype = {
136  __proto__: Store.prototype,
137
138  itemExists: function TabStore_itemExists(id) {
139    return id == Clients.localID;
140  },
141
142  getAllTabs: function getAllTabs(filter) {
143    let filteredUrls = new RegExp(Svc.Prefs.get("engine.tabs.filteredUrls"), "i");
144
145    let allTabs = [];
146
147    let currentState = JSON.parse(Svc.Session.getBrowserState());
148    currentState.windows.forEach(function(window) {
149      window.tabs.forEach(function(tab) {
150        // Make sure there are history entries to look at.
151        if (!tab.entries.length)
152          return;
153        // Until we store full or partial history, just grab the current entry.
154        // index is 1 based, so make sure we adjust.
155        let entry = tab.entries[tab.index - 1];
156
157        // Filter out some urls if necessary. SessionStore can return empty
158        // tabs in some cases - easiest thing is to just ignore them for now.
159        if (!entry.url || filter && filteredUrls.test(entry.url))
160          return;
161
162        // weaveLastUsed will only be set if the tab was ever selected (or
163        // opened after Weave was running). So it might not ever be set.
164        // I think it's also possible that attributes[.image] might not be set
165        // so handle that as well.
166        allTabs.push({
167          title: entry.title || "",
168          urlHistory: [entry.url],
169          icon: tab.attributes && tab.attributes.image || "",
170          lastUsed: tab.extData && tab.extData.weaveLastUsed || 0
171        });
172      });
173    });
174
175    return allTabs;
176  },
177
178  createRecord: function createRecord(id, collection) {
179    let record = new TabSetRecord(collection, id);
180    record.clientName = Clients.localName;
181
182    // Don't provide any tabs to compare against and ignore the update later.
183    if (Svc.Private && Svc.Private.privateBrowsingEnabled && !PBPrefs.get("autostart")) {
184      record.tabs = [];
185      return record;
186    }
187
188    // Sort tabs in descending-used order to grab the most recently used
189    let tabs = this.getAllTabs(true).sort(function(a, b) {
190      return b.lastUsed - a.lastUsed;
191    });
192
193    // Figure out how many tabs we can pack into a payload. Starting with a 28KB
194    // payload, we can estimate various overheads from encryption/JSON/WBO.
195    let size = JSON.stringify(tabs).length;
196    let origLength = tabs.length;
197    const MAX_TAB_SIZE = 20000;
198    if (size > MAX_TAB_SIZE) {
199      // Estimate a little more than the direct fraction to maximize packing
200      let cutoff = Math.ceil(tabs.length * MAX_TAB_SIZE / size);
201      tabs = tabs.slice(0, cutoff + 1);
202
203      // Keep dropping off the last entry until the data fits
204      while (JSON.stringify(tabs).length > MAX_TAB_SIZE)
205        tabs.pop();
206    }
207
208    this._log.trace("Created tabs " + tabs.length + " of " + origLength);
209    tabs.forEach(function(tab) {
210      this._log.trace("Wrapping tab: " + JSON.stringify(tab));
211    }, this);
212
213    record.tabs = tabs;
214    return record;
215  },
216
217  getAllIDs: function TabStore_getAllIds() {
218    // Don't report any tabs if we're in private browsing for first syncs.
219    let ids = {};
220    if (Svc.Private && Svc.Private.privateBrowsingEnabled && !PBPrefs.get("autostart"))
221      return ids;
222
223    ids[Clients.localID] = true;
224    return ids;
225  },
226
227  wipe: function TabStore_wipe() {
228    this._remoteClients = {};
229  },
230
231  create: function TabStore_create(record) {
232    this._log.debug("Adding remote tabs from " + record.clientName);
233    this._remoteClients[record.id] = record.cleartext;
234
235    // Lose some precision, but that's good enough (seconds)
236    let roundModify = Math.floor(record.modified / 1000);
237    let notifyState = Svc.Prefs.get("notifyTabState");
238    // If there's no existing pref, save this first modified time
239    if (notifyState == null)
240      Svc.Prefs.set("notifyTabState", roundModify);
241    // Don't change notifyState if it's already 0 (don't notify)
242    else if (notifyState == 0)
243      return;
244    // We must have gotten a new tab that isn't the same as last time
245    else if (notifyState != roundModify)
246      Svc.Prefs.set("notifyTabState", 0);
247  },
248
249  update: function update(record) {
250    this._log.trace("Ignoring tab updates as local ones win");
251  }
252};
253
254
255function TabTracker(name) {
256  Tracker.call(this, name);
257  Svc.Obs.add("weave:engine:start-tracking", this);
258  Svc.Obs.add("weave:engine:stop-tracking", this);
259
260  // Make sure "this" pointer is always set correctly for event listeners
261  this.onTab = Utils.bind2(this, this.onTab);
262  this._unregisterListeners = Utils.bind2(this, this._unregisterListeners);
263}
264TabTracker.prototype = {
265  __proto__: Tracker.prototype,
266
267  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
268
269  loadChangedIDs: function loadChangedIDs() {
270    // Don't read changed IDs from disk at start up.
271  },
272
273  clearChangedIDs: function clearChangedIDs() {
274    this.modified = false;
275  },
276
277  _topics: ["pageshow", "TabOpen", "TabClose", "TabSelect"],
278  _registerListenersForWindow: function registerListenersFW(window) {
279    this._log.trace("Registering tab listeners in window");
280    for each (let topic in this._topics) {
281      window.addEventListener(topic, this.onTab, false);
282    }
283    window.addEventListener("unload", this._unregisterListeners, false);
284  },
285
286  _unregisterListeners: function unregisterListeners(event) {
287    this._unregisterListenersForWindow(event.target);
288  },
289
290  _unregisterListenersForWindow: function unregisterListenersFW(window) {
291    this._log.trace("Removing tab listeners in window");
292    window.removeEventListener("unload", this._unregisterListeners, false);
293    for each (let topic in this._topics) {
294      window.removeEventListener(topic, this.onTab, false);
295    }
296  },
297
298  _enabled: false,
299  observe: function TabTracker_observe(aSubject, aTopic, aData) {
300    switch (aTopic) {
301      case "weave:engine:start-tracking":
302        if (!this._enabled) {
303          Svc.Obs.add("private-browsing", this);
304          Svc.Obs.add("domwindowopened", this);
305          let wins = Services.wm.getEnumerator("navigator:browser");
306          while (wins.hasMoreElements())
307            this._registerListenersForWindow(wins.getNext());
308          this._enabled = true;
309        }
310        break;
311      case "weave:engine:stop-tracking":
312        if (this._enabled) {
313          Svc.Obs.remove("private-browsing", this);
314          Svc.Obs.remove("domwindowopened", this);
315          let wins = Services.wm.getEnumerator("navigator:browser");
316          while (wins.hasMoreElements())
317            this._unregisterListenersForWindow(wins.getNext());
318          this._enabled = false;
319        }
320        return;
321      case "domwindowopened":
322        // Add tab listeners now that a window has opened
323        let self = this;
324        aSubject.addEventListener("load", function onLoad(event) {
325          aSubject.removeEventListener("load", onLoad, false);
326          // Only register after the window is done loading to avoid unloads
327          self._registerListenersForWindow(aSubject);
328        }, false);
329        break;
330      case "private-browsing":
331        if (aData == "enter" && !PBPrefs.get("autostart"))
332          this.modified = false;
333    }
334  },
335
336  onTab: function onTab(event) {
337    if (Svc.Private && Svc.Private.privateBrowsingEnabled && !PBPrefs.get("autostart")) {
338      this._log.trace("Ignoring tab event from private browsing.");
339      return;
340    }
341
342    this._log.trace("onTab event: " + event.type);
343    this.modified = true;
344
345    // For pageshow events, only give a partial score bump (~.1)
346    let chance = .1;
347
348    // For regular Tab events, do a full score bump and remember when it changed
349    if (event.type != "pageshow") {
350      chance = 1;
351
352      // Store a timestamp in the tab to track when it was last used
353      Svc.Session.setTabValue(event.originalTarget, "weaveLastUsed",
354                              Math.floor(Date.now() / 1000));
355    }
356
357    // Only increase the score by whole numbers, so use random for partial score
358    if (Math.random() < chance)
359      this.score += SCORE_INCREMENT_SMALL;
360  },
361}