Bug 1165841 - Part 2: Move window-related code to nsNfc.js. r=dimi, a=jocheng
authorYoshi Huang <allstars.chh@mozilla.com>
Tue, 02 Jun 2015 01:38:00 -0400
changeset 238559 70ce7b9ea2a124a5022ddb44dd53aca25ab2776e
parent 238558 cba58571bc4340e525739f146cacb40c19f1bc54
child 238560 59fb202660689088f5a8b3a8a4d6ac908c485570
push id671
push userryanvm@gmail.com
push dateTue, 02 Jun 2015 15:17:39 +0000
treeherdermozilla-b2g37_v2_2@08da212f538c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersdimi, jocheng
bugs1165841
milestone37.0
Bug 1165841 - Part 2: Move window-related code to nsNfc.js. r=dimi, a=jocheng
dom/nfc/NfcContentHelper.js
dom/nfc/nsINfcContentHelper.idl
dom/nfc/nsNfc.js
--- a/dom/nfc/NfcContentHelper.js
+++ b/dom/nfc/NfcContentHelper.js
@@ -66,16 +66,17 @@ XPCOMUtils.defineLazyServiceGetter(this,
                                    "@mozilla.org/childprocessmessagemanager;1",
                                    "nsISyncMessageSender");
 
 function NfcContentHelper() {
   Services.obs.addObserver(this, NFC.TOPIC_MOZSETTINGS_CHANGED, false);
   Services.obs.addObserver(this, "xpcom-shutdown", false);
 
   this._requestMap = [];
+  this.initDOMRequestHelper(/* window */ null, NFC_IPC_MSG_NAMES);
 }
 
 NfcContentHelper.prototype = {
   __proto__: DOMRequestIpcHelper.prototype,
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsINfcContentHelper,
                                          Ci.nsINfcBrowserAPI,
                                          Ci.nsISupportsWeakReference,
@@ -83,66 +84,23 @@ NfcContentHelper.prototype = {
   classID:   NFCCONTENTHELPER_CID,
   classInfo: XPCOMUtils.generateCI({
     classID:          NFCCONTENTHELPER_CID,
     classDescription: "NfcContentHelper",
     interfaces:       [Ci.nsINfcContentHelper,
                        Ci.nsINfcBrowserAPI]
   }),
 
-  _window: null,
   _requestMap: null,
   _rfState: null,
-  _tabId: null,
   eventListener: null,
 
   init: function init(aWindow) {
-    if (aWindow == null) {
-      throw Components.Exception("Can't get window object",
-                                  Cr.NS_ERROR_UNEXPECTED);
-    }
-    this._window = aWindow;
-    this.initDOMRequestHelper(this._window, NFC_IPC_MSG_NAMES);
-
-    if (!NFC.DEBUG_CONTENT_HELPER && this._window.navigator.mozSettings) {
-      let lock = this._window.navigator.mozSettings.createLock();
-      var nfcDebug = lock.get(NFC.SETTING_NFC_DEBUG);
-      nfcDebug.onsuccess = function _nfcDebug() {
-        DEBUG = nfcDebug.result[NFC.SETTING_NFC_DEBUG];
-        updateDebug();
-      };
-    }
-
     let info = cpmm.sendSyncMessage("NFC:QueryInfo")[0];
     this._rfState = info.rfState;
-
-    // For now, we assume app will run in oop mode so we can get
-    // tab id for each app. Fix bug 1116449 if we are going to
-    // support in-process mode.
-    let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                          .getInterface(Ci.nsIWebNavigation)
-                          .QueryInterface(Ci.nsIDocShell);
-    try {
-      this._tabId = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
-                            .getInterface(Ci.nsITabChild)
-                            .tabId;
-    } catch(e) {
-      // Only parent process does not have tab id, so in this case
-      // NfcContentHelper is used by system app. Use -1(tabId) to
-      // indicate its system app.
-      let inParent = Cc["@mozilla.org/xre/app-info;1"]
-                       .getService(Ci.nsIXULRuntime)
-                       .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-      if (inParent) {
-        this._tabId = Ci.nsINfcBrowserAPI.SYSTEM_APP_ID;
-      } else {
-        throw Components.Exception("Can't get tab id in child process",
-                                   Cr.NS_ERROR_UNEXPECTED);
-      }
-    }
   },
 
   queryRFState: function queryRFState() {
     return this._rfState;
   },
 
   encodeNDEFRecords: function encodeNDEFRecords(records) {
     if (!Array.isArray(records)) {
@@ -237,19 +195,31 @@ NfcContentHelper.prototype = {
 
   notifySendFileStatus: function notifySendFileStatus(status, requestId) {
     cpmm.sendAsyncMessage("NFC:NotifySendFileStatus", {
       status: status,
       requestId: requestId
     });
   },
 
-  addEventListener: function addEventListener(listener) {
+  addEventListener: function addEventListener(listener, tabId) {
+    let _window = listener.window;
+
+    // TODO Bug 1166210 - enable NFC debug for child process.
+    if (!NFC.DEBUG_CONTENT_HELPER && _window.navigator.mozSettings) {
+      let lock = _window.navigator.mozSettings.createLock();
+      var nfcDebug = lock.get(NFC.SETTING_NFC_DEBUG);
+      nfcDebug.onsuccess = function _nfcDebug() {
+        DEBUG = nfcDebug.result[NFC.SETTING_NFC_DEBUG];
+        updateDebug();
+      };
+    }
+
     this.eventListener = listener;
-    cpmm.sendAsyncMessage("NFC:AddEventListener", { tabId: this._tabId });
+    cpmm.sendAsyncMessage("NFC:AddEventListener", { tabId: tabId });
   },
 
   registerTargetForPeerReady: function registerTargetForPeerReady(appId) {
     cpmm.sendAsyncMessage("NFC:RegisterPeerReadyTarget", { appId: appId });
   },
 
   unregisterTargetForPeerReady: function unregisterTargetForPeerReady(appId) {
     cpmm.sendAsyncMessage("NFC:UnregisterPeerReadyTarget", { appId: appId });
@@ -413,26 +383,17 @@ NfcContentHelper.prototype = {
     }
     delete this._requestMap[requestId];
 
     if (result.errorMsg) {
       callback.notifyError(result.errorMsg);
       return;
     }
 
-    let ndefMsg = new this._window.Array();
-    let records = result.records;
-    for (let i = 0; i < records.length; i++) {
-      let record = records[i];
-      ndefMsg.push(new this._window.MozNDEFRecord({tnf: record.tnf,
-                                                   type: record.type,
-                                                   id: record.id,
-                                                   payload: record.payload}));
-    }
-    callback.notifySuccessWithNDEFRecords(ndefMsg);
+    callback.notifySuccessWithNDEFRecords(result.records);
   },
 
   handleCheckP2PRegistrationResponse: function handleCheckP2PRegistrationResponse(result) {
     let requestId = result.requestId;
     let callback = this._requestMap[requestId];
     if (!callback) {
       debug("not firing message handleCheckP2PRegistrationResponse for id: " + requestId);
       return;
--- a/dom/nfc/nsINfcContentHelper.idl
+++ b/dom/nfc/nsINfcContentHelper.idl
@@ -119,17 +119,17 @@ interface nsINfcRequestCallback : nsISup
 interface nsINfcBrowserAPI : nsISupports
 {
   const int32_t SYSTEM_APP_ID = -1;
 
   void setFocusApp(in uint64_t tabId,
                    in boolean isFocus);
 };
 
-[scriptable, uuid(39e1b25b-5063-449e-b9e8-5514cdca9c3a)]
+[scriptable, uuid(080a84f1-f039-46ed-9dc6-f34ce3aa9638)]
 interface nsINfcContentHelper : nsISupports
 {
   void init(in nsIDOMWindow window);
 
   /**
    * Read current NDEF data on the tag.
    *
    * @param sessionToken
@@ -225,18 +225,20 @@ interface nsINfcContentHelper : nsISuppo
                 in DOMString sessionToken,
                 in nsINfcRequestCallback callback);
 
   /**
    * Add the event listener.
    *
    * @param listener
    *        An instance of the nsINfcEventListener.
+   * @param tabId
+   *        The tab ID of the listener.
    */
-  void addEventListener(in nsINfcEventListener listener);
+  void addEventListener(in nsINfcEventListener listener, in uint64_t tabId);
 
   /**
    * Register the given application id with parent process
    *
    * @param appId
    *        Application ID to be registered
    */
   void registerTargetForPeerReady(in unsigned long appId);
--- a/dom/nfc/nsNfc.js
+++ b/dom/nfc/nsNfc.js
@@ -68,17 +68,26 @@ NfcCallback.prototype = {
   },
 
   notifySuccessWithNDEFRecords: function notifySuccessWithNDEFRecords(aRecords) {
     let resolver = this.takePromiseResolver(atob(this._requestId));
     if (!resolver) {
       debug("can not find promise resolver for id: " + this._requestId);
       return;
     }
-    resolver.resolve(aRecords);
+
+    let records = new this._window.Array();
+    for (let i = 0; i < aRecords.length; i++) {
+      let record = aRecords[i];
+      records.push(new this._window.MozNDEFRecord({tnf: record.tnf,
+                                                   type: record.type,
+                                                   id: record.id,
+                                                   payload: record.payload}));
+    }
+    resolver.resolve(records);
   },
 
   notifySuccessWithByteArray: function notifySuccessWithByteArray(aArray) {
     let resolver = this.takePromiseResolver(atob(this._requestId));
     if (!resolver) {
       debug("can not find promise resolver for id: " + this._requestId);
       return;
     }
@@ -330,16 +339,17 @@ function MozNFCImpl() {
   }
 
   this.eventService = Cc["@mozilla.org/eventlistenerservice;1"]
                         .getService(Ci.nsIEventListenerService);
 }
 MozNFCImpl.prototype = {
   _nfcContentHelper: null,
   window: null,
+  _tabId: null,
   _rfState: null,
   _contentObj: null,
   nfcPeer: null,
   nfcTag: null,
   eventService: null,
 
   init: function init(aWindow) {
     debug("MozNFCImpl init called");
@@ -347,21 +357,52 @@ MozNFCImpl.prototype = {
     this.defineEventHandlerGetterSetter("ontagfound");
     this.defineEventHandlerGetterSetter("ontaglost");
     this.defineEventHandlerGetterSetter("onpeerready");
     this.defineEventHandlerGetterSetter("onpeerfound");
     this.defineEventHandlerGetterSetter("onpeerlost");
 
     if (this._nfcContentHelper) {
       this._nfcContentHelper.init(aWindow);
-      this._nfcContentHelper.addEventListener(this);
+      this._tabId = this.getTabId(aWindow);
+      this._nfcContentHelper.addEventListener(this, this._tabId);
       this._rfState = this._nfcContentHelper.queryRFState();
     }
   },
 
+  getTabId: function getTabId(aWindow) {
+    let tabId;
+    // For now, we assume app will run in oop mode so we can get
+    // tab id for each app. Fix bug 1116449 if we are going to
+    // support in-process mode.
+    let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+                          .getInterface(Ci.nsIWebNavigation)
+                          .QueryInterface(Ci.nsIDocShell);
+    try {
+      tabId = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
+                      .getInterface(Ci.nsITabChild)
+                      .tabId;
+    } catch(e) {
+      // Only parent process does not have tab id, so in this case
+      // NfcContentHelper is used by system app. Use -1(tabId) to
+      // indicate its system app.
+      let inParent = Cc["@mozilla.org/xre/app-info;1"]
+                       .getService(Ci.nsIXULRuntime)
+                       .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
+      if (inParent) {
+        tabId = Ci.nsINfcBrowserAPI.SYSTEM_APP_ID;
+      } else {
+        throw Components.Exception("Can't get tab id in child process",
+                                   Cr.NS_ERROR_UNEXPECTED);
+      }
+    }
+
+    return tabId;
+  },
+
   // Only apps which have nfc-manager permission can call the following interfaces
   // 'checkP2PRegistration' , 'notifyUserAcceptedP2P' , 'notifySendFileStatus',
   // 'startPoll', 'stopPoll', and 'powerOff'.
   checkP2PRegistration: function checkP2PRegistration(manifestUrl) {
     // Get the AppID and pass it to ContentHelper
     let appID = appsService.getAppLocalIdByManifestURL(manifestUrl);
 
     let callback = new NfcCallback(this.window);