Rewrote tabs engine to work with 0.3 API. (Not yet tested).
authorjonathandicarlo@jonathan-dicarlos-macbook-pro.local
Wed, 04 Feb 2009 19:51:20 -0800
changeset 45221 e482805f3d3ca6e31742663fc4577bdda2d40c9c
parent 45220 3ed81bd05076ce782c3558b909ffbb29690360c6
child 45222 c9f8433b34df87fb109e07c8a23a58f3a9c4473b
push idunknown
push userunknown
push dateunknown
Rewrote tabs engine to work with 0.3 API. (Not yet tested).
services/sync/modules/engines/bookmarks.js
services/sync/modules/engines/history.js
services/sync/modules/engines/tabs.js
services/sync/modules/type_records/tabs.js
--- a/services/sync/modules/engines/bookmarks.js
+++ b/services/sync/modules/engines/bookmarks.js
@@ -193,16 +193,20 @@ BookmarksStore.prototype = {
     }
 
     switch (record.cleartext.type) {
     case "query":
     case "bookmark":
     case "microsummary": {
       this._log.debug(" -> creating bookmark \"" + record.cleartext.title + "\"");
       let uri = Utils.makeURI(record.cleartext.uri);
+      this._log.debug(" -> -> ParentID is " + parentId);
+      this._log.debug(" -> -> uri is " + record.cleartext.uri);
+      this._log.debug(" -> -> sortindex is " + record.sortindex);
+      this._log.debug(" -> -> title is " + record.cleartext.title);
       newId = this._bms.insertBookmark(parentId, uri, record.sortindex,
                                        record.cleartext.title);
       this._ts.untagURI(uri, null);
       this._ts.tagURI(uri, record.cleartext.tags);
       this._bms.setKeywordForBookmark(newId, record.cleartext.keyword);
       if (record.cleartext.description) {
         this._ans.setItemAnnotation(newId, "bookmarkProperties/description",
                                     record.cleartext.description, 0,
--- a/services/sync/modules/engines/history.js
+++ b/services/sync/modules/engines/history.js
@@ -350,16 +350,32 @@ HistoryStore.prototype = {
 
 
   getAllIDs: function HistStore_getAllIDs() {
     let query = this._hsvc.getNewQuery(),
         options = this._hsvc.getNewQueryOptions();
 
     query.minVisits = 1;
     options.maxResults = 100;
+    /*
+    dump("SORT_BY_DATE_DESCENDING is " + options.SORT_BY_DATE_DESCENDING + "\n");
+    dump("SORT_BY_ANNOTATIOn_DESCENDING is " + options.SORT_BY_ANNOTATION_DESCENDING + "\n");
+    dump("BEFORE SETTING, options.sortingMode is " + options.sortingMode + "\n");
+
+    for ( let z = -1; z < 20; z++) {
+      try {
+	options.sortingMode = z;
+	dump("  -> Can set to " + z + " OK...\n");
+      } catch (e) {
+	dump("  -> Setting to " + z + " raises exception.\n");
+      }
+    }
+    dump("AFTER SETTING, options.sortingMode is " + options.sortingMode + "\n");
+     */
+     // TODO the following line throws exception on Fennec; see above.
     options.sortingMode = options.SORT_BY_DATE_DESCENDING;
     options.queryType = options.QUERY_TYPE_HISTORY;
 
     let root = this._hsvc.executeQuery(query, options).root;
     root.QueryInterface(Ci.nsINavHistoryQueryResultNode);
     root.containerOpen = true;
 
     let items = {};
--- a/services/sync/modules/engines/tabs.js
+++ b/services/sync/modules/engines/tabs.js
@@ -14,16 +14,17 @@
  * The Original Code is Bookmarks Sync.
  *
  * The Initial Developer of the Original Code is Mozilla.
  * Portions created by the Initial Developer are Copyright (C) 2008
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *  Myk Melez <myk@mozilla.org>
+ *  Jono DiCarlo <jdicarlo@mozilla.com>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either the GNU General Public License Version 2 or later (the "GPL"), or
  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -31,241 +32,244 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 const EXPORTED_SYMBOLS = ['TabEngine'];
 
+const SESSION_STORE_KEY = "weave-tab-sync-id";
+
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 
 Cu.import("resource://weave/util.js");
 Cu.import("resource://weave/async.js");
 Cu.import("resource://weave/engines.js");
-Cu.import("resource://weave/syncCores.js");
 Cu.import("resource://weave/stores.js");
 Cu.import("resource://weave/trackers.js");
 Cu.import("resource://weave/constants.js");
+Cu.import("resource://weave/type_records/tabs.js");
 
 Function.prototype.async = Async.sugar;
 
 function TabEngine() {
   this._init();
 }
 TabEngine.prototype = {
   __proto__: SyncEngine.prototype,
   name: "tabs",
   displayName: "Tabs",
   logName: "Tabs",
   _storeObj: TabStore,
   _trackerObj: TabTracker,
-  _recordObj: ClientTabsRecord
+  _recordObj: TabSetRecord,
 
-  get virtualTabs() {
-    let virtualTabs = {};
-    let realTabs = this._store.wrap();
+  // API for use by Weave UI code to give user choices of tabs to open:
+  getAllClients: function TabEngine_getAllClients() {
+    return this._store._remoteClients;
+  },
 
-    for (let profileId in this._file.data) {
-      let tabset = this._file.data[profileId];
-      for (let guid in tabset) {
-        if (!(guid in realTabs) && !(guid in virtualTabs)) {
-          virtualTabs[guid] = tabset[guid];
-          virtualTabs[guid].profileId = profileId;
-        }
-      }
-    }
-    return virtualTabs;
+  getClientById: function TabEngine_getClientById(id) {
+    return this._store._remoteClients[id];
   }
+
 };
 
+
 function TabStore() {
   this._TabStore_init();
 }
 TabStore.prototype = {
-  __proto__: new Store(),
+  __proto__: Store.prototype,
   _logName: "Tabs.Store",
+  _filePath: "weave/meta/tabSets.json",
+  _remoteClients: {},
+
+  _TabStore_init: function TabStore__init() {
+    this._init();
+    this._readFromFile();
+  },
+
+  get _localClientGUID() {
+    return Engines.get("clients").clientID;
+  },
+
+  get _localClientName() {
+    return Engines.get("clients").clientName;
+  },
+
+  _writeToFile: function TabStore_writeToFile() {
+    // use JSON service to serialize the records...
+    let file = Utils.getProfileFile(
+      {path: this._filePath, autoCreate: true});
+    let jsonObj = {};
+    for (let id in this._remoteClients) {
+      jsonObj[id] = this._remoteClients[id].toJson();
+    }
+    let [fos] = Utils.open(file, ">");
+    fos.writeString(this._json.encode(jsonObj));
+    fos.close();
+  },
+
+  _readFromFile: function TabStore_readFromFile() {
+    // use JSON service to un-serialize the records...
+    // call on initialization.
+    // Put stuff into remoteClients.
+    let file = Utils.getProfileFile(this._filePath);
+    if (!file.exists())
+      return;
+    try {
+      let [is] = Utils.open(file, "<");
+      let json = Utils.readStream(is);
+      is.close();
+      let jsonObj = this._json.decode(json);
+      for (let id in jsonObj) {
+	this._remoteClients[id] = new TabSetRecord();
+	this._remoteClients[id].fromJson(jsonObj[id]);
+	this._remoteClients[id].id = id;
+    }
+    } catch (e) {
+      this._log.warn("Failed to load saved tabs file" + e);
+    }
+  },
 
   get _sessionStore() {
     let sessionStore = Cc["@mozilla.org/browser/sessionstore;1"].
 		       getService(Ci.nsISessionStore);
-    this.__defineGetter__("_sessionStore", function() sessionStore);
+    this.__defineGetter__("_sessionStore", function() { return sessionStore;});
     return this._sessionStore;
   },
 
-  _createCommand: function TabStore__createCommand(command) {
-    this._log.debug("_createCommand: " + command.GUID);
-
-    if (command.GUID in this._virtualTabs || command.GUID in this._wrapRealTabs())
-      throw "trying to create a tab that already exists; id: " + command.GUID;
-
-    // Don't do anything if the command isn't valid (i.e. it doesn't contain
-    // the minimum information about the tab that is necessary to recreate it).
-    if (!this.validateVirtualTab(command.data)) {
-      this._log.warn("could not create command " + command.GUID + "; invalid");
-      return;
-    }
-
-    // Cache the tab and notify the UI to prompt the user to open it.
-    this._virtualTabs[command.GUID] = command.data;
-    this._os.notifyObservers(null, "weave:store:tabs:virtual:created", null);
+  get _json() {
+    let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
+    this.__defineGetter__("_json", function() {return json;});
+    return this._json;
   },
 
-  /**
-   * Serialize the current state of tabs.
-   */
-  wrap: function TabStore_wrap() {
-    let items = {};
+  _createLocalClientTabSetRecord: function TabStore__createLocalTabSet() {
+    let session = this._json.decode(this._sessionStore.getBrowserState());
 
-    let session = this._json.decode(this._sessionStore.getBrowserState());
+    let record = new TabSetRecord();
+    record.setClientName( this._localClientName );
 
     for (let i = 0; i < session.windows.length; i++) {
       let window = session.windows[i];
       // For some reason, session store uses one-based array index references,
       // (f.e. in the "selectedWindow" and each tab's "index" properties), so we
       // convert them to and from JavaScript's zero-based indexes as needed.
       let windowID = i + 1;
 
       for (let j = 0; j < window.tabs.length; j++) {
         let tab = window.tabs[j];
-
-	// The session history entry for the page currently loaded in the tab.
-	// We use the URL of the current page as the ID for the tab.
-	let currentEntry = tab.entries[tab.index - 1];
-	if (!currentEntry || !currentEntry.url) {
-	  this._log.warn("_wrapRealTabs: no current entry or no URL, can't " +
-                         "identify " + this._json.encode(tab));
-	  continue;
+	let title = tab.contentDocument.title.innerHtml; // will this work?
+	let urlHistory = [];
+	let entries = tab.entries.slice(tab.entries.length - 10);
+	for (let entry in entries) {
+	  urlHistory.push( entry.url );
 	}
-
-	let tabID = currentEntry.url;
-
-        // Only sync up to 10 back-button entries, otherwise we can end up with
-        // some insanely large snapshots.
-        tab.entries = tab.entries.slice(tab.entries.length - 10);
-
-        // The ID property of each entry in the tab, which I think contains
-        // nsISHEntry::ID, changes every time session store restores the tab,
-        // so we can't sync them, or we would generate edit commands on every
-        // restart (even though nothing has actually changed).
-        for (let k = 0; k < tab.entries.length; k++) {
-            delete tab.entries[k].ID;
-        }
-
-	items[tabID] = {
-          // Identify this item as a tab in case we start serializing windows
-          // in the future.
-	  type: "tab",
-
-          // The position of this tab relative to other tabs in the window.
-          // For consistency with session store data, we make this one-based.
-          position: j + 1,
-
-	  windowID: windowID,
-
-	  state: tab
-	};
+	record.addTab(title, urlHistory);
       }
     }
+    return record;
+  },
 
+  itemExists: function TabStore_itemExists(id) {
+    if (id == this._localClientGUID) {
+      return true;
+    } else if (this._remoteClients[id]) {
+      return true;
+    } else {
+      return false;
+    }
+  },
+
+  createRecord: function TabStore_createRecord(id) {
+    let record;
+    if (id == this._localClientGUID) {
+      record = this._createLocalClientTabSetRecord();
+    } else {
+      record = this._remoteClients[id];
+    }
+    record.id = id;
+    return record;
+  },
+
+  changeItemId: function TabStore_changeItemId(oldId, newId) {
+    if (this._remoteClients[oldId]) {
+      let record = this._remoteClients[oldId];
+      record.id = newId;
+      delete this._remoteClients[oldId];
+      this._remoteClients[newId] = record;
+    }
+  },
+
+  getAllIds: function TabStore_getAllIds() {
+    let items = {};
+    items[ this._localClientGUID ] = true;
+    for (let id in this._remoteClients) {
+      items[id] = true;
+    }
     return items;
   },
 
   wipe: function TabStore_wipe() {
-    // We're not going to close tabs, since that's probably not what
-    // the user wants
+    this._log.debug("Wipe called.  Clearing cache of remote client tabs.");
+    this._remoteClients = {};
+    this._writeToFile();
+  },
+
+  create: function TabStore_create(record) {
+    if (record.id == this._localClientGUID)
+      return; // can't happen?
+    this._log.debug("Create called.  Adding remote client record for ");
+    this._log.debug(record.getClientName());
+    this._remoteClients[record.id] = record;
+    this._writeToFile();
+    // TODO writing to file after every change is inefficient.  How do we
+    // make sure to do it (or at least flush it) only after sync is done?
+    // override syncFinished
+  },
+
+  update: function TabStore_update(record) {
+    if (record.id == this._localClientGUID)
+      return; // can't happen?
+    this._log.debug("Update called.  Updating remote client record for");
+    this._log.debug(record.getClientName());
+    this._remoteClients[record.id] = record;
+    this._writeToFile();
+  },
+
+  remove: function TabStore_remove(record) {
+    if (record.id == this._localClientGUID)
+      return; // can't happen?
+    this._log.debug("Remove called.  Deleting record with id " + record.id);
+    delete this._remoteClients[record.id];
+    this._writeToFile();
   }
+
 };
 
-function TabTracker(engine) {
-  this._engine = engine;
+function TabTracker() {
   this._init();
 }
 TabTracker.prototype = {
-  __proto__: new Tracker(),
+  __proto__: Tracker.prototype,
+  _logName: "TabTracker",
+  file: "tab_tracker",
 
-  _logName: "TabTracker",
+  _init: function TabTracker__init() {
+    this.__proto__.__proto__.init.call(this);
 
-  _engine: null,
-
-  get _json() {
-    let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
-    this.__defineGetter__("_json", function() json);
-    return this._json;
+    // Register me as an observer!!  Listen for tabs opening and closing:
+    let container = gBrowser.tabContainer;
+    container.addEventListener("TabOpen", this.onTabChanged, false);
+    container.addEventListener("TabClose", this.onTabChanged, false);
+    // TODO: remove these event listeners when not needed?
+    // as in container.removeEventListener("TabOpen", this.onTabChanged, false);
   },
 
-  /**
-   * There are two ways we could calculate the score.  We could calculate it
-   * incrementally by using the window mediator to watch for windows opening/
-   * closing and FUEL (or some other API) to watch for tabs opening/closing
-   * and changing location.
-   *
-   * Or we could calculate it on demand by comparing the state of tabs
-   * according to the session store with the state according to the snapshot.
-   *
-   * It's hard to say which is better.  The incremental approach is less
-   * accurate if it simply increments the score whenever there's a change,
-   * but it might be more performant.  The on-demand approach is more accurate,
-   * but it might be less performant depending on how often it's called.
-   *
-   * In this case we've decided to go with the on-demand approach, and we
-   * calculate the score as the percent difference between the snapshot set
-   * and the current tab set, where tabs that only exist in one set are
-   * completely different, while tabs that exist in both sets but whose data
-   * doesn't match (f.e. because of variations in history) are considered
-   * "half different".
-   *
-   * So if the sets don't match at all, we return 100;
-   * if they completely match, we return 0;
-   * if half the tabs match, and their data is the same, we return 50;
-   * and if half the tabs match, but their data is all different, we return 75.
-   */
-  get score() {
-    // The snapshot data is a singleton that we can't modify, so we have to
-    // copy its unique items to a new hash.
-    let snapshotData = this._engine.snapshot.data;
-    let a = {};
-
-    // The wrapped current state is a unique instance we can munge all we want.
-    let b = this._engine.store.wrap();
-
-    // An array that counts the number of intersecting IDs between a and b
-    // (represented as the length of c) and whether or not their values match
-    // (represented by the boolean value of each item in c).
-    let c = [];
-
-    // Generate c and update a and b to contain only unique items.
-    for (id in snapshotData) {
-      if (id in b) {
-        c.push(this._json.encode(snapshotData[id]) == this._json.encode(b[id]));
-        delete b[id];
-      }
-      else {
-        a[id] = snapshotData[id];
-      }
-    }
-
-    let numShared = c.length;
-    let numUnique = [true for (id in a)].length + [true for (id in b)].length;
-    let numTotal = numShared + numUnique;
-
-    // We're going to divide by the total later, so make sure we don't try
-    // to divide by zero, even though we should never be in a state where there
-    // are no tabs in either set.
-    if (numTotal == 0)
-      return 0;
-
-    // The number of shared items whose data is different.
-    let numChanged = c.filter(function(v) !v).length;
-
-    let fractionSimilar = (numShared - (numChanged / 2)) / numTotal;
-    let fractionDissimilar = 1 - fractionSimilar;
-    let percentDissimilar = Math.round(fractionDissimilar * 100);
-
-    return percentDissimilar;
-  },
-
-  resetScore: function FormsTracker_resetScore() {
-    // Not implemented, since we calculate the score on demand.
+  onTabChanged: function TabTracker_onTabChanged(event) {
+    this._score += 10; // meh?  meh.
   }
 }
new file mode 100644
--- /dev/null
+++ b/services/sync/modules/type_records/tabs.js
@@ -0,0 +1,92 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Weave.
+ *
+ * The Initial Developer of the Original Code is Mozilla.
+ * Portions created by the Initial Developer are Copyright (C) 2009
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *  Jono DiCarlo <jdicarlo@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+const EXPORTED_SYMBOLS = ['TabSetRecord'];
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cr = Components.results;
+const Cu = Components.utils;
+
+Cu.import("resource://weave/log4moz.js");
+Cu.import("resource://weave/util.js");
+Cu.import("resource://weave/async.js");
+Cu.import("resource://weave/base_records/wbo.js");
+Cu.import("resource://weave/base_records/crypto.js");
+Cu.import("resource://weave/base_records/keys.js");
+
+Function.prototype.async = Async.sugar;
+
+function TabSetRecord(uri) {
+  this._TabSetRecord_init(uri);
+}
+TabSetRecord.prototype = {
+  __proto__: CryptoWrapper.prototype,
+  _logName: "Record.Tabs",
+
+  _TabSetRecord_init: function TabSetRecord__init(uri) {
+    this._CryptoWrap_init(uri);
+    this.cleartext = {
+    };
+  },
+
+  addTab: function TabSetRecord_addTab(title, urlHistory) {
+    if (!this.cleartext.tabs)
+      this.cleartext.tabs = [];
+    this.cleartext.tabs.push( { title: title,
+				urlHistory: urlHistory });
+  },
+
+  getAllTabs: function TabSetRecord_getAllTabs() {
+    return this.cleartext.tabs;
+  },
+
+  setClientName: function TabSetRecord_setClientName(value) {
+    this.cleartext.clientName = value;
+  },
+
+  getClientName: function TabSetRecord_getClientName() {
+    return this.cleartext.clientName;
+  },
+
+  toJson: function TabSetRecord_toJson() {
+    return this.cleartext;
+  },
+
+  fromJson: function TabSetRecord_fromJson(json) {
+    this.cleartext = json;
+  }
+};