--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -171,19 +171,16 @@
@RESPATH@/components/dom_css.xpt
@RESPATH@/components/dom_events.xpt
@RESPATH@/components/dom_geolocation.xpt
@RESPATH@/components/dom_media.xpt
@RESPATH@/components/dom_network.xpt
#ifdef MOZ_SECUREELEMENT
@RESPATH@/components/dom_secureelement.xpt
#endif
-#ifdef MOZ_NFC
-@RESPATH@/components/dom_nfc.xpt
-#endif
@RESPATH@/components/dom_notification.xpt
@RESPATH@/components/dom_html.xpt
@RESPATH@/components/dom_offline.xpt
@RESPATH@/components/dom_json.xpt
@RESPATH@/components/dom_messages.xpt
@RESPATH@/components/dom_power.xpt
@RESPATH@/components/dom_push.xpt
@RESPATH@/components/dom_quota.xpt
@@ -552,24 +549,16 @@
@RESPATH@/components/messageWakeupService.manifest
@RESPATH@/components/SettingsManager.js
@RESPATH@/components/SettingsManager.manifest
@RESPATH@/components/SettingsService.js
@RESPATH@/components/SettingsService.manifest
@RESPATH@/components/webvtt.xpt
@RESPATH@/components/WebVTT.manifest
@RESPATH@/components/WebVTTParserWrapper.js
-#ifdef MOZ_NFC
-@RESPATH@/components/nsNfc.manifest
-@RESPATH@/components/nsNfc.js
-@RESPATH@/components/Nfc.manifest
-@RESPATH@/components/Nfc.js
-@RESPATH@/components/NfcContentHelper.manifest
-@RESPATH@/components/NfcContentHelper.js
-#endif
#ifdef MOZ_SECUREELEMENT
@RESPATH@/components/DOMSecureElement.manifest
@RESPATH@/components/DOMSecureElement.js
#endif
@RESPATH@/components/nsINIProcessor.manifest
@RESPATH@/components/nsINIProcessor.js
@RESPATH@/components/nsPrompter.manifest
@RESPATH@/components/nsPrompter.js
--- a/dom/apps/PermissionsTable.jsm
+++ b/dom/apps/PermissionsTable.jsm
@@ -355,36 +355,16 @@ this.PermissionsTable = { geolocation:
privileged: ALLOW_ACTION,
certified: ALLOW_ACTION
},
"audio-capture:3gpp2": {
app: DENY_ACTION,
privileged: ALLOW_ACTION,
certified: ALLOW_ACTION
},
- "nfc": {
- app: DENY_ACTION,
- privileged: ALLOW_ACTION,
- certified: ALLOW_ACTION
- },
- "nfc-share": {
- app: DENY_ACTION,
- privileged: DENY_ACTION,
- certified: ALLOW_ACTION
- },
- "nfc-manager": {
- app: DENY_ACTION,
- privileged: DENY_ACTION,
- certified: ALLOW_ACTION
- },
- "nfc-hci-events": {
- app: DENY_ACTION,
- privileged: DENY_ACTION,
- certified: ALLOW_ACTION
- },
"speaker-control": {
app: DENY_ACTION,
privileged: ALLOW_ACTION,
certified: ALLOW_ACTION
},
"downloads": {
app: DENY_ACTION,
privileged: DENY_ACTION,
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -1959,29 +1959,16 @@ Navigator::HasWifiManagerSupport(JSConte
// and test directly with permission manager.
nsIPrincipal* principal = nsContentUtils::ObjectPrincipal(aGlobal);
uint32_t permission = GetPermission(principal, "wifi-manage");
return permission == nsIPermissionManager::ALLOW_ACTION;
}
-#ifdef MOZ_NFC
-/* static */
-bool
-Navigator::HasNFCSupport(JSContext* /* unused */, JSObject* aGlobal)
-{
- nsCOMPtr<nsPIDOMWindowInner> win = GetWindowFromGlobal(aGlobal);
-
- // Do not support NFC if NFC content helper does not exist.
- nsCOMPtr<nsISupports> contentHelper = do_GetService("@mozilla.org/nfc/content-helper;1");
- return !!contentHelper;
-}
-#endif // MOZ_NFC
-
/* static */
bool
Navigator::HasUserMediaSupport(JSContext* /* unused */,
JSObject* /* unused */)
{
// Make enabling peerconnection enable getUserMedia() as well
return Preferences::GetBool("media.navigator.enabled", false) ||
Preferences::GetBool("media.peerconnection.enabled", false);
--- a/dom/base/Navigator.h
+++ b/dom/base/Navigator.h
@@ -272,19 +272,16 @@ public:
StorageManager* Storage();
static void GetAcceptLanguages(nsTArray<nsString>& aLanguages);
// WebIDL helper methods
static bool HasWakeLockSupport(JSContext* /* unused*/, JSObject* /*unused */);
static bool HasWifiManagerSupport(JSContext* /* unused */,
JSObject* aGlobal);
-#ifdef MOZ_NFC
- static bool HasNFCSupport(JSContext* /* unused */, JSObject* aGlobal);
-#endif // MOZ_NFC
static bool HasUserMediaSupport(JSContext* /* unused */,
JSObject* /* unused */);
static bool IsE10sEnabled(JSContext* aCx, JSObject* aGlobal);
nsPIDOMWindowInner* GetParentObject() const
{
return GetWindow();
--- a/dom/base/StructuredCloneHolder.cpp
+++ b/dom/base/StructuredCloneHolder.cpp
@@ -36,19 +36,16 @@
#include "mozilla/gfx/2D.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "MultipartBlobImpl.h"
#include "nsIRemoteBlob.h"
#include "nsQueryObject.h"
-#ifdef MOZ_NFC
-#include "mozilla/dom/MozNDEFRecord.h"
-#endif // MOZ_NFC
#ifdef MOZ_WEBRTC
#include "mozilla/dom/RTCCertificate.h"
#include "mozilla/dom/RTCCertificateBinding.h"
#endif
using namespace mozilla::ipc;
namespace mozilla {
@@ -401,38 +398,16 @@ StructuredCloneHolder::ReadFullySerializ
if (NS_FAILED(rv)) {
xpc::Throw(aCx, NS_ERROR_DOM_DATA_CLONE_ERR);
return nullptr;
}
return result.toObjectOrNull();
}
-#ifdef MOZ_NFC
- if (aTag == SCTAG_DOM_NFC_NDEF) {
- if (!NS_IsMainThread()) {
- return nullptr;
- }
-
- nsIGlobalObject *global = xpc::NativeGlobal(JS::CurrentGlobalOrNull(aCx));
- if (!global) {
- return nullptr;
- }
-
- // Prevent the return value from being trashed by a GC during ~nsRefPtr.
- JS::Rooted<JSObject*> result(aCx);
- {
- RefPtr<MozNDEFRecord> ndefRecord = new MozNDEFRecord(global);
- result = ndefRecord->ReadStructuredClone(aCx, aReader) ?
- ndefRecord->WrapObject(aCx, nullptr) : nullptr;
- }
- return result;
- }
-#endif
-
#ifdef MOZ_WEBRTC
if (aTag == SCTAG_DOM_RTC_CERTIFICATE) {
if (!NS_IsMainThread()) {
return nullptr;
}
nsIGlobalObject *global = xpc::NativeGlobal(JS::CurrentGlobalOrNull(aCx));
if (!global) {
@@ -505,27 +480,16 @@ StructuredCloneHolder::WriteFullySeriali
nsCOMPtr<nsISupports> base = xpc::UnwrapReflectorToISupports(aObj);
nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(base);
if (principal) {
auto nsjsprincipals = nsJSPrincipals::get(principal);
return nsjsprincipals->write(aCx, aWriter);
}
}
-#ifdef MOZ_NFC
- {
- MozNDEFRecord* ndefRecord = nullptr;
- if (NS_SUCCEEDED(UNWRAP_OBJECT(MozNDEFRecord, aObj, ndefRecord))) {
- MOZ_ASSERT(NS_IsMainThread());
- return JS_WriteUint32Pair(aWriter, SCTAG_DOM_NFC_NDEF, 0) &&
- ndefRecord->WriteStructuredClone(aCx, aWriter);
- }
- }
-#endif // MOZ_NFC
-
// Don't know what this is
xpc::Throw(aCx, NS_ERROR_DOM_DATA_CLONE_ERR);
return false;
}
namespace {
// Recursive!
--- a/dom/base/StructuredCloneTags.h
+++ b/dom/base/StructuredCloneTags.h
@@ -35,17 +35,16 @@ enum StructuredCloneTags {
// This tag is for WebCrypto keys
SCTAG_DOM_WEBCRYPTO_KEY,
SCTAG_DOM_NULL_PRINCIPAL,
SCTAG_DOM_SYSTEM_PRINCIPAL,
SCTAG_DOM_CONTENT_PRINCIPAL,
- SCTAG_DOM_NFC_NDEF,
SCTAG_DOM_IMAGEBITMAP,
SCTAG_DOM_RTC_CERTIFICATE,
SCTAG_DOM_FORMDATA,
// This tag is for OffscreenCanvas.
SCTAG_DOM_CANVAS,
--- a/dom/base/test/mozbrowser_api_utils.js
+++ b/dom/base/test/mozbrowser_api_utils.js
@@ -16,17 +16,16 @@ const METHODS = {
download: {},
purgeHistory: {},
getScreenshot: {},
zoom: {},
getCanGoBack: {},
getCanGoForward: {},
getContentDimensions: {},
setInputMethodActive: {},
- setNFCFocus: {},
findAll: {},
findNext: {},
clearMatch: {},
executeScript: {},
getWebManifest: {},
mute: {},
unmute: {},
getMuted: {},
--- a/dom/browser-element/BrowserElementParent.js
+++ b/dom/browser-element/BrowserElementParent.js
@@ -124,17 +124,16 @@ BrowserElementParentProxyCallHandler.pro
case 'setActive':
case 'sendMouseEvent':
case 'sendTouchEvent':
case 'goBack':
case 'goForward':
case 'reload':
case 'stop':
case 'zoom':
- case 'setNFCFocus':
case 'findAll':
case 'findNext':
case 'clearMatch':
case 'mute':
case 'unmute':
case 'setVolume':
this._frameElement[data.methodName]
.apply(this._frameElement, data.args);
@@ -1084,45 +1083,16 @@ BrowserElementParent.prototype = {
throw Components.Exception("Invalid argument",
Cr.NS_ERROR_INVALID_ARG);
}
return this._sendDOMRequest('set-input-method-active',
{isActive: isActive});
},
- setNFCFocus: function(isFocus) {
- if (!this._isAlive()) {
- throw Components.Exception("Dead content process",
- Cr.NS_ERROR_DOM_INVALID_STATE_ERR);
- }
-
- // For now, we use tab id as an identifier to let NFC module know
- // which app is in foreground. But this approach will not work in
- // in-process mode because tab id doesn't exist. Fix bug 1116449
- // if we are going to support in-process mode.
- try {
- var tabId = this._frameLoader.QueryInterface(Ci.nsIFrameLoader)
- .tabParent
- .tabId;
- } catch(e) {
- debug("SetNFCFocus for in-process mode is not yet supported");
- throw Components.Exception("SetNFCFocus for in-process mode is not yet supported",
- Cr.NS_ERROR_NOT_IMPLEMENTED);
- }
-
- try {
- let nfcContentHelper =
- Cc["@mozilla.org/nfc/content-helper;1"].getService(Ci.nsINfcBrowserAPI);
- nfcContentHelper.setFocusTab(tabId, isFocus);
- } catch(e) {
- // Not all platforms support NFC
- }
- },
-
getAudioChannelVolume: function(aAudioChannel) {
return this._sendDOMRequest('get-audio-channel-volume',
{audioChannel: aAudioChannel});
},
setAudioChannelVolume: function(aAudioChannel, aVolume) {
return this._sendDOMRequest('set-audio-channel-volume',
{audioChannel: aAudioChannel,
--- a/dom/browser-element/BrowserElementProxy.js
+++ b/dom/browser-element/BrowserElementProxy.js
@@ -187,17 +187,16 @@ BrowserElementProxy.prototype = {
setActive: defineNoReturnMethod('setActive'),
sendMouseEvent: defineNoReturnMethod('sendMouseEvent'),
sendTouchEvent: defineNoReturnMethod('sendTouchEvent'),
goBack: defineNoReturnMethod('goBack'),
goForward: defineNoReturnMethod('goForward'),
reload: defineNoReturnMethod('reload'),
stop: defineNoReturnMethod('stop'),
zoom: defineNoReturnMethod('zoom'),
- setNFCFocus: defineNoReturnMethod('setNFCFocus'),
findAll: defineNoReturnMethod('findAll'),
findNext: defineNoReturnMethod('findNext'),
clearMatch: defineNoReturnMethod('clearMatch'),
mute: defineNoReturnMethod('mute'),
unmute: defineNoReturnMethod('unmute'),
setVolume: defineNoReturnMethod('setVolume'),
getVisible: defineDOMRequestMethod('getVisible'),
deleted file mode 100644
--- a/dom/browser-element/mochitest/browserElement_SetNFCFocus.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Any copyright is dedicated to the public domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Bug 1188639 - Check permission to use setNFCFocus
-"use strict";
-
-SimpleTest.waitForExplicitFinish();
-browserElementTestHelpers.setEnabledPref(true);
-
-function hasSetNFCFocus() {
- return new Promise((resolve, reject) => {
- var iframe = document.createElement('iframe');
- iframe.setAttribute('mozbrowser', 'true');
- iframe.addEventListener('mozbrowserloadend', e => {
- is(iframe.setNFCFocus !== undefined, true,
- "has permission to use setNFCFocus");
- resolve();
- });
- document.body.appendChild(iframe);
- });
-}
-
-function runTest() {
- hasSetNFCFocus().then(SimpleTest.finish);
-}
-
-addEventListener('testready', runTest);
--- a/dom/browser-element/mochitest/chrome.ini
+++ b/dom/browser-element/mochitest/chrome.ini
@@ -22,17 +22,16 @@ support-files =
browserElement_GetScreenshotDppx.js
browserElement_getWebManifest.js
browserElement_NextPaint.js
browserElement_NoAudioTrack.js
browserElement_PurgeHistory.js
browserElement_ReloadPostRequest.js
browserElement_SendEvent.js
browserElement_SetInputMethodActive.js
- browserElement_SetNFCFocus.js
browserElement_SetVisible.js
browserElement_SetVisibleFrames.js
browserElement_SetVisibleFrames2.js
browserElement_Stop.js
browserElement_VisibilityChange.js
file_audio.html
file_browserElement_ActiveStateChange.html
file_browserElement_AudioChannelSeeking.html
@@ -81,14 +80,13 @@ tags = audiochannel
tags = audiochannel
[test_browserElement_inproc_PurgeHistory.html]
[test_browserElement_inproc_ReloadPostRequest.html]
disabled = no modal prompt on POST reload for chrome window
[test_browserElement_inproc_SendEvent.html]
# The setInputMethodActive() tests will timed out on Android
[test_browserElement_inproc_SetInputMethodActive.html]
skip-if = (os == "android")
-[test_browserElement_inproc_SetNFCFocus.html]
[test_browserElement_inproc_SetVisible.html]
[test_browserElement_inproc_SetVisibleFrames.html]
[test_browserElement_inproc_SetVisibleFrames2.html]
[test_browserElement_inproc_Stop.html]
[test_browserElement_inproc_VisibilityChange.html]
--- a/dom/browser-element/mochitest/mochitest-oop.ini
+++ b/dom/browser-element/mochitest/mochitest-oop.ini
@@ -140,17 +140,15 @@ disabled = bug 924771
[test_browserElement_oop_GetContentDimensions.html]
disabled = Disabling some OOP tests for WebIDL scope changes
[test_browserElement_oop_AudioChannel.html]
tags = audiochannel
disabled = Disabling some OOP tests for WebIDL scope changes
[test_browserElement_oop_AudioChannel_nested.html]
tags = audiochannel
disabled = Disabling some OOP tests for WebIDL scope changes
-[test_browserElement_oop_SetNFCFocus.html]
-disabled = Disabling some OOP tests for WebIDL scope changes
[test_browserElement_oop_getWebManifest.html]
disabled = Disabling some OOP tests for WebIDL scope changes
[test_browserElement_oop_OpenWindowEmpty.html]
skip-if = (toolkit == 'gonk') # Test doesn't work on B2G emulator
[test_browserElement_oop_ActiveStateChange.html]
tags = audiochannel
disabled = Disabling some OOP tests for WebIDL scope changes
deleted file mode 100644
--- a/dom/browser-element/mochitest/test_browserElement_inproc_SetNFCFocus.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Bug 1188639</title>
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <script type="application/javascript" src="browserElementTestHelpers.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<script type="application/javascript;version=1.7" src="browserElement_SetNFCFocus.js">
-</script>
-</body>
-</html>
deleted file mode 100644
--- a/dom/browser-element/mochitest/test_browserElement_oop_SetNFCFocus.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Bug 1188639</title>
- <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="application/javascript" src="browserElementTestHelpers.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<script type="application/javascript;version=1.7" src="browserElement_SetNFCFocus.js">
-</script>
-</body>
-</html>
--- a/dom/browser-element/nsIBrowserElementAPI.idl
+++ b/dom/browser-element/nsIBrowserElementAPI.idl
@@ -97,18 +97,16 @@ interface nsIBrowserElementAPI : nsISupp
nsIDOMDOMRequest getAudioChannelVolume(in uint32_t audioChannel);
nsIDOMDOMRequest setAudioChannelVolume(in uint32_t audioChannel, in float volume);
nsIDOMDOMRequest getAudioChannelMuted(in uint32_t audioChannel);
nsIDOMDOMRequest setAudioChannelMuted(in uint32_t audioChannel, in bool muted);
nsIDOMDOMRequest isAudioChannelActive(in uint32_t audioChannel);
- void setNFCFocus(in boolean isFocus);
-
nsIDOMDOMRequest executeScript(in DOMString script, in jsval options);
/**
* Returns an object that represents a Web Manifest:
* http://w3c.github.io/manifest/
*/
nsIDOMDOMRequest getWebManifest();
};
--- a/dom/events/test/test_all_synthetic_events.html
+++ b/dom/events/test/test_all_synthetic_events.html
@@ -330,24 +330,16 @@ const kEventConstructors = {
MozMessageDeletedEvent: { create: function (aName, aProps) {
return new MozMessageDeletedEvent(aName, aProps);
},
},
MozMmsEvent: { create: function (aName, aProps) {
return new MozMmsEvent(aName, aProps);
},
},
- MozNFCPeerEvent: { create: function (aName, aProps) {
- return new MozNFCPeerEvent(aName, aProps);
- },
- },
- MozNFCTagEvent: { create: function (aName, aProps) {
- return new MozNFCTagEvent(aName, aProps);
- },
- },
MozOtaStatusEvent: { create: function (aName, aProps) {
return new MozOtaStatusEvent(aName, aProps);
},
},
MozSettingsEvent: { create: function (aName, aProps) {
return new MozSettingsEvent(aName, aProps);
},
},
--- a/dom/html/nsBrowserElement.cpp
+++ b/dom/html/nsBrowserElement.cpp
@@ -664,28 +664,16 @@ nsBrowserElement::SetVolume(float aVolum
nsresult rv = mBrowserElementAPI->SetVolume(aVolume);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
}
}
-void
-nsBrowserElement::SetNFCFocus(bool aIsFocus,
- ErrorResult& aRv)
-{
- NS_ENSURE_TRUE_VOID(IsBrowserElementOrThrow(aRv));
-
- nsresult rv = mBrowserElementAPI->SetNFCFocus(aIsFocus);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
- }
-}
-
already_AddRefed<DOMRequest>
nsBrowserElement::ExecuteScript(const nsAString& aScript,
const BrowserElementExecuteScriptOptions& aOptions,
ErrorResult& aRv)
{
NS_ENSURE_TRUE(IsBrowserElementOrThrow(aRv), nullptr);
nsCOMPtr<nsIDOMDOMRequest> req;
--- a/dom/html/nsBrowserElement.h
+++ b/dom/html/nsBrowserElement.h
@@ -109,19 +109,16 @@ public:
ErrorResult& aRv);
already_AddRefed<dom::DOMRequest> ExecuteScript(const nsAString& aScript,
const dom::BrowserElementExecuteScriptOptions& aOptions,
ErrorResult& aRv);
already_AddRefed<dom::DOMRequest> GetWebManifest(ErrorResult& aRv);
- void SetNFCFocus(bool isFocus,
- ErrorResult& aRv);
-
// Helper
static void GenerateAllowedAudioChannels(
nsPIDOMWindowInner* aWindow,
nsIFrameLoader* aFrameLoader,
nsIBrowserElementAPI* aAPI,
nsTArray<RefPtr<dom::BrowserElementAudioChannel>>& aAudioChannels,
ErrorResult& aRv);
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -121,19 +121,16 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk
'wifi',
]
if CONFIG['MOZ_B2G_RIL']:
DIRS += [
'wappush',
]
-if CONFIG['MOZ_NFC']:
- DIRS += ['nfc']
-
if CONFIG['MOZ_SECUREELEMENT']:
DIRS += ['secureelement']
if CONFIG['MOZ_B2G']:
DIRS += [
'downloads',
]
deleted file mode 100644
--- a/dom/nfc/MozIsoDepTech.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "MozIsoDepTech.h"
-#include "TagUtils.h"
-#include "mozilla/dom/Promise.h"
-
-using namespace mozilla::dom::nfc;
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(MozIsoDepTech)
-
-NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(MozIsoDepTech)
- NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_TRACE_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MozIsoDepTech)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTag)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MozIsoDepTech)
- NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
- NS_IMPL_CYCLE_COLLECTION_UNLINK(mTag)
- NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MozIsoDepTech)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MozIsoDepTech)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MozIsoDepTech)
- NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
- NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-const NFCTechType MozIsoDepTech::sTechnology = NFCTechType::ISO_DEP;
-
-/* static */
-already_AddRefed<MozIsoDepTech>
-MozIsoDepTech::Constructor(const GlobalObject& aGlobal,
- MozNFCTag& aNFCTag,
- ErrorResult& aRv)
-{
- ErrorResult rv;
- nsCOMPtr<nsPIDOMWindowInner> win = do_QueryInterface(aGlobal.GetAsSupports());
- if (!win) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- if (!TagUtils::IsTechSupported(aNFCTag, sTechnology)) {
- aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
- return nullptr;
- }
-
- RefPtr<MozIsoDepTech> isoDep = new MozIsoDepTech(win, aNFCTag);
-
- return isoDep.forget();
-}
-
-MozIsoDepTech::MozIsoDepTech(nsPIDOMWindowInner* aWindow, MozNFCTag& aNFCTag)
- : mWindow(aWindow)
- , mTag(&aNFCTag)
-{
-}
-
-MozIsoDepTech::~MozIsoDepTech()
-{
-}
-
-already_AddRefed<Promise>
-MozIsoDepTech::Transceive(const Uint8Array& aCommand, ErrorResult& aRv)
-{
- return TagUtils::Transceive(mTag, sTechnology, aCommand, aRv);
-}
-
-JSObject*
-MozIsoDepTech::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return MozIsoDepTechBinding::Wrap(aCx, this, aGivenProto);
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/nfc/MozIsoDepTech.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef mozilla_dom_nfc_MozIsoDepTech_h__
-#define mozilla_dom_nfc_MozIsoDepTech_h__
-
-#include "mozilla/dom/MozNFCTagBinding.h"
-#include "mozilla/dom/MozIsoDepTechBinding.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsWrapperCache.h"
-#include "nsISupportsImpl.h"
-#include "nsPIDOMWindow.h"
-
-namespace mozilla {
-namespace dom {
-
-class Promise;
-
-class MozIsoDepTech : public nsISupports,
- public nsWrapperCache
-{
-public:
- NS_DECL_CYCLE_COLLECTING_ISUPPORTS
- NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MozIsoDepTech)
-
- already_AddRefed<Promise> Transceive(const Uint8Array& aCommand,
- ErrorResult& aRv);
-
- nsPIDOMWindowInner* GetParentObject() const { return mWindow; }
-
- virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
- static already_AddRefed<MozIsoDepTech>
- Constructor(const GlobalObject& aGlobal, MozNFCTag& aNFCTag,
- ErrorResult& aRv);
-
-private:
- MozIsoDepTech(nsPIDOMWindowInner* aWindow, MozNFCTag& aNFCTag);
- virtual ~MozIsoDepTech();
-
- RefPtr<nsPIDOMWindowInner> mWindow;
- RefPtr<MozNFCTag> mTag;
-
- static const NFCTechType sTechnology;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_nfc_MozIsoDepTech_h__
deleted file mode 100644
--- a/dom/nfc/MozNDEFRecord.cpp
+++ /dev/null
@@ -1,413 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-/* Copyright © 2013 Deutsche Telekom, Inc. */
-
-#include "MozNDEFRecord.h"
-#include "js/StructuredClone.h"
-#include "mozilla/dom/MozNDEFRecordBinding.h"
-#include "mozilla/HoldDropJSObjects.h"
-#include "nsContentUtils.h"
-#include "nsIGlobalObject.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(MozNDEFRecord)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MozNDEFRecord)
- NS_IMPL_CYCLE_COLLECTION_UNLINK(mParent)
- NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
- tmp->DropData();
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MozNDEFRecord)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParent)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(MozNDEFRecord)
- NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mType)
- NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mId)
- NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mPayload)
- NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_TRACE_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MozNDEFRecord)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MozNDEFRecord)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MozNDEFRecord)
- NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
- NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-void
-MozNDEFRecord::HoldData()
-{
- mozilla::HoldJSObjects(this);
-}
-
-void
-MozNDEFRecord::DropData()
-{
- if (mType) {
- mType = nullptr;
- }
- if (mId) {
- mId = nullptr;
- }
- if (mPayload) {
- mPayload = nullptr;
- }
- mozilla::DropJSObjects(this);
-}
-
-/**
- * Validate TNF.
- * See section 3.3 THE NDEF Specification Test Requirements,
- * NDEF specification 1.0
- */
-/* static */ bool
-MozNDEFRecord::ValidateTNF(const MozNDEFRecordOptions& aOptions,
- ErrorResult& aRv)
-{
- // * The TNF field MUST have a value between 0x00 and 0x06.
- // * The TNF value MUST NOT be 0x07.
- // These two requirements are already handled by WebIDL bindings.
-
- // If the TNF value is 0x00 (Empty), the TYPE, ID, and PAYLOAD fields MUST be
- // omitted from the record.
- if ((aOptions.mTnf == TNF::Empty) &&
- (aOptions.mType.WasPassed() || aOptions.mId.WasPassed() ||
- aOptions.mPayload.WasPassed())) {
- NS_WARNING("tnf is empty but type/id/payload is not null.");
- aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
- return false;
- }
-
- // If the TNF value is 0x05 (Unknown) or 0x06(Unchanged), the TYPE field MUST
- // be omitted from the NDEF record.
- if ((aOptions.mTnf == TNF::Unknown || aOptions.mTnf == TNF::Unchanged) &&
- aOptions.mType.WasPassed()) {
- NS_WARNING("tnf is unknown/unchanged but type is not null.");
- aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
- return false;
- }
-
- return true;
-}
-
-/* static */ already_AddRefed<MozNDEFRecord>
-MozNDEFRecord::Constructor(const GlobalObject& aGlobal,
- const MozNDEFRecordOptions& aOptions,
- ErrorResult& aRv)
-{
- if (!ValidateTNF(aOptions, aRv)) {
- return nullptr;
- }
-
- nsCOMPtr<nsISupports> parent = do_QueryInterface(aGlobal.GetAsSupports());
- if (!parent) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- JSContext* context = aGlobal.Context();
- RefPtr<MozNDEFRecord> ndefRecord = new MozNDEFRecord(parent, aOptions.mTnf);
- ndefRecord->InitType(context, aOptions.mType);
- ndefRecord->InitId(context, aOptions.mId);
- ndefRecord->InitPayload(context, aOptions.mPayload);
-
- return ndefRecord.forget();
-}
-
-/* static */ already_AddRefed<MozNDEFRecord>
-MozNDEFRecord::Constructor(const GlobalObject& aGlobal,
- const nsAString& aUri,
- ErrorResult& aRv)
-{
- if (aUri.IsVoid()) {
- aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
- return nullptr;
- }
-
- nsCOMPtr<nsISupports> parent = do_QueryInterface(aGlobal.GetAsSupports());
- if (!parent) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- RefPtr<MozNDEFRecord> ndefRecord = new MozNDEFRecord(parent, TNF::Well_known);
- ndefRecord->InitType(aGlobal.Context(), RTD::U);
- ndefRecord->InitPayload(aGlobal.Context(), aUri);
- return ndefRecord.forget();
-}
-
-MozNDEFRecord::MozNDEFRecord(nsISupports* aParent, TNF aTnf)
- : mParent(aParent) // For GetParentObject()
- , mTnf(aTnf)
- , mSize(3) // 1(flags) + 1(type_length) + 1(payload_length)
-{
- HoldData();
-}
-
-void
-MozNDEFRecord::GetAsURI(nsAString& aRetVal)
-{
- aRetVal.SetIsVoid(true);
- if (mTnf != TNF::Well_known) {
- return;
- }
-
- JS::AutoCheckCannotGC nogc;
- bool isShared = false;
- uint8_t* typeData = JS_GetUint8ArrayData(mType, &isShared, nogc);
- if (isShared) {
- return; // Must opt in to shared memory
- }
- const char* uVal = RTDValues::strings[static_cast<uint32_t>(RTD::U)].value;
- if (typeData[0] != uVal[0]) {
- return;
- }
-
- uint32_t payloadLen;
- uint8_t* payloadData;
- js::GetUint8ArrayLengthAndData(mPayload, &payloadLen, &isShared, &payloadData);
- if (isShared) {
- return; // Must opt in to shared memory
- }
- uint8_t id = payloadData[0];
- if (id >= static_cast<uint8_t>(WellKnownURIPrefix::EndGuard_)) {
- return;
- }
-
- using namespace mozilla::dom::WellKnownURIPrefixValues;
- aRetVal.AssignASCII(strings[id].value);
- aRetVal.Append(NS_ConvertUTF8toUTF16(
- nsDependentCSubstring(reinterpret_cast<char*>(&payloadData[1]), payloadLen - 1)));
-}
-
-bool
-MozNDEFRecord::WriteStructuredClone(JSContext* aCx, JSStructuredCloneWriter* aWriter) const
-{
- uint8_t* dummy;
- uint32_t typeLen = 0, idLen = 0, payloadLen = 0;
- bool isShared;
- if (mType) {
- js::GetUint8ArrayLengthAndData(mType, &typeLen, &isShared, &dummy);
- if (isShared) {
- return false; // Must opt in to shared memory
- }
- }
-
- if (mId) {
- js::GetUint8ArrayLengthAndData(mId, &idLen, &isShared, &dummy);
- if (isShared) {
- return false; // Must opt in to shared memory
- }
- }
-
- if (mPayload) {
- js::GetUint8ArrayLengthAndData(mPayload, &payloadLen, &isShared, &dummy);
- if (isShared) {
- return false; // Must opt in to shared memory
- }
- }
-
- return JS_WriteUint32Pair(aWriter, static_cast<uint32_t>(mTnf), typeLen) &&
- JS_WriteUint32Pair(aWriter, idLen, payloadLen) &&
- WriteUint8Array(aCx, aWriter, mType, typeLen) &&
- WriteUint8Array(aCx, aWriter, mId, idLen) &&
- WriteUint8Array(aCx, aWriter, mPayload, payloadLen);
-}
-
-bool
-MozNDEFRecord::ReadStructuredClone(JSContext* aCx, JSStructuredCloneReader* aReader)
-{
- uint32_t tnf, typeLen, idLen, payloadLen;
-
- if (!JS_ReadUint32Pair(aReader, &tnf, &typeLen) ||
- !JS_ReadUint32Pair(aReader, &idLen, &payloadLen)) {
- return false;
- }
-
- mTnf = static_cast<TNF>(tnf);
-
- if (typeLen) {
- JS::Rooted<JS::Value> value(aCx);
- if (!JS_ReadTypedArray(aReader, &value)) {
- return false;
- }
- MOZ_ASSERT(value.isObject());
- InitType(aCx, value.toObject(), typeLen);
- }
-
- if (idLen) {
- JS::Rooted<JS::Value> value(aCx);
- if (!JS_ReadTypedArray(aReader, &value)) {
- return false;
- }
- MOZ_ASSERT(value.isObject());
- InitId(aCx, value.toObject(), idLen);
- }
-
- if (payloadLen) {
- JS::Rooted<JS::Value> value(aCx);
- if (!JS_ReadTypedArray(aReader, &value)) {
- return false;
- }
- MOZ_ASSERT(value.isObject());
- InitPayload(aCx, value.toObject(), payloadLen);
- }
-
- return true;
-}
-
-void
-MozNDEFRecord::InitType(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aType)
-{
- if (!aType.WasPassed() || aType.Value().IsNull()) {
- return;
- }
-
- const Uint8Array& type = aType.Value().Value();
- type.ComputeLengthAndData();
- mType = Uint8Array::Create(aCx, this, type.Length(), type.Data());
- IncSize(type.Length());
-}
-
-void
-MozNDEFRecord::InitType(JSContext* aCx, RTD rtd)
-{
- EnumEntry rtdType = RTDValues::strings[static_cast<uint32_t>(rtd)];
- mType = Uint8Array::Create(aCx, rtdType.length,
- reinterpret_cast<const uint8_t*>(rtdType.value));
- IncSize(rtdType.length);
-}
-
-void
-MozNDEFRecord::InitType(JSContext* aCx, JSObject& aType, uint32_t aLen)
-{
- mType = &aType;
- IncSize(aLen);
-}
-
-void
-MozNDEFRecord::InitId(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aId)
-{
- if (!aId.WasPassed() || aId.Value().IsNull()) {
- return;
- }
-
- const Uint8Array& id = aId.Value().Value();
- id.ComputeLengthAndData();
- mId = Uint8Array::Create(aCx, this, id.Length(), id.Data());
- IncSize(1 /* id_length */ + id.Length());
-}
-
-void
-MozNDEFRecord::InitId(JSContext* aCx, JSObject& aId, uint32_t aLen)
-{
- mId = &aId;
- IncSize(1 /* id_length */ + aLen);
-}
-
-void
-MozNDEFRecord::InitPayload(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aPayload)
-{
- if (!aPayload.WasPassed() || aPayload.Value().IsNull()) {
- return;
- }
-
- const Uint8Array& payload = aPayload.Value().Value();
- payload.ComputeLengthAndData();
- mPayload = Uint8Array::Create(aCx, this, payload.Length(), payload.Data());
- IncSizeForPayload(payload.Length());
-}
-
-void
-MozNDEFRecord::InitPayload(JSContext* aCx, const nsAString& aUri)
-{
- using namespace mozilla::dom::WellKnownURIPrefixValues;
-
- nsCString uri = NS_ConvertUTF16toUTF8(aUri);
- uint8_t id = GetURIIdentifier(uri);
- uri = Substring(uri, strings[id].length);
- mPayload = Uint8Array::Create(aCx, this, uri.Length() + 1);
-
- JS::AutoCheckCannotGC nogc;
- bool isShared = false;
- uint8_t* data = JS_GetUint8ArrayData(mPayload, &isShared, nogc);
- MOZ_ASSERT(!isShared); // Created as unshared above
- data[0] = id;
- memcpy(&data[1], reinterpret_cast<const uint8_t*>(uri.Data()), uri.Length());
- IncSizeForPayload(uri.Length() + 1);
-}
-
-void
-MozNDEFRecord::InitPayload(JSContext* aCx, JSObject& aPayload, uint32_t aLen)
-{
- mPayload = &aPayload;
- IncSizeForPayload(aLen);
-}
-
-void
-MozNDEFRecord::IncSize(uint32_t aCount)
-{
- mSize += aCount;
-}
-
-void
-MozNDEFRecord::IncSizeForPayload(uint32_t aLen)
-{
- if (aLen > 0xff) {
- IncSize(3);
- }
-
- IncSize(aLen);
-}
-
-bool
-MozNDEFRecord::WriteUint8Array(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, uint32_t aLen) const
-{
- if (!aLen) {
- return true;
- }
-
- JS::Rooted<JSObject*> obj(aCx, aObj);
- JSAutoCompartment ac(aCx, obj);
- JS::Rooted<JS::Value> value(aCx, JS::ObjectValue(*obj));
- return JS_WriteTypedArray(aWriter, value);
-}
-
-/* static */ uint32_t
-MozNDEFRecord::GetURIIdentifier(const nsCString& aUri)
-{
- using namespace mozilla::dom::WellKnownURIPrefixValues;
-
- // strings[0] is "", so we start from 1.
- for (uint32_t i = 1; i < static_cast<uint32_t>(WellKnownURIPrefix::EndGuard_); i++) {
- if (StringBeginsWith(aUri, nsDependentCString(strings[i].value))) {
- return i;
- }
- }
-
- return 0;
-}
-
-MozNDEFRecord::~MozNDEFRecord()
-{
- DropData();
-}
-
-JSObject*
-MozNDEFRecord::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return MozNDEFRecordBinding::Wrap(aCx, this, aGivenProto);
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/nfc/MozNDEFRecord.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-/* Copyright © 2013 Deutsche Telekom, Inc. */
-
-#ifndef mozilla_dom_MozNDEFRecord_h__
-#define mozilla_dom_MozNDEFRecord_h__
-
-#include "mozilla/Attributes.h"
-#include "mozilla/ErrorResult.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsWrapperCache.h"
-#include "jsapi.h"
-
-#include "mozilla/dom/MozNDEFRecordBinding.h"
-#include "mozilla/dom/TypedArray.h"
-#include "jsfriendapi.h"
-#include "js/GCAPI.h"
-#include "nsISupports.h"
-
-struct JSContext;
-struct JSStructuredCloneWriter;
-
-namespace mozilla {
-namespace dom {
-
-class MozNDEFRecordOptions;
-
-class MozNDEFRecord final : public nsISupports,
- public nsWrapperCache
-{
-public:
- NS_DECL_CYCLE_COLLECTING_ISUPPORTS
- NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MozNDEFRecord)
-
-public:
- MozNDEFRecord(nsISupports* aParent, TNF aTnf = TNF::Empty);
-
- nsISupports* GetParentObject() const
- {
- return mParent;
- }
-
- virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
- static already_AddRefed<MozNDEFRecord>
- Constructor(const GlobalObject& aGlobal,
- const MozNDEFRecordOptions& aOptions,
- ErrorResult& aRv);
-
- static already_AddRefed<MozNDEFRecord>
- Constructor(const GlobalObject& aGlobal,
- const nsAString& aURI,
- ErrorResult& aRv);
-
- TNF Tnf() const
- {
- return mTnf;
- }
-
- void GetType(JSContext* /* unused */, JS::MutableHandle<JSObject*> aRetVal) const
- {
- aRetVal.set(mType);
- }
-
- void GetId(JSContext* /* unused */, JS::MutableHandle<JSObject*> aRetVal) const
- {
- aRetVal.set(mId);
- }
-
- void GetPayload(JSContext* /* unused */, JS::MutableHandle<JSObject*> aRetVal) const
- {
- aRetVal.set(mPayload);
- }
-
- uint32_t Size() const
- {
- return mSize;
- }
-
- void GetAsURI(nsAString& aRetVal);
-
- // Structured clone methods use these to clone MozNDEFRecord.
- bool WriteStructuredClone(JSContext* aCx, JSStructuredCloneWriter* aWriter) const;
- bool ReadStructuredClone(JSContext* aCx, JSStructuredCloneReader* aReader);
-
-protected:
- ~MozNDEFRecord();
-
-private:
- MozNDEFRecord() = delete;
- RefPtr<nsISupports> mParent;
- void HoldData();
- void DropData();
- void InitType(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aType);
- void InitType(JSContext* aCx, const RTD rtd);
- void InitType(JSContext* aCx, JSObject& aType, uint32_t aLen);
- void InitId(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aId);
- void InitId(JSContext* aCx, JSObject& aId, uint32_t aLen);
- void InitPayload(JSContext* aCx, const Optional<Nullable<Uint8Array>>& aPayload);
- void InitPayload(JSContext* aCx, const nsAString& aUri);
- void InitPayload(JSContext* aCx, JSObject& aPayload, uint32_t aLen);
- void IncSize(uint32_t aCount);
- void IncSizeForPayload(uint32_t aLen);
- bool WriteUint8Array(JSContext* aCx, JSStructuredCloneWriter* aWriter, JSObject* aObj, uint32_t aLen) const;
-
- static bool
- ValidateTNF(const MozNDEFRecordOptions& aOptions, ErrorResult& aRv);
- static uint32_t GetURIIdentifier(const nsCString& aUri);
-
- TNF mTnf;
- JS::Heap<JSObject*> mType;
- JS::Heap<JSObject*> mId;
- JS::Heap<JSObject*> mPayload;
- uint32_t mSize;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_MozNDEFRecord_h__
deleted file mode 100644
--- a/dom/nfc/MozNfcATech.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "MozNfcATech.h"
-#include "TagUtils.h"
-#include "mozilla/dom/Promise.h"
-
-using namespace mozilla::dom::nfc;
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(MozNfcATech)
-
-NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(MozNfcATech)
- NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_TRACE_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MozNfcATech)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTag)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MozNfcATech)
- NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
- NS_IMPL_CYCLE_COLLECTION_UNLINK(mTag)
- NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MozNfcATech)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MozNfcATech)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MozNfcATech)
- NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
- NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-const NFCTechType MozNfcATech::sTechnology = NFCTechType::NFC_A;
-
-/* static */
-already_AddRefed<MozNfcATech>
-MozNfcATech::Constructor(const GlobalObject& aGlobal,
- MozNFCTag& aNFCTag,
- ErrorResult& aRv)
-{
- ErrorResult rv;
- nsCOMPtr<nsPIDOMWindowInner> win = do_QueryInterface(aGlobal.GetAsSupports());
- if (!win) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- if (!TagUtils::IsTechSupported(aNFCTag, sTechnology)) {
- aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
- return nullptr;
- }
-
- RefPtr<MozNfcATech> nfcA = new MozNfcATech(win, aNFCTag);
- return nfcA.forget();
-}
-
-MozNfcATech::MozNfcATech(nsPIDOMWindowInner* aWindow, MozNFCTag& aNFCTag)
- : mWindow(aWindow)
- , mTag(&aNFCTag)
-{
-}
-
-MozNfcATech::~MozNfcATech()
-{
-}
-
-already_AddRefed<Promise>
-MozNfcATech::Transceive(const Uint8Array& aCommand, ErrorResult& aRv)
-{
- return TagUtils::Transceive(mTag, sTechnology, aCommand, aRv);
-}
-
-JSObject*
-MozNfcATech::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return MozNfcATechBinding::Wrap(aCx, this, aGivenProto);
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/nfc/MozNfcATech.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef mozilla_dom_nfc_MozNfcATech_h__
-#define mozilla_dom_nfc_MozNfcATech_h__
-
-#include "mozilla/dom/MozNFCTagBinding.h"
-#include "mozilla/dom/MozNfcATechBinding.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsWrapperCache.h"
-#include "nsISupportsImpl.h"
-#include "nsPIDOMWindow.h"
-
-namespace mozilla {
-namespace dom {
-
-class Promise;
-
-class MozNfcATech : public nsISupports,
- public nsWrapperCache
-{
-public:
- NS_DECL_CYCLE_COLLECTING_ISUPPORTS
- NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MozNfcATech)
-
- already_AddRefed<Promise> Transceive(const Uint8Array& aCommand,
- ErrorResult& aRv);
-
- nsPIDOMWindowInner* GetParentObject() const { return mWindow; }
-
- virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
- static already_AddRefed<MozNfcATech>
- Constructor(const GlobalObject& aGlobal, MozNFCTag& aNFCTag,
- ErrorResult& aRv);
-
-private:
- MozNfcATech(nsPIDOMWindowInner* aWindow, MozNFCTag& aNFCTag);
- virtual ~MozNfcATech();
-
- RefPtr<nsPIDOMWindowInner> mWindow;
- RefPtr<MozNFCTag> mTag;
-
- static const NFCTechType sTechnology;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_nfc_MozNfcATech_h__
deleted file mode 100644
--- a/dom/nfc/NfcContentHelper.js
+++ /dev/null
@@ -1,417 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2013, Deutsche Telekom, Inc. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "NFC", function () {
- let obj = {};
- Cu.import("resource://gre/modules/nfc_consts.js", obj);
- return obj;
-});
-
-Cu.import("resource://gre/modules/systemlibs.js");
-const NFC_ENABLED = libcutils.property_get("ro.moz.nfc.enabled", "false") === "true";
-
-// set to true to in nfc_consts.js to see debug messages
-var DEBUG = NFC.DEBUG_CONTENT_HELPER;
-
-var debug;
-function updateDebug() {
- if (DEBUG || NFC.DEBUG_CONTENT_HELPER) {
- debug = function (s) {
- dump("-*- NfcContentHelper: " + s + "\n");
- };
- } else {
- debug = function (s) {};
- }
-};
-updateDebug();
-
-const NFCCONTENTHELPER_CID =
- Components.ID("{4d72c120-da5f-11e1-9b23-0800200c9a66}");
-
-const NFC_IPC_MSG_NAMES = [
- "NFC:ReadNDEFResponse",
- "NFC:WriteNDEFResponse",
- "NFC:MakeReadOnlyResponse",
- "NFC:FormatResponse",
- "NFC:TransceiveResponse",
- "NFC:CheckP2PRegistrationResponse",
- "NFC:DOMEvent",
- "NFC:NotifySendFileStatusResponse",
- "NFC:ChangeRFStateResponse"
-];
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsISyncMessageSender");
-
-function NfcContentHelper() {
- Services.obs.addObserver(this, "xpcom-shutdown", false);
-
- this._requestMap = [];
- this.initDOMRequestHelper(/* window */ null, NFC_IPC_MSG_NAMES);
- this.eventListeners = {};
-}
-
-NfcContentHelper.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINfcContentHelper,
- Ci.nsINfcBrowserAPI,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver]),
- classID: NFCCONTENTHELPER_CID,
- classInfo: XPCOMUtils.generateCI({
- classID: NFCCONTENTHELPER_CID,
- classDescription: "NfcContentHelper",
- interfaces: [Ci.nsINfcContentHelper,
- Ci.nsINfcBrowserAPI]
- }),
-
- _requestMap: null,
- eventListeners: null,
-
- queryRFState: function queryRFState() {
- return cpmm.sendSyncMessage("NFC:QueryInfo")[0].rfState;
- },
-
- setFocusTab: function setFocusTab(tabId, isFocus) {
- cpmm.sendAsyncMessage("NFC:SetFocusTab", {
- tabId: tabId,
- isFocus: isFocus
- });
- },
-
- // NFCTag interface
- readNDEF: function readNDEF(sessionToken, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:ReadNDEF", {
- requestId: requestId,
- sessionToken: sessionToken
- });
- },
-
- writeNDEF: function writeNDEF(records, isP2P, sessionToken, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:WriteNDEF", {
- requestId: requestId,
- sessionToken: sessionToken,
- records: records,
- isP2P: isP2P
- });
- },
-
- makeReadOnly: function makeReadOnly(sessionToken, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:MakeReadOnly", {
- requestId: requestId,
- sessionToken: sessionToken
- });
- },
-
- format: function format(sessionToken, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:Format", {
- requestId: requestId,
- sessionToken: sessionToken
- });
- },
-
- transceive: function transceive(sessionToken, technology, command, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:Transceive", {
- requestId: requestId,
- sessionToken: sessionToken,
- technology: technology,
- command: command
- });
- },
-
- sendFile: function sendFile(data, sessionToken, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:SendFile", {
- requestId: requestId,
- sessionToken: sessionToken,
- blob: data.blob
- });
- },
-
- notifySendFileStatus: function notifySendFileStatus(status, requestId) {
- cpmm.sendAsyncMessage("NFC:NotifySendFileStatus", {
- status: status,
- requestId: requestId
- });
- },
-
- addEventListener: function addEventListener(listener, tabId) {
- let _window = listener.window;
-
- this.eventListeners[tabId] = listener;
- cpmm.sendAsyncMessage("NFC:AddEventListener", { tabId: tabId });
- },
-
- removeEventListener: function removeEventListener(tabId) {
- delete this.eventListeners[tabId];
-
- cpmm.sendAsyncMessage("NFC:RemoveEventListener", { tabId: tabId });
- },
-
- registerTargetForPeerReady: function registerTargetForPeerReady(appId) {
- cpmm.sendAsyncMessage("NFC:RegisterPeerReadyTarget", { appId: appId });
- },
-
- unregisterTargetForPeerReady: function unregisterTargetForPeerReady(appId) {
- cpmm.sendAsyncMessage("NFC:UnregisterPeerReadyTarget", { appId: appId });
- },
-
- checkP2PRegistration: function checkP2PRegistration(appId, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:CheckP2PRegistration", {
- appId: appId,
- requestId: requestId
- });
- },
-
- notifyUserAcceptedP2P: function notifyUserAcceptedP2P(appId) {
- cpmm.sendAsyncMessage("NFC:NotifyUserAcceptedP2P", {
- appId: appId
- });
- },
-
- changeRFState: function changeRFState(rfState, callback) {
- let requestId = callback.getCallbackId();
- this._requestMap[requestId] = callback;
-
- cpmm.sendAsyncMessage("NFC:ChangeRFState",
- {requestId: requestId,
- rfState: rfState});
- },
-
- callDefaultFoundHandler: function callDefaultFoundHandler(sessionToken,
- isP2P,
- records) {
- cpmm.sendAsyncMessage("NFC:CallDefaultFoundHandler",
- {sessionToken: sessionToken,
- isP2P: isP2P,
- records: records});
- },
-
- callDefaultLostHandler: function callDefaultLostHandler(sessionToken, isP2P) {
- cpmm.sendAsyncMessage("NFC:CallDefaultLostHandler",
- {sessionToken: sessionToken,
- isP2P: isP2P});
- },
-
- // nsIObserver
- observe: function observe(subject, topic, data) {
- if (topic == "xpcom-shutdown") {
- this.destroyDOMRequestHelper();
- Services.obs.removeObserver(this, "xpcom-shutdown");
- cpmm = null;
- }
- },
-
- // nsIMessageListener
- receiveMessage: function receiveMessage(message) {
- DEBUG && debug("Message received: " + JSON.stringify(message));
- let result = message.data;
-
- switch (message.name) {
- case "NFC:ReadNDEFResponse":
- this.handleReadNDEFResponse(result);
- break;
- case "NFC:CheckP2PRegistrationResponse":
- this.handleCheckP2PRegistrationResponse(result);
- break;
- case "NFC:TransceiveResponse":
- this.handleTransceiveResponse(result);
- break;
- case "NFC:WriteNDEFResponse": // Fall through.
- case "NFC:MakeReadOnlyResponse":
- case "NFC:FormatResponse":
- case "NFC:NotifySendFileStatusResponse":
- case "NFC:ChangeRFStateResponse":
- this.handleGeneralResponse(result);
- break;
- case "NFC:DOMEvent":
- this.handleDOMEvent(result);
- break;
- }
- },
-
- handleGeneralResponse: function handleGeneralResponse(result) {
- let requestId = result.requestId;
- let callback = this._requestMap[requestId];
- if (!callback) {
- debug("not firing message " + result.type + " for id: " + requestId);
- return;
- }
- delete this._requestMap[requestId];
-
- if (result.errorMsg) {
- callback.notifyError(result.errorMsg);
- } else {
- callback.notifySuccess();
- }
- },
-
- handleReadNDEFResponse: function handleReadNDEFResponse(result) {
- let requestId = result.requestId;
- let callback = this._requestMap[requestId];
- if (!callback) {
- debug("not firing message handleReadNDEFResponse for id: " + requestId);
- return;
- }
- delete this._requestMap[requestId];
-
- if (result.errorMsg) {
- callback.notifyError(result.errorMsg);
- return;
- }
-
- 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;
- }
- delete this._requestMap[requestId];
-
- // Privilaged status API. Always fire success to avoid using exposed props.
- // The receiver must check the boolean mapped status code to handle.
- callback.notifySuccessWithBoolean(!result.errorMsg);
- },
-
- handleTransceiveResponse: function handleTransceiveResponse(result) {
- let requestId = result.requestId;
- let callback = this._requestMap[requestId];
- if (!callback) {
- debug("not firing message handleTransceiveResponse for id: " + requestId);
- return;
- }
- delete this._requestMap[requestId];
-
- if (result.errorMsg) {
- callback.notifyError(result.errorMsg);
- return;
- }
-
- callback.notifySuccessWithByteArray(result.response);
- },
-
- handleDOMEvent: function handleDOMEvent(result) {
- let listener = this.eventListeners[result.tabId];
- if (!listener) {
- debug("no listener for tabId " + result.tabId);
- return;
- }
-
- switch (result.event) {
- case NFC.PEER_EVENT_READY:
- listener.notifyPeerFound(result.sessionToken, /* isPeerReady */ true);
- break;
- case NFC.PEER_EVENT_FOUND:
- listener.notifyPeerFound(result.sessionToken);
- break;
- case NFC.PEER_EVENT_LOST:
- listener.notifyPeerLost(result.sessionToken);
- break;
- case NFC.TAG_EVENT_FOUND:
- let ndefInfo = null;
- if (result.tagType !== undefined &&
- result.maxNDEFSize !== undefined &&
- result.isReadOnly !== undefined &&
- result.isFormatable !== undefined) {
- ndefInfo = new TagNDEFInfo(result.tagType,
- result.maxNDEFSize,
- result.isReadOnly,
- result.isFormatable);
- }
-
- let tagInfo = new TagInfo(result.techList, result.tagId);
- listener.notifyTagFound(result.sessionToken,
- tagInfo,
- ndefInfo,
- result.records);
- break;
- case NFC.TAG_EVENT_LOST:
- listener.notifyTagLost(result.sessionToken);
- break;
- case NFC.RF_EVENT_STATE_CHANGED:
- listener.notifyRFStateChanged(result.rfState);
- break;
- case NFC.FOCUS_CHANGED:
- listener.notifyFocusChanged(result.focus);
- break;
- }
- }
-};
-
-function TagNDEFInfo(tagType, maxNDEFSize, isReadOnly, isFormatable) {
- this.tagType = tagType;
- this.maxNDEFSize = maxNDEFSize;
- this.isReadOnly = isReadOnly;
- this.isFormatable = isFormatable;
-}
-TagNDEFInfo.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITagNDEFInfo]),
-
- tagType: null,
- maxNDEFSize: 0,
- isReadOnly: false,
- isFormatable: false
-};
-
-function TagInfo(techList, tagId) {
- this.techList = techList;
- this.tagId = tagId;
-}
-TagInfo.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITagInfo]),
-
- techList: null,
- tagId: null,
-};
-
-if (NFC_ENABLED) {
- this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NfcContentHelper]);
-}
deleted file mode 100644
--- a/dom/nfc/NfcContentHelper.manifest
+++ /dev/null
@@ -1,7 +0,0 @@
-# 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/.
-# NfcContentHelper.js
-component {4d72c120-da5f-11e1-9b23-0800200c9a66} NfcContentHelper.js
-contract @mozilla.org/nfc/content-helper;1 {4d72c120-da5f-11e1-9b23-0800200c9a66}
-category profile-after-change NfcContentHelper @mozilla.org/nfc/content-helper;1
deleted file mode 100644
--- a/dom/nfc/TagUtils.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "TagUtils.h"
-#include "mozilla/dom/Promise.h"
-
-namespace mozilla {
-namespace dom {
-namespace nfc {
-
-bool
-TagUtils::IsTechSupported(const MozNFCTag& aTag,
- const NFCTechType& aTechnology)
-{
- ErrorResult rv;
-
- Nullable<nsTArray<NFCTechType>> techList;
- aTag.GetTechList(techList, rv);
- ENSURE_SUCCESS(rv, false);
- return !techList.IsNull() && techList.Value().Contains(aTechnology);
-}
-
-already_AddRefed<Promise>
-TagUtils::Transceive(MozNFCTag* aTag,
- const NFCTechType& aTechnology,
- const Uint8Array& aCommand,
- ErrorResult& aRv)
-{
- ErrorResult rv;
-
- aCommand.ComputeLengthAndData();
- RefPtr<Promise> promise = aTag->Transceive(aTechnology, aCommand, rv);
- if (rv.Failed()) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- return promise.forget();
-}
-
-} // namespace nfc
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/nfc/TagUtils.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef mozilla_dom_nfc_TagUtils_h__
-#define mozilla_dom_nfc_TagUtils_h__
-
-#include "mozilla/dom/MozNFCTagBinding.h"
-
-namespace mozilla {
-namespace dom {
-namespace nfc {
-
-/**
- * Class of static helper functions for nfc tag.
- */
-class TagUtils
-{
-public:
- /**
- * Check if specified technogy is supported in this tag.
- */
- static bool
- IsTechSupported(const MozNFCTag& aNFCTag,
- const NFCTechType& aTechnology);
-
- /**
- * Send raw command to tag and receive the response.
- */
- static already_AddRefed<Promise>
- Transceive(MozNFCTag* aTag,
- const NFCTechType& aTechnology,
- const Uint8Array& aCommand,
- ErrorResult& aRv);
-};
-
-} // namespace nfc
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_nfc_TagUtils_h__
deleted file mode 100644
--- a/dom/nfc/gonk/Nfc.js
+++ /dev/null
@@ -1,851 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2013, Deutsche Telekom, Inc. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyGetter(this, "NFC", function () {
- let obj = {};
- Cu.import("resource://gre/modules/nfc_consts.js", obj);
- return obj;
-});
-
-Cu.import("resource://gre/modules/systemlibs.js");
-const NFC_ENABLED = libcutils.property_get("ro.moz.nfc.enabled", "false") === "true";
-
-// set to true in nfc_consts.js to see debug messages
-var DEBUG = NFC.DEBUG_NFC;
-
-var debug;
-function updateDebug() {
- if (DEBUG || NFC.DEBUG_NFC) {
- debug = function (s) {
- dump("-*- Nfc: " + s + "\n");
- };
- } else {
- debug = function (s) {};
- }
-};
-updateDebug();
-
-const NFC_CONTRACTID = "@mozilla.org/nfc;1";
-const NFC_CID =
- Components.ID("{2ff24790-5e74-11e1-b86c-0800200c9a66}");
-
-const NFC_IPC_MSG_ENTRIES = [
- { permission: null,
- messages: ["NFC:AddEventListener",
- "NFC:RemoveEventListener",
- "NFC:QueryInfo",
- "NFC:CallDefaultFoundHandler",
- "NFC:CallDefaultLostHandler"] },
-
- { permission: "nfc",
- messages: ["NFC:ReadNDEF",
- "NFC:WriteNDEF",
- "NFC:MakeReadOnly",
- "NFC:Format",
- "NFC:Transceive"] },
-
- { permission: "nfc-share",
- messages: ["NFC:SendFile",
- "NFC:RegisterPeerReadyTarget",
- "NFC:UnregisterPeerReadyTarget"] },
-
- { permission: "nfc-manager",
- messages: ["NFC:CheckP2PRegistration",
- "NFC:NotifyUserAcceptedP2P",
- "NFC:NotifySendFileStatus",
- "NFC:ChangeRFState",
- "NFC:SetFocusTab"] }
-];
-
-// Should be consistent with NfcRequestType defined in NfcOptions.webidl.
-const NfcRequestType = {
- CHANGE_RF_STATE: "changeRFState",
- READ_NDEF: "readNDEF",
- WRITE_NDEF: "writeNDEF",
- MAKE_READ_ONLY: "makeReadOnly",
- FORMAT: "format",
- TRANSCEIVE: "transceive"
-};
-
-const CommandMsgTable = {};
-CommandMsgTable["NFC:ChangeRFState"] = NfcRequestType.CHANGE_RF_STATE;
-CommandMsgTable["NFC:ReadNDEF"] = NfcRequestType.READ_NDEF;
-CommandMsgTable["NFC:WriteNDEF"] = NfcRequestType.WRITE_NDEF;
-CommandMsgTable["NFC:MakeReadOnly"] = NfcRequestType.MAKE_READ_ONLY;
-CommandMsgTable["NFC:Format"] = NfcRequestType.FORMAT;
-CommandMsgTable["NFC:Transceive"] = NfcRequestType.TRANSCEIVE;
-
-// Should be consistent with NfcResponseType defined in NfcOptions.webidl.
-const NfcResponseType = {
- CHANGE_RF_STATE_RSP: "changeRFStateRsp",
- READ_NDEF_RSP: "readNDEFRsp",
- WRITE_NDEF_RSP: "writeNDEFRsp",
- MAKE_READ_ONLY_RSP: "makeReadOnlyRsp",
- FORMAT_RSP: "formatRsp",
- TRANSCEIVE_RSP: "transceiveRsp",
-};
-
-const EventMsgTable = {};
-EventMsgTable[NfcResponseType.CHANGE_RF_STATE_RSP] = "NFC:ChangeRFStateResponse";
-EventMsgTable[NfcResponseType.READ_NDEF_RSP] = "NFC:ReadNDEFResponse";
-EventMsgTable[NfcResponseType.WRITE_NDEF_RSP] = "NFC:WriteNDEFResponse";
-EventMsgTable[NfcResponseType.MAKE_READ_ONLY_RSP] = "NFC:MakeReadOnlyResponse";
-EventMsgTable[NfcResponseType.FORMAT_RSP] = "NFC:FormatResponse";
-EventMsgTable[NfcResponseType.TRANSCEIVE_RSP] = "NFC:TransceiveResponse";
-
-// Should be consistent with NfcNotificationType defined in NfcOptions.webidl.
-const NfcNotificationType = {
- INITIALIZED: "initialized",
- TECH_DISCOVERED: "techDiscovered",
- TECH_LOST: "techLost",
- HCI_EVENT_TRANSACTION: "hciEventTransaction",
- NDEF_RECEIVED: "ndefReceived"
-};
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
- "@mozilla.org/parentprocessmessagemanager;1",
- "nsIMessageBroadcaster");
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
- "@mozilla.org/system-message-internal;1",
- "nsISystemMessagesInternal");
-XPCOMUtils.defineLazyServiceGetter(this, "UUIDGenerator",
- "@mozilla.org/uuid-generator;1",
- "nsIUUIDGenerator");
-XPCOMUtils.defineLazyGetter(this, "gMessageManager", function () {
- return {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIMessageListener,
- Ci.nsIObserver]),
-
- nfc: null,
-
- // Manage registered Peer Targets
- peerTargets: {},
-
- eventListeners: {},
-
- focusId: NFC.SYSTEM_APP_ID,
-
- init: function init(nfc) {
- this.nfc = nfc;
- Services.obs.addObserver(this, NFC.TOPIC_XPCOM_SHUTDOWN, false);
- this._registerMessageListeners();
- },
-
- listenDebugEvent: function listenDebugEvent() {
- let lock = gSettingsService.createLock();
- lock.get(NFC.SETTING_NFC_DEBUG, this.nfc);
- Services.obs.addObserver(this, NFC.TOPIC_MOZSETTINGS_CHANGED, false);
- },
-
- _shutdown: function _shutdown() {
- this.nfc.shutdown();
- this.nfc = null;
-
- Services.obs.removeObserver(this, NFC.TOPIC_MOZSETTINGS_CHANGED);
- Services.obs.removeObserver(this, NFC.TOPIC_XPCOM_SHUTDOWN);
- this._unregisterMessageListeners();
- },
-
- _registerMessageListeners: function _registerMessageListeners() {
- ppmm.addMessageListener("child-process-shutdown", this);
-
- for (let entry of NFC_IPC_MSG_ENTRIES) {
- for (let message of entry.messages) {
- ppmm.addMessageListener(message, this);
- }
- }
- },
-
- _unregisterMessageListeners: function _unregisterMessageListeners() {
- ppmm.removeMessageListener("child-process-shutdown", this);
-
- for (let entry of NFC_IPC_MSG_ENTRIES) {
- for (let message of entry.messages) {
- ppmm.removeMessageListener(message, this);
- }
- }
-
- ppmm = null;
- },
-
- registerPeerReadyTarget: function registerPeerReadyTarget(target, appId) {
- if (!this.peerTargets[appId]) {
- this.peerTargets[appId] = target;
- }
- },
-
- unregisterPeerReadyTarget: function unregisterPeerReadyTarget(appId) {
- if (this.peerTargets[appId]) {
- delete this.peerTargets[appId];
- }
- },
-
- removePeerTarget: function removePeerTarget(target) {
- Object.keys(this.peerTargets).forEach((appId) => {
- if (this.peerTargets[appId] === target) {
- delete this.peerTargets[appId];
- }
- });
- },
-
- notifyFocusTab: function notifyFocusTab(options) {
- let tabId = this.getFocusTabId();
- options.tabId = tabId;
-
- this.notifyDOMEvent(this.eventListeners[tabId], options);
- },
-
- notifyDOMEvent: function notifyDOMEvent(target, options) {
- if (!target) {
- dump("invalid target");
- return;
- }
-
- target.sendAsyncMessage("NFC:DOMEvent", options);
- },
-
- getFocusTabId: function getFocusTabId() {
- return this.eventListeners[this.focusId] ? this.focusId
- : NFC.SYSTEM_APP_ID;
- },
-
- setFocusTab: function setFocusTab(id, isFocus) {
- // if calling setNFCFocus(true) on the browser-element which is already
- // focused, or calling setNFCFocus(false) on the browser-element which has
- // lost focus already, ignore.
- if (isFocus == (id == this.focusId)) {
- return;
- }
-
- if (this.focusId != NFC.SYSTEM_APP_ID) {
- this.onFocusChanged(this.focusId, false);
- }
-
- if (isFocus) {
- // Now we only support one focus app.
- this.focusId = id;
- this.onFocusChanged(this.focusId, true);
- } else if (this.focusId == id){
- // Set focusId to SystemApp means currently there is no foreground app.
- this.focusId = NFC.SYSTEM_APP_ID;
- }
- },
-
- addEventListener: function addEventListener(target, id) {
- if (this.eventListeners[id] !== undefined) {
- return;
- }
-
- this.eventListeners[id] = target;
- },
-
- removeEventListener: function removeEventListener(target) {
- for (let id in this.eventListeners) {
- if (target == this.eventListeners[id]) {
- this.removeEventListenerById(id);
- break;
- }
- }
- },
-
- removeEventListenerById: function removeEventListenerById(id) {
- delete this.eventListeners[id];
- },
-
- checkP2PRegistration: function checkP2PRegistration(message) {
- let target = this.peerTargets[message.data.appId];
- let sessionToken = SessionHelper.getCurrentP2PToken();
- let isValid = (sessionToken != null) && (target != null);
- let respMsg = { requestId: message.data.requestId };
- if (!isValid) {
- respMsg.errorMsg = this.nfc.getErrorMessage(NFC.NFC_GECKO_ERROR_P2P_REG_INVALID);
- }
- // Notify the content process immediately of the status
- message.target.sendAsyncMessage(message.name + "Response", respMsg);
- },
-
- notifyUserAcceptedP2P: function notifyUserAcceptedP2P(appId) {
- let target = this.peerTargets[appId];
- let sessionToken = SessionHelper.getCurrentP2PToken();
- if (!sessionToken || !target) {
- debug("Peer already lost or " + appId + " is not a registered PeerReadytarget");
- return;
- }
-
- this.notifyDOMEvent(target, {tabId: this.getFocusTabId(),
- event: NFC.PEER_EVENT_READY,
- sessionToken: sessionToken});
- },
-
- notifySendFileStatus: function notifySendFileStatus(message) {
- if (message.data.status) {
- message.data.errorMsg =
- this.nfc.getErrorMessage(NFC.NFC_GECKO_ERROR_SEND_FILE_FAILED);
- }
- this.nfc.sendFileStatusResponse(message.data);
- },
-
- callDefaultFoundHandler: function callDefaultFoundHandler(message) {
- let sysMsg = new NfcTechDiscoveredSysMsg(message.sessionToken,
- message.isP2P,
- message.records || null);
- gSystemMessenger.broadcastMessage("nfc-manager-tech-discovered", sysMsg);
- },
-
- callDefaultLostHandler: function callDefaultLostHandler(message) {
- // message.isP2P is not used.
- gSystemMessenger.broadcastMessage("nfc-manager-tech-lost", message.sessionToken);
- },
-
- onTagFound: function onTagFound(message) {
- message.event = NFC.TAG_EVENT_FOUND;
- this.notifyFocusTab(message);
- delete message.event;
- },
-
- onTagLost: function onTagLost(sessionToken) {
- this.notifyFocusTab({ event: NFC.TAG_EVENT_LOST,
- sessionToken: sessionToken });
- },
-
- onPeerEvent: function onPeerEvent(eventType, sessionToken) {
- this.notifyFocusTab({ event: eventType,
- sessionToken: sessionToken });
- },
-
- onRFStateChanged: function onRFStateChanged(rfState) {
- for (let id in this.eventListeners) {
- this.notifyDOMEvent(this.eventListeners[id],
- { tabId: id,
- event: NFC.RF_EVENT_STATE_CHANGED,
- rfState: rfState });
- }
- },
-
- onFocusChanged: function onFocusChanged(focusId, focus) {
- let target = this.eventListeners[focusId];
- if (!target) {
- return;
- }
-
- this.notifyDOMEvent(target, { tabId: this.focusId,
- event: NFC.FOCUS_CHANGED,
- focus: focus });
- },
-
- /**
- * nsIMessageListener interface methods.
- */
-
- receiveMessage: function receiveMessage(message) {
- DEBUG && debug("Received message from content process: " + JSON.stringify(message));
-
- if (message.name == "child-process-shutdown") {
- this.removePeerTarget(message.target);
- this.nfc.removeTarget(message.target);
- this.removeEventListener(message.target);
- return null;
- }
-
- for (let entry of NFC_IPC_MSG_ENTRIES) {
- if (entry.messages.indexOf(message.name) != -1) {
- if (entry.permission &&
- !message.target.assertPermission(entry.permission)) {
- debug("Nfc message " + message.name + "doesn't have " +
- entry.permission + " permission.");
- return null;
- }
- break;
- }
- }
-
- switch (message.name) {
- case "NFC:SetFocusTab":
- this.setFocusTab(message.data.tabId, message.data.isFocus);
- return null;
- case "NFC:AddEventListener":
- this.addEventListener(message.target, message.data.tabId);
- return null;
- case "NFC:RemoveEventListener":
- this.removeEventListenerById(message.data.tabId);
- return null;
- case "NFC:RegisterPeerReadyTarget":
- this.registerPeerReadyTarget(message.target, message.data.appId);
- return null;
- case "NFC:UnregisterPeerReadyTarget":
- this.unregisterPeerReadyTarget(message.data.appId);
- return null;
- case "NFC:CheckP2PRegistration":
- this.checkP2PRegistration(message);
- return null;
- case "NFC:NotifyUserAcceptedP2P":
- this.notifyUserAcceptedP2P(message.data.appId);
- return null;
- case "NFC:NotifySendFileStatus":
- // Upon receiving the status of sendFile operation, send the response
- // to appropriate content process.
- this.notifySendFileStatus(message);
- return null;
- case "NFC:CallDefaultFoundHandler":
- this.callDefaultFoundHandler(message.data);
- return null;
- case "NFC:CallDefaultLostHandler":
- this.callDefaultLostHandler(message.data);
- return null;
- case "NFC:SendFile":
- // Chrome process is the arbitrator / mediator between
- // system app (content process) that issued nfc 'sendFile' operation
- // and system app that handles the system message :
- // 'nfc-manager-send-file'. System app subsequently handover's
- // the data to alternate carrier's (BT / WiFi) 'sendFile' interface.
-
- // Notify system app to initiate BT send file operation
- let sysMsg = new NfcSendFileSysMsg(message.data.requestId,
- message.data.sessionToken,
- message.data.blob);
- gSystemMessenger.broadcastMessage("nfc-manager-send-file",
- sysMsg);
- return null;
- default:
- return this.nfc.receiveMessage(message);
- }
- },
-
- /**
- * nsIObserver interface methods.
- */
-
- observe: function observe(subject, topic, data) {
- switch (topic) {
- case NFC.TOPIC_MOZSETTINGS_CHANGED:
- if ("wrappedJSObject" in subject) {
- subject = subject.wrappedJSObject;
- }
- if (subject) {
- this.nfc.handle(subject.key, subject.value);
- }
- break;
- case NFC.TOPIC_XPCOM_SHUTDOWN:
- this._shutdown();
- break;
- }
- },
- };
-});
-
-var SessionHelper = {
- tokenMap: {},
-
- registerSession: function registerSession(id, isP2P) {
- if (this.tokenMap[id]) {
- return this.tokenMap[id].token;
- }
-
- this.tokenMap[id] = {
- token: UUIDGenerator.generateUUID().toString(),
- isP2P: isP2P
- };
-
- return this.tokenMap[id].token;
- },
-
- unregisterSession: function unregisterSession(id) {
- if (this.tokenMap[id]) {
- delete this.tokenMap[id];
- }
- },
-
- getToken: function getToken(id) {
- return this.tokenMap[id] ? this.tokenMap[id].token : null;
- },
-
- getCurrentP2PToken: function getCurrentP2PToken() {
- for (let id in this.tokenMap) {
- if (this.tokenMap[id] && this.tokenMap[id].isP2P) {
- return this.tokenMap[id].token;
- }
- }
- return null;
- },
-
- getId: function getId(token) {
- for (let id in this.tokenMap) {
- if (this.tokenMap[id].token == token) {
- return id;
- }
- }
-
- return 0;
- },
-
- isP2PSession: function isP2PSession(id) {
- return (this.tokenMap[id] != null) && this.tokenMap[id].isP2P;
- }
-};
-
-function Nfc(isXPCShell) {
- // TODO: Bug 1239954: xpcshell test timed out with
- // SettingsSevice.createlock().get()
- // gSettingsService.createLock will cause timeout while running xpshell-test,
- // so we try to prevent to run gSettingsService under xpcshell-test here.
- gMessageManager.init(this);
- if (!isXPCShell && !NFC.DEBUG_NFC) {
- gMessageManager.listenDebugEvent();
- }
-
- this.targetsByRequestId = {};
-}
-
-Nfc.prototype = {
-
- classID: NFC_CID,
- classInfo: XPCOMUtils.generateCI({classID: NFC_CID,
- classDescription: "Nfc",
- interfaces: [Ci.nsINfcService]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsINfcGonkEventListener]),
-
- rfState: NFC.NFC_RF_STATE_IDLE,
-
- nfcService: null,
-
- targetsByRequestId: null,
-
- // temporary variables while NFC initialization is pending
- pendingNfcService: null,
- pendingMessageQueue: [],
-
- /**
- * Start NFC service
- */
- startNfcService: function startNfcService() {
- debug("Starting Nfc Service");
-
- let nfcService =
- Cc["@mozilla.org/nfc/service;1"].getService(Ci.nsINfcService);
- if (!nfcService) {
- debug("No nfc service component available!");
- return false;
- }
-
- nfcService.start(this);
- this.pendingNfcService = nfcService;
-
- return true;
- },
-
- /**
- * Shutdown NFC service
- */
- shutdownNfcService : function shutdownNfcService() {
- debug("Shutting down Nfc Service");
-
- this.nfcService.shutdown();
- this.nfcService = null;
- },
-
- /**
- * Send arbitrary message to Nfc service.
- *
- * @param nfcMessageType
- * A text message type.
- * @param message [optional]
- * An optional message object to send.
- */
- sendToNfcService: function sendToNfcService(nfcMessageType, message) {
- message = message || {};
- message.type = nfcMessageType;
- this.nfcService.sendCommand(message);
- },
-
- sendFileStatusResponse: function sendFileStatusResponse(message) {
- let target = this.getTargetByRequestId(message.requestId);
- if (!target) {
- return;
- }
-
- target.sendAsyncMessage("NFC:NotifySendFileStatusResponse", message);
- },
-
- sendNfcResponse: function sendNfcResponse(message) {
- let target = this.getTargetByRequestId(message.requestId);
- if (!target) {
- return;
- }
-
- target.sendAsyncMessage(EventMsgTable[message.type], message);
- },
-
- getTargetByRequestId: function getTargetByRequestId(requestId) {
- let target = this.targetsByRequestId[requestId];
- if (!target) {
- debug("No target for requestId: " + requestId);
- return null;
- }
- delete this.targetsByRequestId[requestId];
-
- return target;
- },
-
- /**
- * Send Error response to content process.
- *
- * @param message
- * An nsIMessageListener's message parameter.
- * @param errorMsg
- * A string with an error message.
- */
- sendNfcErrorResponse: function sendNfcErrorResponse(message, errorMsg) {
- if (!message.target) {
- return;
- }
-
- let nfcMsgType = message.name + "Response";
- message.data.errorMsg = errorMsg;
- message.target.sendAsyncMessage(nfcMsgType, message.data);
- },
-
- getErrorMessage: function getErrorMessage(errorCode) {
- return NFC.NFC_ERROR_MSG[errorCode];
- },
-
- /**
- * Process the incoming message from the NFC Service.
- */
- onEvent: function onEvent(event) {
- let message = Cu.cloneInto(event, this);
- DEBUG && debug("Received message from NFC Service: " + JSON.stringify(message));
-
- message.type = message.rspType || message.ntfType;
- switch (message.type) {
- case NfcNotificationType.INITIALIZED:
- this.nfcService = this.pendingNfcService;
- // Send messages that have been queued up during initialization
- // TODO: Bug 1141007: send error responses if the message
- // indicates an error during initialization.
- while (this.pendingMessageQueue.length) {
- this.receiveMessage(this.pendingMessageQueue.shift());
- }
- this.pendingNfcService = null;
- break;
- case NfcNotificationType.TECH_DISCOVERED:
- // Update the upper layers with a session token (alias)
- message.sessionToken =
- SessionHelper.registerSession(message.sessionId, message.isP2P);
- // Do not expose the actual session to the content
- let sessionId = message.sessionId;
- delete message.sessionId;
-
- if (SessionHelper.isP2PSession(sessionId)) {
- gMessageManager.onPeerEvent(NFC.PEER_EVENT_FOUND, message.sessionToken);
- } else {
- gMessageManager.onTagFound(message);
- }
- break;
- case NfcNotificationType.TECH_LOST:
- // Update the upper layers with a session token (alias)
- message.sessionToken = SessionHelper.getToken(message.sessionId);
- if (SessionHelper.isP2PSession(message.sessionId)) {
- gMessageManager.onPeerEvent(NFC.PEER_EVENT_LOST, message.sessionToken);
- } else {
- gMessageManager.onTagLost(message.sessionToken);
- }
-
- SessionHelper.unregisterSession(message.sessionId);
- break;
- case NfcNotificationType.HCI_EVENT_TRANSACTION:
- this.notifyHCIEventTransaction(message);
- break;
- case NfcNotificationType.NDEF_RECEIVED:
- message.sessionToken = SessionHelper.getToken(message.sessionId);
- delete message.sessionId;
- message.isP2P = true;
- // TODO: Bug 1082493.
- // This event should be sent to the focus app, but before Bug 1082493
- // is landed we forward this to System app.
- gMessageManager.callDefaultFoundHandler(message);
- break;
- case NfcResponseType.CHANGE_RF_STATE_RSP:
- this.sendNfcResponse(message);
-
- if (!message.errorMsg) {
- this.rfState = message.rfState;
- gMessageManager.onRFStateChanged(this.rfState);
- }
- if (this.rfState == NFC.NFC_RF_STATE_IDLE) {
- this.shutdownNfcService();
- }
- break;
- case NfcResponseType.READ_NDEF_RSP: // Fall through.
- case NfcResponseType.WRITE_NDEF_RSP:
- case NfcResponseType.MAKE_READ_ONLY_RSP:
- case NfcResponseType.FORMAT_RSP:
- case NfcResponseType.TRANSCEIVE_RSP:
- this.sendNfcResponse(message);
- break;
- default:
- throw new Error("Don't know about this message type: " + message.type);
- }
- },
-
- // HCI Event Transaction
- notifyHCIEventTransaction: function notifyHCIEventTransaction(message) {
- delete message.type;
- /**
- * FIXME:
- * GSMA 6.0 7.4 UI Application triggering requirements
- * This specifies the need for the following parameters to be derived and
- * sent. One unclear spec is what the URI format "secure:0" refers to, given
- * SEName can be something like "SIM1" or "SIM2".
- *
- * 1) Mime-type - Secure Element application dependent
- * 2) URI, of the format: nfc://secure:0/<SEName>/<AID>
- * - SEName reflects the originating SE. It must be compliant with
- * SIMAlliance Open Mobile APIs
- * - AID reflects the originating UICC applet identifier
- * 3) Data - Data payload of the transaction notification, if any.
- */
- gSystemMessenger.broadcastMessage("nfc-hci-event-transaction", message);
- },
-
- /**
- * Process a message from the gMessageManager.
- */
- receiveMessage: function receiveMessage(message) {
- // Return early if we don't need the NFC Service. We won't start
- // the NFC daemon here.
- switch (message.name) {
- case "NFC:QueryInfo":
- return {rfState: this.rfState};
- default:
- break;
- }
-
- // Start NFC Service if necessary. Messages are held in a
- // queue while initialization is being performed.
- if (!this.nfcService) {
- if ((message.name == "NFC:ChangeRFState") &&
- (message.data.rfState != "idle") &&
- !this.pendingNfcService) {
- this.startNfcService(); // error handled in next branch
- }
- if (this.pendingNfcService) {
- this.pendingMessageQueue.push(message);
- } else {
- this.sendNfcErrorResponse(message, "NotInitialize");
- }
- return;
- }
-
- // NFC Service is running and we have a message for it. This
- // is the case during normal operation.
- if (message.name != "NFC:ChangeRFState") {
- // Update the current sessionId before sending to the NFC service.
- message.data.sessionId = SessionHelper.getId(message.data.sessionToken);
- }
-
- let command = CommandMsgTable[message.name];
- if (!command) {
- debug("Unknown message: " + message.name);
- return null;
- }
- this.targetsByRequestId[message.data.requestId] = message.target;
- this.sendToNfcService(command, message.data);
- return null;
- },
-
- removeTarget: function removeTarget(target) {
- Object.keys(this.targetsByRequestId).forEach((requestId) => {
- if (this.targetsByRequestId[requestId] === target) {
- delete this.targetsByRequestId[requestId];
- }
- });
- },
-
- /**
- * nsISettingsServiceCallback
- */
- handle: function handle(name, result) {
- switch (name) {
- case NFC.SETTING_NFC_DEBUG:
- DEBUG = result;
- updateDebug();
- break;
- }
- },
-
- /**
- * nsIObserver interface methods.
- */
- observe: function(subject, topic, data) {
- if (topic != "profile-after-change") {
- debug("Should receive 'profile-after-change' only, received " + topic);
- }
- },
-
- shutdown: function shutdown() {
- // We shutdown before initialization has been completed. The
- // pending messages will receive an error response.
- while (this.pendingMessageQueue.length) {
- this.sendNfcErrorResponse(this.pendingMessageQueue.shift(), "NotInitialize");
- }
- if (this.nfcService) {
- this.shutdownNfcService();
- }
- }
-};
-
-function NfcTechDiscoveredSysMsg(sessionToken, isP2P, records) {
- this.sessionToken = sessionToken;
- this.isP2P = isP2P;
- this.records = records;
-}
-NfcTechDiscoveredSysMsg.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINfcTechDiscoveredSysMsg]),
-
- sessionToken: null,
- isP2P: null,
- records: null
-};
-
-function NfcSendFileSysMsg(requestId, sessionToken, blob) {
- this.requestId = requestId;
- this.sessionToken = sessionToken;
- this.blob = blob;
-}
-NfcSendFileSysMsg.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINfcSendFileSysMsg]),
-
- requestId: null,
- sessionToken: null,
- blob: null
-};
-
-if (NFC_ENABLED) {
- this.NSGetFactory = XPCOMUtils.generateNSGetFactory([Nfc]);
-}
deleted file mode 100644
--- a/dom/nfc/gonk/Nfc.manifest
+++ /dev/null
@@ -1,11 +0,0 @@
-# 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/.
-#
-# Copyright © 2013 Deutsche Telekom, Inc.
-
-# Nfc.js
-component {2ff24790-5e74-11e1-b86c-0800200c9a66} Nfc.js
-contract @mozilla.org/nfc;1 {2ff24790-5e74-11e1-b86c-0800200c9a66}
-category profile-after-change Nfc @mozilla.org/nfc;1
-
deleted file mode 100644
--- a/dom/nfc/gonk/NfcMessageHandler.cpp
+++ /dev/null
@@ -1,392 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "NfcMessageHandler.h"
-#include <binder/Parcel.h>
-#include "mozilla/dom/MozNDEFRecordBinding.h"
-#include "nsDebug.h"
-#include "NfcOptions.h"
-#include "mozilla/Unused.h"
-
-#include <android/log.h>
-#define NMH_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "NfcMessageHandler", args)
-
-#define NFCD_MAJOR_VERSION 1
-#define NFCD_MINOR_VERSION 22
-
-using namespace android;
-using namespace mozilla;
-using namespace mozilla::dom;
-
-bool
-NfcMessageHandler::Marshall(Parcel& aParcel, const CommandOptions& aOptions)
-{
- bool result;
- switch (aOptions.mType) {
- case NfcRequestType::ChangeRFState:
- result = ChangeRFStateRequest(aParcel, aOptions);
- break;
- case NfcRequestType::ReadNDEF:
- result = ReadNDEFRequest(aParcel, aOptions);
- break;
- case NfcRequestType::WriteNDEF:
- result = WriteNDEFRequest(aParcel, aOptions);
- break;
- case NfcRequestType::MakeReadOnly:
- result = MakeReadOnlyRequest(aParcel, aOptions);
- break;
- case NfcRequestType::Format:
- result = FormatRequest(aParcel, aOptions);
- break;
- case NfcRequestType::Transceive:
- result = TransceiveRequest(aParcel, aOptions);
- break;
- default:
- result = false;
- break;
- };
-
- return result;
-}
-
-bool
-NfcMessageHandler::Unmarshall(const Parcel& aParcel, EventOptions& aOptions)
-{
- mozilla::Unused << htonl(aParcel.readInt32()); // parcel size
- int32_t type = aParcel.readInt32();
- bool isNtf = type >> 31;
- int32_t msgType = type & ~(1 << 31);
-
- return isNtf ? ProcessNotification(msgType, aParcel, aOptions) :
- ProcessResponse(msgType, aParcel, aOptions);
-}
-
-bool
-NfcMessageHandler::ProcessResponse(int32_t aType, const Parcel& aParcel, EventOptions& aOptions)
-{
- bool result;
- aOptions.mRspType = static_cast<NfcResponseType>(aType);
- switch (aOptions.mRspType) {
- case NfcResponseType::ChangeRFStateRsp:
- result = ChangeRFStateResponse(aParcel, aOptions);
- break;
- case NfcResponseType::ReadNDEFRsp:
- result = ReadNDEFResponse(aParcel, aOptions);
- break;
- case NfcResponseType::WriteNDEFRsp: // Fall through.
- case NfcResponseType::MakeReadOnlyRsp:
- case NfcResponseType::FormatRsp:
- result = GeneralResponse(aParcel, aOptions);
- break;
- case NfcResponseType::TransceiveRsp:
- result = TransceiveResponse(aParcel, aOptions);
- break;
- default:
- result = false;
- }
-
- return result;
-}
-
-bool
-NfcMessageHandler::ProcessNotification(int32_t aType, const Parcel& aParcel, EventOptions& aOptions)
-{
- bool result;
- aOptions.mNtfType = static_cast<NfcNotificationType>(aType);
- switch (aOptions.mNtfType) {
- case NfcNotificationType::Initialized:
- result = InitializeNotification(aParcel, aOptions);
- break;
- case NfcNotificationType::TechDiscovered:
- result = TechDiscoveredNotification(aParcel, aOptions);
- break;
- case NfcNotificationType::TechLost:
- result = TechLostNotification(aParcel, aOptions);
- break;
- case NfcNotificationType::HciEventTransaction:
- result = HCIEventTransactionNotification(aParcel, aOptions);
- break;
- case NfcNotificationType::NdefReceived:
- result = NDEFReceivedNotification(aParcel, aOptions);
- break;
- default:
- result = false;
- break;
- }
-
- return result;
-}
-
-bool
-NfcMessageHandler::GeneralResponse(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mErrorCode = aParcel.readInt32();
- aOptions.mSessionId = aParcel.readInt32();
-
- NS_ENSURE_TRUE(!mRequestIdQueue.IsEmpty(), false);
- aOptions.mRequestId = mRequestIdQueue[0];
- mRequestIdQueue.RemoveElementAt(0);
- return true;
-}
-
-bool
-NfcMessageHandler::ChangeRFStateRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::ChangeRFState));
- aParcel.writeInt32(aOptions.mRfState);
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::ChangeRFStateResponse(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mErrorCode = aParcel.readInt32();
- NS_ENSURE_TRUE(!mRequestIdQueue.IsEmpty(), false);
- aOptions.mRequestId = mRequestIdQueue[0];
- mRequestIdQueue.RemoveElementAt(0);
-
- aOptions.mRfState = aParcel.readInt32();
- return true;
-}
-
-bool
-NfcMessageHandler::ReadNDEFRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::ReadNDEF));
- aParcel.writeInt32(aOptions.mSessionId);
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::ReadNDEFResponse(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mErrorCode = aParcel.readInt32();
- aOptions.mSessionId = aParcel.readInt32();
-
- NS_ENSURE_TRUE(!mRequestIdQueue.IsEmpty(), false);
- aOptions.mRequestId = mRequestIdQueue[0];
- mRequestIdQueue.RemoveElementAt(0);
-
- if (aOptions.mErrorCode == 0) {
- ReadNDEFMessage(aParcel, aOptions);
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::TransceiveRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::Transceive));
- aParcel.writeInt32(aOptions.mSessionId);
- aParcel.writeInt32(aOptions.mTechnology);
-
- uint32_t length = aOptions.mCommand.Length();
- aParcel.writeInt32(length);
-
- void* data = aParcel.writeInplace(length);
- memcpy(data, aOptions.mCommand.Elements(), length);
-
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::TransceiveResponse(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mErrorCode = aParcel.readInt32();
- aOptions.mSessionId = aParcel.readInt32();
-
- NS_ENSURE_TRUE(!mRequestIdQueue.IsEmpty(), false);
- aOptions.mRequestId = mRequestIdQueue[0];
- mRequestIdQueue.RemoveElementAt(0);
-
- if (aOptions.mErrorCode == 0) {
- ReadTransceiveResponse(aParcel, aOptions);
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::WriteNDEFRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::WriteNDEF));
- aParcel.writeInt32(aOptions.mSessionId);
- aParcel.writeInt32(aOptions.mIsP2P);
- WriteNDEFMessage(aParcel, aOptions);
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::MakeReadOnlyRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::MakeReadOnly));
- aParcel.writeInt32(aOptions.mSessionId);
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::FormatRequest(Parcel& aParcel, const CommandOptions& aOptions)
-{
- aParcel.writeInt32(static_cast<int32_t>(NfcRequestType::Format));
- aParcel.writeInt32(aOptions.mSessionId);
- mRequestIdQueue.AppendElement(aOptions.mRequestId);
- return true;
-}
-
-bool
-NfcMessageHandler::InitializeNotification(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mStatus = aParcel.readInt32();
- aOptions.mMajorVersion = aParcel.readInt32();
- aOptions.mMinorVersion = aParcel.readInt32();
-
- if (aOptions.mMajorVersion != NFCD_MAJOR_VERSION ||
- aOptions.mMinorVersion != NFCD_MINOR_VERSION) {
- NMH_LOG("NFCD version mismatched. majorVersion: %d, minorVersion: %d",
- aOptions.mMajorVersion, aOptions.mMinorVersion);
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::TechDiscoveredNotification(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mSessionId = aParcel.readInt32();
- aOptions.mIsP2P = aParcel.readInt32();
-
- int32_t techCount = aParcel.readInt32();
- aOptions.mTechList.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(techCount)), techCount);
-
- int32_t idCount = aParcel.readInt32();
- aOptions.mTagId.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(idCount)), idCount);
-
- int32_t ndefMsgCount = aParcel.readInt32();
- if (ndefMsgCount != 0) {
- ReadNDEFMessage(aParcel, aOptions);
- }
-
- int32_t ndefInfo = aParcel.readInt32();
- if (ndefInfo) {
- aOptions.mTagType = aParcel.readInt32();
- aOptions.mMaxNDEFSize = aParcel.readInt32();
- aOptions.mIsReadOnly = aParcel.readInt32();
- aOptions.mIsFormatable = aParcel.readInt32();
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::TechLostNotification(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mSessionId = aParcel.readInt32();
- return true;
-}
-
-bool
-NfcMessageHandler::HCIEventTransactionNotification(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mOriginType = aParcel.readInt32();
- aOptions.mOriginIndex = aParcel.readInt32();
-
- int32_t aidLength = aParcel.readInt32();
- aOptions.mAid.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(aidLength)), aidLength);
-
- int32_t payloadLength = aParcel.readInt32();
- aOptions.mPayload.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(payloadLength)), payloadLength);
-
- return true;
-}
-
-bool
-NfcMessageHandler::NDEFReceivedNotification(const Parcel& aParcel, EventOptions& aOptions)
-{
- aOptions.mSessionId = aParcel.readInt32();
- int32_t ndefMsgCount = aParcel.readInt32();
- if (ndefMsgCount != 0) {
- ReadNDEFMessage(aParcel, aOptions);
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::ReadNDEFMessage(const Parcel& aParcel, EventOptions& aOptions)
-{
- int32_t recordCount = aParcel.readInt32();
- aOptions.mRecords.SetCapacity(recordCount);
-
- for (int i = 0; i < recordCount; i++) {
- int32_t tnf = aParcel.readInt32();
- NDEFRecordStruct record;
- record.mTnf = static_cast<TNF>(tnf);
-
- int32_t typeLength = aParcel.readInt32();
- record.mType.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(typeLength)), typeLength);
-
- int32_t idLength = aParcel.readInt32();
- record.mId.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(idLength)), idLength);
-
- int32_t payloadLength = aParcel.readInt32();
- record.mPayload.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(payloadLength)), payloadLength);
-
- aOptions.mRecords.AppendElement(record);
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::WriteNDEFMessage(Parcel& aParcel, const CommandOptions& aOptions)
-{
- int recordCount = aOptions.mRecords.Length();
- aParcel.writeInt32(recordCount);
- for (int i = 0; i < recordCount; i++) {
- const NDEFRecordStruct& record = aOptions.mRecords[i];
- aParcel.writeInt32(static_cast<int32_t>(record.mTnf));
-
- void* data;
-
- aParcel.writeInt32(record.mType.Length());
- data = aParcel.writeInplace(record.mType.Length());
- memcpy(data, record.mType.Elements(), record.mType.Length());
-
- aParcel.writeInt32(record.mId.Length());
- data = aParcel.writeInplace(record.mId.Length());
- memcpy(data, record.mId.Elements(), record.mId.Length());
-
- aParcel.writeInt32(record.mPayload.Length());
- data = aParcel.writeInplace(record.mPayload.Length());
- memcpy(data, record.mPayload.Elements(), record.mPayload.Length());
- }
-
- return true;
-}
-
-bool
-NfcMessageHandler::ReadTransceiveResponse(const Parcel& aParcel, EventOptions& aOptions)
-{
- uint32_t length = aParcel.readInt32();
-
- aOptions.mResponse.AppendElements(
- static_cast<const uint8_t*>(aParcel.readInplace(length)), length);
-
- return true;
-}
deleted file mode 100644
--- a/dom/nfc/gonk/NfcMessageHandler.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef NfcMessageHandler_h
-#define NfcMessageHandler_h
-
-#include "nsString.h"
-#include "nsTArray.h"
-
-namespace android {
-class MOZ_EXPORT Parcel;
-} // namespace android
-
-namespace mozilla {
-
-class CommandOptions;
-class EventOptions;
-
-class NfcMessageHandler
-{
-public:
- bool Marshall(android::Parcel& aParcel, const CommandOptions& aOptions);
- bool Unmarshall(const android::Parcel& aParcel, EventOptions& aOptions);
-
-private:
- bool ProcessResponse(int32_t aType, const android::Parcel& aParcel, EventOptions& aOptions);
- bool GeneralResponse(const android::Parcel& aParcel, EventOptions& aOptions);
- bool ChangeRFStateRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool ChangeRFStateResponse(const android::Parcel& aParcel, EventOptions& aOptions);
- bool ReadNDEFRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool ReadNDEFResponse(const android::Parcel& aParcel, EventOptions& aOptions);
- bool WriteNDEFRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool MakeReadOnlyRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool FormatRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool TransceiveRequest(android::Parcel& aParcel, const CommandOptions& options);
- bool TransceiveResponse(const android::Parcel& aParcel, EventOptions& aOptions);
-
- bool ProcessNotification(int32_t aType, const android::Parcel& aParcel, EventOptions& aOptions);
- bool InitializeNotification(const android::Parcel& aParcel, EventOptions& aOptions);
- bool TechDiscoveredNotification(const android::Parcel& aParcel, EventOptions& aOptions);
- bool TechLostNotification(const android::Parcel& aParcel, EventOptions& aOptions);
- bool HCIEventTransactionNotification(const android::Parcel& aParcel, EventOptions& aOptions);
- bool NDEFReceivedNotification(const android::Parcel& aParcel, EventOptions& aOptions);
-
- bool ReadNDEFMessage(const android::Parcel& aParcel, EventOptions& aOptions);
- bool WriteNDEFMessage(android::Parcel& aParcel, const CommandOptions& aOptions);
- bool ReadTransceiveResponse(const android::Parcel& aParcel, EventOptions& aOptions);
-private:
- nsTArray<nsString> mRequestIdQueue;
-};
-
-} // namespace mozilla
-
-#endif // NfcMessageHandler_h
deleted file mode 100644
--- a/dom/nfc/gonk/NfcOptions.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef NfcOptions_h
-#define NfcOptions_h
-
-#include "mozilla/dom/NfcOptionsBinding.h"
-#include "mozilla/dom/MozNDEFRecordBinding.h"
-
-namespace mozilla {
-
-struct NDEFRecordStruct
-{
- dom::TNF mTnf;
- nsTArray<uint8_t> mType;
- nsTArray<uint8_t> mId;
- nsTArray<uint8_t> mPayload;
-};
-
-struct CommandOptions
-{
- CommandOptions(const mozilla::dom::NfcCommandOptions& aOther) {
-
-#define COPY_FIELD(prop) prop = aOther.prop;
-
-#define COPY_OPT_FIELD(prop, defaultValue) \
- prop = aOther.prop.WasPassed() ? aOther.prop.Value() : defaultValue;
-
- COPY_FIELD(mType)
- COPY_FIELD(mRequestId)
- COPY_OPT_FIELD(mSessionId, 0)
-
- mRfState = aOther.mRfState.WasPassed() ?
- static_cast<int32_t>(aOther.mRfState.Value()) :
- 0;
-
- COPY_OPT_FIELD(mTechType, 0)
- COPY_OPT_FIELD(mIsP2P, false)
-
- mTechnology = aOther.mTechnology.WasPassed() ?
- static_cast<int32_t>(aOther.mTechnology.Value()) :
- -1;
-
- if (aOther.mCommand.WasPassed()) {
- dom::Uint8Array const & currentValue = aOther.mCommand.InternalValue();
- currentValue.ComputeLengthAndData();
- mCommand.AppendElements(currentValue.Data(), currentValue.Length());
- }
-
- if (!aOther.mRecords.WasPassed()) {
- return;
- }
-
- mozilla::dom::Sequence<mozilla::dom::MozNDEFRecordOptions> const & currentValue = aOther.mRecords.InternalValue();
- int count = currentValue.Length();
- for (int32_t i = 0; i < count; i++) {
- NDEFRecordStruct record;
- record.mTnf = currentValue[i].mTnf;
-
- if (currentValue[i].mType.WasPassed() &&
- !currentValue[i].mType.Value().IsNull()) {
- const dom::Uint8Array& type = currentValue[i].mType.Value().Value();
- type.ComputeLengthAndData();
- record.mType.AppendElements(type.Data(), type.Length());
- }
-
- if (currentValue[i].mId.WasPassed() &&
- !currentValue[i].mId.Value().IsNull()) {
- const dom::Uint8Array& id = currentValue[i].mId.Value().Value();
- id.ComputeLengthAndData();
- record.mId.AppendElements(id.Data(), id.Length());
- }
-
- if (currentValue[i].mPayload.WasPassed() &&
- !currentValue[i].mPayload.Value().IsNull()) {
- const dom::Uint8Array& payload = currentValue[i].mPayload.Value().Value();
- payload.ComputeLengthAndData();
- record.mPayload.AppendElements(payload.Data(), payload.Length());
- }
-
- mRecords.AppendElement(record);
- }
-
-#undef COPY_FIELD
-#undef COPY_OPT_FIELD
- }
-
- dom::NfcRequestType mType;
- int32_t mSessionId;
- nsString mRequestId;
- int32_t mRfState;
- int32_t mTechType;
- bool mIsP2P;
- nsTArray<NDEFRecordStruct> mRecords;
- int32_t mTechnology;
- nsTArray<uint8_t> mCommand;
-};
-
-struct EventOptions
-{
- EventOptions()
- : mRspType(dom::NfcResponseType::EndGuard_),
- mNtfType(dom::NfcNotificationType::EndGuard_),
- mStatus(-1), mErrorCode(-1), mSessionId(-1), mRequestId(EmptyString()),
- mMajorVersion(-1), mMinorVersion(-1), mIsP2P(-1),
- mTagType(-1), mMaxNDEFSize(-1), mIsReadOnly(-1), mIsFormatable(-1), mRfState(-1),
- mOriginType(-1), mOriginIndex(-1)
- {}
-
- dom::NfcResponseType mRspType;
- dom::NfcNotificationType mNtfType;
- int32_t mStatus;
- int32_t mErrorCode;
- int32_t mSessionId;
- nsString mRequestId;
- int32_t mMajorVersion;
- int32_t mMinorVersion;
- nsTArray<uint8_t> mTechList;
- nsTArray<uint8_t> mTagId;
- int32_t mIsP2P;
- nsTArray<NDEFRecordStruct> mRecords;
- int32_t mTagType;
- int32_t mMaxNDEFSize;
- int32_t mIsReadOnly;
- int32_t mIsFormatable;
- int32_t mRfState;
-
- int32_t mOriginType;
- int32_t mOriginIndex;
- nsTArray<uint8_t> mAid;
- nsTArray<uint8_t> mPayload;
- nsTArray<uint8_t> mResponse;
-};
-
-} // namespace mozilla
-
-#endif
deleted file mode 100644
--- a/dom/nfc/gonk/NfcService.cpp
+++ /dev/null
@@ -1,696 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "NfcService.h"
-#include <binder/Parcel.h>
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/dom/NfcOptionsBinding.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "mozilla/dom/RootedDictionary.h"
-#include "mozilla/EndianUtils.h"
-#include "mozilla/Hal.h"
-#include "mozilla/ipc/ListenSocket.h"
-#include "mozilla/ipc/ListenSocketConsumer.h"
-#include "mozilla/ipc/NfcConnector.h"
-#include "mozilla/ipc/StreamSocket.h"
-#include "mozilla/ipc/StreamSocketConsumer.h"
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/UniquePtr.h"
-#include "mozilla/Unused.h"
-#include "NfcMessageHandler.h"
-#include "NfcOptions.h"
-#include "nsString.h"
-#include "nsXULAppAPI.h"
-
-#define NS_NFCSERVICE_CID \
- { 0x584c9a21, 0x4e17, 0x43b7, {0xb1, 0x6a, 0x87, 0xa0, 0x42, 0xef, 0xd4, 0x64} }
-#define NS_NFCSERVICE_CONTRACTID "@mozilla.org/nfc/service;1"
-
-using namespace android;
-using namespace mozilla::dom;
-using namespace mozilla::ipc;
-using namespace mozilla::hal;
-
-namespace mozilla {
-
-static StaticRefPtr<NfcService> gNfcService;
-
-NS_IMPL_ISUPPORTS(NfcService, nsINfcService)
-
-//
-// NfcConsumer
-//
-
-/**
- * |NfcConsumer| implements the details of the connection to an NFC daemon
- * as well as the message passing.
- */
-class NfcConsumer
- : public ListenSocketConsumer
- , public StreamSocketConsumer
-{
-public:
- NfcConsumer(NfcService* aNfcService);
-
- nsresult Start();
- void Shutdown();
-
- nsresult Send(const CommandOptions& aCommandOptions);
- nsresult Receive(UnixSocketBuffer* aBuffer);
-
- // Methods for |StreamSocketConsumer| and |ListenSocketConsumer|
- //
-
- void ReceiveSocketData(
- int aIndex, UniquePtr<mozilla::ipc::UnixSocketBuffer>& aBuffer) override;
-
- void OnConnectSuccess(int aIndex) override;
- void OnConnectError(int aIndex) override;
- void OnDisconnect(int aIndex) override;
-
-private:
- class DispatchNfcEventRunnable;
- class ShutdownServiceRunnable;
-
- enum SocketType {
- LISTEN_SOCKET,
- STREAM_SOCKET
- };
-
- bool IsNfcServiceThread() const;
-
- RefPtr<NfcService> mNfcService;
- nsCOMPtr<nsIThread> mThread;
- RefPtr<mozilla::ipc::ListenSocket> mListenSocket;
- RefPtr<mozilla::ipc::StreamSocket> mStreamSocket;
- UniquePtr<NfcMessageHandler> mHandler;
- nsCString mListenSocketName;
-};
-
-NfcConsumer::NfcConsumer(NfcService* aNfcService)
- : mNfcService(aNfcService)
-{
- MOZ_ASSERT(mNfcService);
-}
-
-nsresult
-NfcConsumer::Start()
-{
- static const char BASE_SOCKET_NAME[] = "nfcd";
-
- MOZ_ASSERT(!mThread); // already started
-
- // Store a pointer of the consumer's NFC thread for
- // use with |IsNfcServiceThread|.
- mThread = do_GetCurrentThread();
-
- // If we could not cleanup properly before and an old
- // instance of the daemon is still running, we kill it
- // here.
- StopSystemService("nfcd");
-
- mHandler = MakeUnique<NfcMessageHandler>();
-
- mStreamSocket = new StreamSocket(this, STREAM_SOCKET);
-
- mListenSocketName = BASE_SOCKET_NAME;
-
- mListenSocket = new ListenSocket(this, LISTEN_SOCKET);
- nsresult rv = mListenSocket->Listen(new NfcConnector(mListenSocketName),
- mStreamSocket);
- if (NS_FAILED(rv)) {
- mStreamSocket = nullptr;
- mHandler = nullptr;
- mThread = nullptr;
- return rv;
- }
-
- return NS_OK;
-}
-
-void
-NfcConsumer::Shutdown()
-{
- MOZ_ASSERT(IsNfcServiceThread());
-
- mListenSocket->Close();
- mListenSocket = nullptr;
- mStreamSocket->Close();
- mStreamSocket = nullptr;
-
- mHandler = nullptr;
-
- mThread = nullptr;
-}
-
-nsresult
-NfcConsumer::Send(const CommandOptions& aOptions)
-{
- MOZ_ASSERT(IsNfcServiceThread());
-
- if (NS_WARN_IF(!mStreamSocket) ||
- NS_WARN_IF(mStreamSocket->GetConnectionStatus() != SOCKET_CONNECTED)) {
- return NS_OK; // Probably shutting down.
- }
-
- Parcel parcel;
- parcel.writeInt32(0); // Parcel Size.
- mHandler->Marshall(parcel, aOptions);
- parcel.setDataPosition(0);
- uint32_t sizeBE = htonl(parcel.dataSize() - sizeof(int));
- parcel.writeInt32(sizeBE);
-
- // TODO: Zero-copy buffer transfers
- mStreamSocket->SendSocketData(
- new UnixSocketRawData(parcel.data(), parcel.dataSize()));
-
- return NS_OK;
-}
-
-// Runnable used dispatch the NfcEventOptions on the main thread.
-class NfcConsumer::DispatchNfcEventRunnable final : public Runnable
-{
-public:
- DispatchNfcEventRunnable(NfcService* aNfcService, const EventOptions& aEvent)
- : mNfcService(aNfcService)
- , mEvent(aEvent)
- {
- MOZ_ASSERT(mNfcService);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mozilla::AutoSafeJSContext cx;
- RootedDictionary<NfcEventOptions> event(cx);
-
- // the copy constructor is private.
-#define COPY_FIELD(prop) event.prop = mEvent.prop;
-
-#define COPY_OPT_FIELD(prop, defaultValue) \
- if (mEvent.prop != defaultValue) { \
- event.prop.Construct(); \
- event.prop.Value() = mEvent.prop; \
- }
-
- COPY_OPT_FIELD(mRspType, NfcResponseType::EndGuard_)
- COPY_OPT_FIELD(mNtfType, NfcNotificationType::EndGuard_)
-
- // Only one of rspType and ntfType should be used.
- MOZ_ASSERT(((mEvent.mRspType != NfcResponseType::EndGuard_) ||
- (mEvent.mNtfType != NfcNotificationType::EndGuard_)) &&
- ((mEvent.mRspType == NfcResponseType::EndGuard_) ||
- (mEvent.mNtfType == NfcNotificationType::EndGuard_)));
-
- COPY_OPT_FIELD(mRequestId, EmptyString())
- COPY_OPT_FIELD(mStatus, -1)
- COPY_OPT_FIELD(mSessionId, -1)
- COPY_OPT_FIELD(mMajorVersion, -1)
- COPY_OPT_FIELD(mMinorVersion, -1)
-
- if (mEvent.mRfState != -1) {
- event.mRfState.Construct();
- RFState rfState = static_cast<RFState>(mEvent.mRfState);
- MOZ_ASSERT(rfState < RFState::EndGuard_);
- event.mRfState.Value() = rfState;
- }
-
- if (mEvent.mErrorCode != -1) {
- event.mErrorMsg.Construct();
- event.mErrorMsg.Value() = static_cast<NfcErrorMessage>(mEvent.mErrorCode);
- }
-
- if (mEvent.mTechList.Length() > 0) {
- int length = mEvent.mTechList.Length();
- event.mTechList.Construct();
-
- if (!event.mTechList.Value().SetCapacity(length, fallible)) {
- return NS_ERROR_FAILURE;
- }
-
- for (int i = 0; i < length; i++) {
- NFCTechType tech = static_cast<NFCTechType>(mEvent.mTechList[i]);
- MOZ_ASSERT(tech < NFCTechType::EndGuard_);
- // FIXME: Make this infallible after bug 968520 is done.
- *event.mTechList.Value().AppendElement(fallible) = tech;
- }
- }
-
- if (mEvent.mTagId.Length() > 0) {
- event.mTagId.Construct();
- event.mTagId.Value().Init(Uint8Array::Create(cx, mEvent.mTagId.Length(), mEvent.mTagId.Elements()));
- }
-
- if (mEvent.mRecords.Length() > 0) {
- int length = mEvent.mRecords.Length();
- event.mRecords.Construct();
- if (!event.mRecords.Value().SetCapacity(length, fallible)) {
- return NS_ERROR_FAILURE;
- }
-
- for (int i = 0; i < length; i++) {
- NDEFRecordStruct& recordStruct = mEvent.mRecords[i];
- // FIXME: Make this infallible after bug 968520 is done.
- MozNDEFRecordOptions& record =
- *event.mRecords.Value().AppendElement(fallible);
-
- record.mTnf = recordStruct.mTnf;
- MOZ_ASSERT(record.mTnf < TNF::EndGuard_);
-
- if (recordStruct.mType.Length() > 0) {
- record.mType.Construct();
- record.mType.Value().SetValue().Init(Uint8Array::Create(cx, recordStruct.mType.Length(), recordStruct.mType.Elements()));
- }
-
- if (recordStruct.mId.Length() > 0) {
- record.mId.Construct();
- record.mId.Value().SetValue().Init(Uint8Array::Create(cx, recordStruct.mId.Length(), recordStruct.mId.Elements()));
- }
-
- if (recordStruct.mPayload.Length() > 0) {
- record.mPayload.Construct();
- record.mPayload.Value().SetValue().Init(Uint8Array::Create(cx, recordStruct.mPayload.Length(), recordStruct.mPayload.Elements()));
- }
- }
- }
-
- COPY_OPT_FIELD(mIsP2P, -1)
-
- if (mEvent.mTagType != -1) {
- event.mTagType.Construct();
- event.mTagType.Value() = static_cast<NFCTagType>(mEvent.mTagType);
- }
-
- COPY_OPT_FIELD(mMaxNDEFSize, -1)
- COPY_OPT_FIELD(mIsReadOnly, -1)
- COPY_OPT_FIELD(mIsFormatable, -1)
-
- // HCI Event Transaction parameters.
- if (mEvent.mOriginType != -1) {
- MOZ_ASSERT(static_cast<HCIEventOrigin>(mEvent.mOriginType) < HCIEventOrigin::EndGuard_);
-
- event.mOrigin.Construct();
- event.mOrigin.Value().AssignASCII(HCIEventOriginValues::strings[mEvent.mOriginType].value);
- event.mOrigin.Value().AppendInt(mEvent.mOriginIndex, 16 /* radix */);
- }
-
- if (mEvent.mAid.Length() > 0) {
- event.mAid.Construct();
- event.mAid.Value().Init(Uint8Array::Create(cx, mEvent.mAid.Length(), mEvent.mAid.Elements()));
- }
-
- if (mEvent.mPayload.Length() > 0) {
- event.mPayload.Construct();
- event.mPayload.Value().Init(Uint8Array::Create(cx, mEvent.mPayload.Length(), mEvent.mPayload.Elements()));
- }
-
- if (mEvent.mResponse.Length() > 0) {
- event.mResponse.Construct();
- event.mResponse.Value().Init(
- Uint8Array::Create(cx, mEvent.mResponse.Length(), mEvent.mResponse.Elements()));
- }
-
-#undef COPY_FIELD
-#undef COPY_OPT_FIELD
-
- mNfcService->DispatchNfcEvent(event);
- return NS_OK;
- }
-
-private:
- RefPtr<NfcService> mNfcService;
- EventOptions mEvent;
-};
-
-nsresult
-NfcConsumer::Receive(UnixSocketBuffer* aBuffer)
-{
- MOZ_ASSERT(IsNfcServiceThread());
- MOZ_ASSERT(mHandler);
- MOZ_ASSERT(aBuffer);
-
- while (aBuffer->GetSize()) {
- const uint8_t* data = aBuffer->GetData();
- uint32_t parcelSize = BigEndian::readUint32(data);
-
- MOZ_ASSERT(parcelSize <= aBuffer->GetSize());
-
- // TODO: Zero-copy buffer transfers
- Parcel parcel;
- parcel.setData(aBuffer->GetData(), parcelSize + sizeof(parcelSize));
- aBuffer->Consume(parcelSize + sizeof(parcelSize));
-
- EventOptions event;
- mHandler->Unmarshall(parcel, event);
-
- NS_DispatchToMainThread(new DispatchNfcEventRunnable(mNfcService, event));
- }
-
- return NS_OK;
-}
-
-bool
-NfcConsumer::IsNfcServiceThread() const
-{
- return nsCOMPtr<nsIThread>(do_GetCurrentThread()) == mThread;
-}
-
-// |StreamSocketConsumer|, |ListenSocketConsumer|
-
-void
-NfcConsumer::ReceiveSocketData(
- int aIndex, UniquePtr<mozilla::ipc::UnixSocketBuffer>& aBuffer)
-{
- MOZ_ASSERT(IsNfcServiceThread());
- MOZ_ASSERT(aIndex == STREAM_SOCKET);
-
- Receive(aBuffer.get());
-}
-
-void
-NfcConsumer::OnConnectSuccess(int aIndex)
-{
- MOZ_ASSERT(IsNfcServiceThread());
-
- switch (aIndex) {
- case LISTEN_SOCKET: {
- nsCString args("-S -a ");
- args.Append(mListenSocketName);
- nsresult rv = StartSystemService("nfcd", args.get());
- if (NS_FAILED(rv)) {
- OnConnectError(STREAM_SOCKET);
- }
- break;
- }
- case STREAM_SOCKET:
- /* nothing to do */
- break;
- }
-}
-
-class NfcConsumer::ShutdownServiceRunnable final : public Runnable
-{
-public:
- ShutdownServiceRunnable(NfcService* aNfcService)
- : mNfcService(aNfcService)
- {
- MOZ_ASSERT(mNfcService);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mNfcService->Shutdown();
-
- return NS_OK;
- }
-
-private:
- RefPtr<NfcService> mNfcService;
-};
-
-void
-NfcConsumer::OnConnectError(int aIndex)
-{
- MOZ_ASSERT(IsNfcServiceThread());
-
- NS_DispatchToMainThread(new ShutdownServiceRunnable(mNfcService));
-}
-
-void
-NfcConsumer::OnDisconnect(int aIndex)
-{
- MOZ_ASSERT(IsNfcServiceThread());
-}
-
-//
-// NfcService
-//
-
-NfcService::NfcService()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!gNfcService);
-}
-
-NfcService::~NfcService()
-{
- MOZ_ASSERT(!gNfcService);
-}
-
-already_AddRefed<NfcService>
-NfcService::FactoryCreate()
-{
- if (!XRE_IsParentProcess()) {
- return nullptr;
- }
-
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!gNfcService) {
- gNfcService = new NfcService();
- ClearOnShutdown(&gNfcService);
- }
-
- RefPtr<NfcService> service(gNfcService);
- return service.forget();
-}
-
-/**
- * |StartConsumerRunnable| calls |NfcConsumer::Start| on the NFC thread.
- */
-class NfcService::StartConsumerRunnable final : public Runnable
-{
-public:
- StartConsumerRunnable(NfcConsumer* aNfcConsumer)
- : mNfcConsumer(aNfcConsumer)
- {
- MOZ_ASSERT(mNfcConsumer);
- }
-
- NS_IMETHOD Run() override
- {
- mNfcConsumer->Start();
-
- return NS_OK;
- }
-
-private:
- NfcConsumer* mNfcConsumer;
-};
-
-NS_IMETHODIMP
-NfcService::Start(nsINfcGonkEventListener* aListener)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(aListener);
- MOZ_ASSERT(!mThread);
- MOZ_ASSERT(!mNfcConsumer);
-
- auto nfcConsumer = MakeUnique<NfcConsumer>(this);
-
- nsresult rv = NS_NewNamedThread("NfcThread", getter_AddRefs(mThread));
- if (NS_FAILED(rv)) {
- NS_WARNING("Can't create Nfc worker thread.");
- return rv;
- }
-
- rv = mThread->Dispatch(new StartConsumerRunnable(nfcConsumer.get()),
- nsIEventTarget::DISPATCH_NORMAL);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- mListener = aListener;
- mNfcConsumer = Move(nfcConsumer);
-
- return NS_OK;
-}
-
-/**
- * |CleanupRunnable| deletes instances of the NFC consumer and
- * thread on the main thread. This has to be down after shutting
- * down the NFC consumer on the NFC thread.
- */
-class NfcService::CleanupRunnable final : public Runnable
-{
-public:
- CleanupRunnable(NfcConsumer* aNfcConsumer,
- already_AddRefed<nsIThread> aThread)
- : mNfcConsumer(aNfcConsumer)
- , mThread(aThread)
- {
- MOZ_ASSERT(mNfcConsumer);
- MOZ_ASSERT(mThread);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mNfcConsumer = nullptr; // deletes NFC consumer
-
- mThread->Shutdown();
- mThread = nullptr; // deletes NFC worker thread
-
- return NS_OK;
- }
-
-private:
- UniquePtr<NfcConsumer> mNfcConsumer;
- nsCOMPtr<nsIThread> mThread;
-};
-
-/**
- * |ShutdownConsumerRunnable| calls |NfcConsumer::Shutdown| on the
- * NFC thread. Optionally, it can dispatch a |CleanupRunnable| to
- * the main thread for cleaning up the NFC resources.
- */
-class NfcService::ShutdownConsumerRunnable final : public Runnable
-{
-public:
- ShutdownConsumerRunnable(NfcConsumer* aNfcConsumer, bool aCleanUp)
- : mNfcConsumer(aNfcConsumer)
- , mCleanUp(aCleanUp)
- {
- MOZ_ASSERT(mNfcConsumer);
- }
-
- NS_IMETHOD Run() override
- {
- mNfcConsumer->Shutdown();
-
- if (mCleanUp) {
- NS_DispatchToMainThread(
- new CleanupRunnable(mNfcConsumer, do_GetCurrentThread()));
- }
-
- return NS_OK;
- }
-
-private:
- NfcConsumer* mNfcConsumer;
- bool mCleanUp;
-};
-
-NS_IMETHODIMP
-NfcService::Shutdown()
-{
- if (!mNfcConsumer) {
- return NS_OK; // NFC was shut down meanwhile; not an error
- }
-
- nsresult rv = mThread->Dispatch(
- new ShutdownConsumerRunnable(mNfcConsumer.get(), true),
- nsIEventTarget::DISPATCH_NORMAL);
-
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- // |CleanupRunnable| will take care of these pointers
- Unused << mNfcConsumer.release();
- Unused << mThread.forget();
-
- return NS_OK;
-}
-
-/**
- * |SendRunnable| calls |NfcConsumer::Send| on the NFC thread.
- */
-class NfcService::SendRunnable final : public Runnable
-{
-public:
- SendRunnable(NfcConsumer* aNfcConsumer, const CommandOptions& aOptions)
- : mNfcConsumer(aNfcConsumer)
- , mOptions(aOptions)
- {
- MOZ_ASSERT(mNfcConsumer);
- }
-
- NS_IMETHOD Run() override
- {
- mNfcConsumer->Send(mOptions);
-
- return NS_OK;
- }
-
-private:
- NfcConsumer* mNfcConsumer;
- CommandOptions mOptions;
-};
-
-NS_IMETHODIMP
-NfcService::SendCommand(JS::HandleValue aOptions, JSContext* aCx)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- NfcCommandOptions options;
-
- if (!options.Init(aCx, aOptions)) {
- NS_WARNING("Bad dictionary passed to NfcService::SendCommand");
- return NS_ERROR_FAILURE;
- }
-
- // Dispatch the command to the NFC thread.
- nsresult rv = mThread->Dispatch(
- new SendRunnable(mNfcConsumer.get(), CommandOptions(options)),
- nsIEventTarget::DISPATCH_NORMAL);
-
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- return NS_OK;
-}
-
-void
-NfcService::DispatchNfcEvent(const mozilla::dom::NfcEventOptions& aOptions)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(mListener);
-
- if (!mNfcConsumer) {
- return; // NFC has been shutdown meanwhile; not en error
- }
-
- mozilla::AutoSafeJSContext cx;
- JS::RootedValue val(cx);
-
- if (!ToJSValue(cx, aOptions, &val)) {
- return;
- }
-
- mListener->OnEvent(val);
-}
-
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(NfcService,
- NfcService::FactoryCreate)
-
-NS_DEFINE_NAMED_CID(NS_NFCSERVICE_CID);
-
-static const mozilla::Module::CIDEntry kNfcServiceCIDs[] = {
- { &kNS_NFCSERVICE_CID, false, nullptr, NfcServiceConstructor },
- { nullptr }
-};
-
-static const mozilla::Module::ContractIDEntry kNfcServiceContracts[] = {
- { NS_NFCSERVICE_CONTRACTID, &kNS_NFCSERVICE_CID },
- { nullptr }
-};
-
-static const mozilla::Module kNfcServiceModule = {
- mozilla::Module::kVersion,
- kNfcServiceCIDs,
- kNfcServiceContracts,
- nullptr
-};
-
-} // namespace mozilla
-
-NSMODULE_DEFN(NfcServiceModule) = &mozilla::kNfcServiceModule;
deleted file mode 100644
--- a/dom/nfc/gonk/NfcService.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef NfcService_h
-#define NfcService_h
-
-#include "nsCOMPtr.h"
-#include "nsINfcService.h"
-
-class nsIThread;
-
-namespace mozilla {
-namespace dom {
-class NfcEventOptions;
-} // namespace dom
-
-class NfcConsumer;
-
-class NfcService final : public nsINfcService
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSINFCSERVICE
-
- static already_AddRefed<NfcService> FactoryCreate();
-
- void DispatchNfcEvent(const mozilla::dom::NfcEventOptions& aOptions);
-
-private:
- class CleanupRunnable;
- class SendRunnable;
- class ShutdownConsumerRunnable;
- class StartConsumerRunnable;
-
- NfcService();
- ~NfcService();
-
- nsCOMPtr<nsIThread> mThread;
- nsCOMPtr<nsINfcGonkEventListener> mListener;
- UniquePtr<NfcConsumer> mNfcConsumer;
-};
-
-} // namespace mozilla
-
-#endif // NfcService_h
deleted file mode 100644
--- a/dom/nfc/gonk/nfc_consts.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2013, Deutsche Telekom, Inc. */
-
-// Set to true to debug all NFC layers
-this.DEBUG_ALL = false;
-
-// Set individually to debug specific layers
-this.DEBUG_CONTENT_HELPER = DEBUG_ALL || false;
-this.DEBUG_NFC = DEBUG_ALL || false;
-
-// Gecko specific error codes
-this.NFC_GECKO_ERROR_P2P_REG_INVALID = 1;
-this.NFC_GECKO_ERROR_SEND_FILE_FAILED = 2;
-
-this.NFC_ERROR_MSG = {};
-this.NFC_ERROR_MSG[this.NFC_GECKO_ERROR_P2P_REG_INVALID] = "NfcP2PRegistrationInvalid";
-this.NFC_ERROR_MSG[this.NFC_GECKO_ERROR_SEND_FILE_FAILED] = "NfcSendFileFailed";
-
-this.NFC_RF_STATE_IDLE = "idle";
-this.NFC_RF_STATE_LISTEN = "listen";
-this.NFC_RF_STATE_DISCOVERY = "discovery";
-
-this.TOPIC_MOZSETTINGS_CHANGED = "mozsettings-changed";
-this.TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-
-this.SETTING_NFC_DEBUG = "nfc.debugging.enabled";
-
-this.PEER_EVENT_READY = 0x01;
-this.PEER_EVENT_LOST = 0x02;
-this.TAG_EVENT_FOUND = 0x03;
-this.TAG_EVENT_LOST = 0x04;
-this.PEER_EVENT_FOUND = 0x05;
-this.RF_EVENT_STATE_CHANGED = 0x06;
-this.FOCUS_CHANGED = 0x07;
-
-// This value should sync with |SYSTEM_APP_ID| in nsINfcContentHelper.idl
-this.SYSTEM_APP_ID = 0;
-
-// Allow this file to be imported via Components.utils.import().
-this.EXPORTED_SYMBOLS = Object.keys(this);
deleted file mode 100644
--- a/dom/nfc/gonk/nsINfcService.idl
+++ /dev/null
@@ -1,21 +0,0 @@
-/* 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/. */
-
-#include "nsISupports.idl"
-
-[scriptable, uuid(cc9f1e96-fddc-4d98-8399-8d11c4f640aa)]
-interface nsINfcGonkEventListener : nsISupports
-{
- void onEvent(in jsval event);
-};
-
-[scriptable, uuid(8beeb4cd-5661-4e67-83ca-d335f0801484)]
-interface nsINfcService : nsISupports
-{
- void start(in nsINfcGonkEventListener listener);
- void shutdown();
-
- [implicit_jscontext]
- void sendCommand(in jsval param);
-};
deleted file mode 100644
--- a/dom/nfc/gonk/nsINfcSystemMessage.idl
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-#include "nsISupports.idl"
-
-interface nsIDOMBlob ;
-interface nsIVariant;
-
-[scriptable, uuid(ff0b1622-0e79-4d97-8153-6244a2410eee)]
-interface nsINfcTechDiscoveredSysMsg : nsISupports
-{
- readonly attribute DOMString sessionToken;
- readonly attribute boolean isP2P;
- readonly attribute nsIVariant records;
-};
-
-[scriptable, uuid(31c334f5-f072-451f-9405-19d0ac7ae7d1)]
-interface nsINfcSendFileSysMsg : nsISupports
-{
- readonly attribute DOMString requestId;
- readonly attribute DOMString sessionToken;
- readonly attribute nsIDOMBlob blob;
-};
-
deleted file mode 100644
--- a/dom/nfc/messages/HCIEventTransactionSystemMessage.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {b501edd0-28bd-11e4-8c21-0800200c9a66} HCIEventTransactionSystemMessageConfigurator.js
-contract @mozilla.org/dom/system-messages/configurator/nfc-hci-event-transaction;1 {b501edd0-28bd-11e4-8c21-0800200c9a66}
deleted file mode 100644
--- a/dom/nfc/messages/HCIEventTransactionSystemMessageConfigurator.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* 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";
-
-const { interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "appsService",
- "@mozilla.org/AppsService;1",
- "nsIAppsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "aceService",
- "@mozilla.org/secureelement/access-control/ace;1",
- "nsIAccessControlEnforcer");
-
-XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
- "resource://gre/modules/SEUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "SE", () => {
- let obj = {};
- Cu.import("resource://gre/modules/se_consts.js", obj);
- return obj;
-});
-
-var DEBUG = SE.DEBUG_SE;
-function debug(aMsg) {
- if (DEBUG) {
- dump("-*- HCIEventTransaction: " + aMsg);
- }
-}
-
-/**
- * nsISystemMessagesConfigurator implementation.
- */
-function HCIEventTransactionSystemMessageConfigurator() {
- debug("HCIEventTransactionSystemMessageConfigurator");
-}
-
-HCIEventTransactionSystemMessageConfigurator.prototype = {
- get mustShowRunningApp() {
- debug("mustShowRunningApp returning true");
- return true;
- },
-
- shouldDispatch: function shouldDispatch(aManifestURL, aPageURL, aType, aMessage, aExtra) {
- DEBUG && debug("message to dispatch: " + JSON.stringify(aMessage));
- debug("aManifest url: " + aManifestURL);
-
- if (!aMessage) {
- return Promise.resolve(false);
- }
-
- let appId = appsService.getAppLocalIdByManifestURL(aManifestURL);
- if (appId === Ci.nsIScriptSecurityManager.NO_APP_ID) {
- return Promise.resolve(false);
- }
-
- return new Promise((resolve, reject) => {
- appsService.getManifestFor(aManifestURL)
- .then((aManifest) => this._checkAppManifest(aMessage.origin, aMessage.aid, aManifest))
- .then(() => aceService.isAccessAllowed(appId, aMessage.origin, aMessage.aid))
- .then((allowed) => {
- debug("dispatching message: " + allowed);
- resolve(allowed);
- })
- .catch(() => {
- debug("not dispatching");
- resolve(false);
- });
- });
- },
-
- _checkAppManifest: function _checkAppManifest(aOrigin, aAid, aManifest) {
- DEBUG && debug("aManifest " + JSON.stringify(aManifest));
-
- // convert AID and Secure Element name to uppercased string for comparison
- // with manifest secure_element_access rules
- let aid = SEUtils.byteArrayToHexString(aAid);
- let seName = (aOrigin) ? aOrigin.toUpperCase() : "";
-
- let hciRules = aManifest["secure_element_access"] || [];
- let matchingRule = hciRules.find((rule) => {
- rule = rule.toUpperCase();
- if(rule === "*" || rule === (seName + "/" + aid)) {
- return true;
- }
-
- let isMatching = (match, element) => {
- if(match === "*") {
- return true;
- }
- if(match.charAt(match.length - 1) === '*') {
- return element.indexOf(match.substr(0,match.length - 1)) === 0;
- }
-
- return match === element;
- };
-
- return isMatching(rule.split('/')[0], seName) &&
- isMatching(rule.split('/')[1], aid);
- });
-
- return (matchingRule) ? Promise.resolve() : Promise.reject();
- },
-
- classID: Components.ID("{b501edd0-28bd-11e4-8c21-0800200c9a66}"),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISystemMessagesConfigurator])
-}
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([HCIEventTransactionSystemMessageConfigurator]);
deleted file mode 100644
--- a/dom/nfc/moz.build
+++ /dev/null
@@ -1,57 +0,0 @@
-# vim: set filetype=python:
-# 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/.
-#
-# Copyright © 2013 Deutsche Telekom, Inc.
-
-XPIDL_MODULE = 'dom_nfc'
-
-if CONFIG['MOZ_NFC']:
- XPIDL_SOURCES += [
- 'nsINfcContentHelper.idl',
- ]
- EXPORTS.mozilla.dom += [
- 'MozIsoDepTech.h',
- 'MozNDEFRecord.h',
- 'MozNfcATech.h',
- 'TagUtils.h',
- ]
- UNIFIED_SOURCES += [
- 'MozIsoDepTech.cpp',
- 'MozNDEFRecord.cpp',
- 'MozNfcATech.cpp',
- 'TagUtils.cpp',
- ]
- EXTRA_COMPONENTS += [
- 'NfcContentHelper.js',
- 'NfcContentHelper.manifest',
- 'nsNfc.js',
- 'nsNfc.manifest',
- ]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['MOZ_NFC']:
- UNIFIED_SOURCES += [
- 'gonk/NfcMessageHandler.cpp',
- 'gonk/NfcService.cpp',
- ]
- XPIDL_SOURCES += [
- 'gonk/nsINfcService.idl',
- 'gonk/nsINfcSystemMessage.idl',
- ]
- EXTRA_COMPONENTS += [
- 'gonk/Nfc.js',
- 'gonk/Nfc.manifest',
- 'messages/HCIEventTransactionSystemMessage.manifest',
- 'messages/HCIEventTransactionSystemMessageConfigurator.js',
- ]
- EXTRA_JS_MODULES += [
- 'gonk/nfc_consts.js',
- ]
- XPCSHELL_TESTS_MANIFESTS += [
- 'tests/unit/xpcshell.ini'
- ]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
deleted file mode 100644
--- a/dom/nfc/nsINfcContentHelper.idl
+++ /dev/null
@@ -1,333 +0,0 @@
-/* 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/. */
-
-#include "nsISupports.idl"
-
-interface nsIVariant;
-interface nsIDOMWindow;
-
-[scriptable, uuid(a694c7e8-10dd-416e-a3d9-433edf40647e)]
-interface nsITagInfo : nsISupports
-{
- /**
- * Array of technolgies supported. See NFCTechType in MozNFCTag.webidl
- */
- readonly attribute nsIVariant techList;
-
- readonly attribute nsIVariant tagId; // Uint8Array
-};
-
-[scriptable, uuid(74d70ebb-557f-4ac8-8296-7885961cd1dc)]
-interface nsITagNDEFInfo : nsISupports
-{
- // one of NFCTagType defined in MozNFCTag.webidl.
- readonly attribute DOMString tagType;
-
- readonly attribute long maxNDEFSize;
-
- readonly attribute boolean isReadOnly;
-
- readonly attribute boolean isFormatable;
-};
-
-[scriptable, uuid(86e46a0c-016d-4e5d-9fb5-789eb71848a1)]
-interface nsINfcEventListener : nsISupports
-{
- /**
- * Callback function used to notify tagfound.
- *
- * @param sessionToken
- * SessionToken received from parent process
- * @param tagInfo
- * nsITagInfo received from parent process.
- * @param ndefInfo
- * nsITagNDEFInfo received from parent process, could be null if the
- * tag is not formated as NDEF.
- * @param ndefRecords
- * NDEF records pre-read during tag-discovered.
- */
- void notifyTagFound(in DOMString sessionToken,
- in nsITagInfo tagInfo,
- in nsITagNDEFInfo ndefInfo,
- in nsIVariant ndefRecords);
-
- /**
- * Callback function used to notify taglost.
- *
- * @param sessionToken
- * SessionToken received from parent process
- */
- void notifyTagLost(in DOMString sessionToken);
-
- /**
- * Callback function used to notify peerfound/peerready.
- * @param sessionToken
- * SessionToken received from parent process
- * @param isPeerReady
- * Set to true to dispatch peerready instead of peerfound
- */
- void notifyPeerFound(in DOMString sessionToken, [optional] in boolean isPeerReady);
-
- /**
- * Callback function used to notify peerlost.
- *
- * @param sessionToken
- * SessionToken received from parent process
- */
- void notifyPeerLost(in DOMString sessionToken);
-
- /**
- * Callback function used to notify RF state change.
- *
- * @param rfState
- * RF state received from parent process
- */
- void notifyRFStateChanged(in DOMString rfState);
-
- /**
- * Callback function used to notify focus changed.
- *
- * @param focus
- * focus value receveid from parent process.
- */
- void notifyFocusChanged(in boolean focus);
-
- /**
- * The window object of this event listener.
- */
- readonly attribute nsIDOMWindow window;
-};
-
-[scriptable, uuid(6c913015-9658-46a9-88d9-6ecfda2bd020)]
-interface nsINfcRequestCallback : nsISupports
-{
- DOMString getCallbackId();
-
- void notifySuccess();
-
- void notifySuccessWithBoolean(in boolean result);
-
- void notifySuccessWithNDEFRecords(in nsIVariant records);
-
- void notifySuccessWithByteArray(in nsIVariant array);
-
- void notifyError(in DOMString errorMsg);
-};
-
-[scriptable, uuid(9f86c799-6959-4ad2-bdd6-6fbf49b52d1c)]
-interface nsINfcBrowserAPI : nsISupports
-{
- const int32_t SYSTEM_APP_ID = 0;
-
- void setFocusTab(in uint64_t tabId,
- in boolean isFocus);
-};
-
-[scriptable, uuid(75f0c8c0-2e5a-491f-a75d-4f3849c4feec)]
-interface nsINfcContentHelper : nsISupports
-{
- /**
- * Read current NDEF data on the tag.
- *
- * @param sessionToken
- * Current token
- *
- * @param callback
- * Called when request is finished
- */
- void readNDEF(in DOMString sessionToken,
- in nsINfcRequestCallback callback);
-
- /**
- * Write NDEF data to a peer device or a tag.
- *
- * @param records
- * NDEF records to be written
- *
- * @param isP2P
- * If this write is for P2P.
- * @param sessionToken
- * Current token
- *
- * @param callback
- * Called when request is finished
- */
- void writeNDEF(in nsIVariant records,
- in boolean isP2P,
- in DOMString sessionToken,
- in nsINfcRequestCallback callback);
-
- /**
- * Make a tag read-only
- *
- * @param sessionToken
- * Current token
- *
- * @param callback
- * Called when request is finished
- */
- void makeReadOnly(in DOMString sessionToken,
- in nsINfcRequestCallback callback);
-
- /**
- * Format a tag as NDEF
- *
- * @param sessionToken
- * Current token
- *
- * @param callback
- * Called when request is finished
- */
- void format(in DOMString sessionToken,
- in nsINfcRequestCallback callback);
-
- /**
- * Send raw command to the tag and receive the response.
- *
- * @param sessionToken
- * Current token
- *
- * @param technology
- * Tag technology
- *
- * @param command
- * Command to send
- *
- * @param callback
- * Called when request is finished
- *
- */
- void transceive(in DOMString sessionToken,
- in DOMString technology,
- in nsIVariant command,
- in nsINfcRequestCallback callback);
-
- /**
- * Get current RF state. This function will be blocking.
- */
- DOMString queryRFState();
-
- /**
- * Initiate send file operation.
- *
- * @param blob
- * Raw data of the file to be sent. This object represents a file-like
- * (DOM File) object of immutable, raw data. The blob data needs
- * to be 'object wrapped' before calling this interface.
- *
- * @param sessionToken
- * Current token
- *
- * @param callback
- * Called when request is finished
- */
- void sendFile(in jsval blob,
- 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, in uint64_t tabId);
-
- /**
- * Remove event listener.
- *
- * @param tabId
- * The tabId provided in addEventListener.
- */
- void removeEventListener(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);
-
- /**
- * Unregister the given application id with parent process
- *
- * @param appId
- * Application ID to be registered
- */
- void unregisterTargetForPeerReady(in unsigned long appId);
-
- /**
- * Checks if the given application's id is a registered peer target (with the parent process)
- *
- * @param appId
- * Application ID to be updated with parent process
- *
- * @param callback
- * Called when request is finished
- */
- void checkP2PRegistration(in unsigned long appId,
- in nsINfcRequestCallback callback);
-
- /**
- * Notify the parent process that user has accepted to share nfc message on P2P UI
- *
- * @param appId
- * Application ID that is capable of handling NFC_EVENT_PEER_READY event
- */
- void notifyUserAcceptedP2P(in unsigned long appId);
-
- /**
- * Notify the status of sendFile operation to parent process
- *
- * @param status
- * Status of sendFile operation
- *
- * @param requestId
- * Request ID of SendFile DOM Request
- */
- void notifySendFileStatus(in octet status,
- in DOMString requestId);
-
- /**
- * Change RF state.
- *
- * @param rfState. Possible values are 'idle', 'listen' and 'discovery'.
- *
- * @param callback
- * Called when request is finished
- */
- void changeRFState(in DOMString rfState,
- in nsINfcRequestCallback callback);
-
- /**
- * Notify parent process to call the default tagfound or peerfound event
- * handler.
- *
- * @param sessionToken
- * Session token of this event.
- * @param isP2P
- * Is this a P2P Session.
- * @param records
- * NDEF Records.
- */
- void callDefaultFoundHandler(in DOMString sessionToken,
- in boolean isP2P,
- in nsIVariant records);
-
- /**
- * Notify parent process to call the default taglost or peerlost event
- * handler.
- *
- * @param sessionToken
- * Session token of this event.
- * @param isP2P
- * Is this a P2P Session.
- */
- void callDefaultLostHandler(in DOMString sessionToken,
- in boolean isP2P);
-
-};
deleted file mode 100644
--- a/dom/nfc/nsNfc.js
+++ /dev/null
@@ -1,767 +0,0 @@
-/* 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/. */
-
-/* Copyright © 2013, Deutsche Telekom, Inc. */
-
-"use strict";
-
-const DEBUG = false;
-function debug(s) {
- if (DEBUG) dump("-*- Nfc DOM: " + s + "\n");
-}
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this,
- "appsService",
- "@mozilla.org/AppsService;1",
- "nsIAppsService");
-
-function NfcCallback(aWindow) {
- this._window = aWindow;
- this.initDOMRequestHelper(aWindow, null);
- this._createPromise();
-}
-NfcCallback.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- _window: null,
- promise: null,
- _requestId: null,
-
- _createPromise: function _createPromise() {
- this.promise = this.createPromiseWithId((aResolverId) => {
- this._requestId = btoa(aResolverId);
- });
- },
-
- getCallbackId: function getCallbackId() {
- return this._requestId;
- },
-
- notifySuccess: function notifySuccess() {
- let resolver = this.takePromiseResolver(atob(this._requestId));
- if (!resolver) {
- debug("can not find promise resolver for id: " + this._requestId);
- return;
- }
- resolver.resolve();
- },
-
- notifySuccessWithBoolean: function notifySuccessWithBoolean(aResult) {
- let resolver = this.takePromiseResolver(atob(this._requestId));
- if (!resolver) {
- debug("can not find promise resolver for id: " + this._requestId);
- return;
- }
- resolver.resolve(aResult);
- },
-
- notifySuccessWithNDEFRecords: function notifySuccessWithNDEFRecords(aRecords) {
- let resolver = this.takePromiseResolver(atob(this._requestId));
- if (!resolver) {
- debug("can not find promise resolver for id: " + this._requestId);
- return;
- }
-
- 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;
- }
- resolver.resolve(Cu.cloneInto(aArray, this._window));
- },
-
- notifyError: function notifyError(aErrorMsg) {
- let resolver = this.takePromiseResolver(atob(this._requestId));
- if (!resolver) {
- debug("can not find promise resolver for id: " + this._requestId +
- ", errormsg: " + aErrorMsg);
- return;
- }
- resolver.reject(new this._window.Error(aErrorMsg));
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference,
- Ci.nsIObserver,
- Ci.nsINfcRequestCallback]),
-};
-
-// Should be mapped to the NFCTagType defined in MozNFCTag.webidl.
-var TagType = {
- TYPE1: "Type1",
- TYPE2: "Type2",
- TYPE3: "Type3",
- TYPE4: "Type4",
- MIFARE_CLASSIC: "MIFARE-Classic"
-};
-
-/**
- * Implementation of NFCTag.
- *
- * @param window global window object.
- * @param sessionToken session token received from parent process.
- * @param tagInfo type of nsITagInfo received from parent process.
- * @parem ndefInfo type of nsITagNDEFInfo received from parent process.
- */
-function MozNFCTagImpl(window, sessionToken, tagInfo, ndefInfo) {
- debug("In MozNFCTagImpl Constructor");
- this._nfcContentHelper = Cc["@mozilla.org/nfc/content-helper;1"]
- .getService(Ci.nsINfcContentHelper);
- this._window = window;
- this.session = sessionToken;
- this.techList = tagInfo.techList;
- this.id = Cu.cloneInto(tagInfo.tagId, window);
-
- if (ndefInfo) {
- this.type = ndefInfo.tagType;
- this.maxNDEFSize = ndefInfo.maxNDEFSize;
- this.isReadOnly = ndefInfo.isReadOnly;
- this.isFormatable = ndefInfo.isFormatable;
- this.canBeMadeReadOnly = this.type == TagType.TYPE1 ||
- this.type == TagType.TYPE2 ||
- this.type == TagType.MIFARE_CLASSIC;
- }
-}
-MozNFCTagImpl.prototype = {
- _nfcContentHelper: null,
- _window: null,
- session: null,
- techList: null,
- id: null,
- type: null,
- maxNDEFSize: null,
- isReadOnly: null,
- isFormatable: null,
- canBeMadeReadOnly: null,
- isLost: false,
-
- createTech: { "ISO-DEP": (win, tag) => { return new win.MozIsoDepTech(tag); },
- "NFC-A" : (win, tag) => { return new win.MozNfcATech(tag); },
- },
-
- // NFCTag interface:
- readNDEF: function readNDEF() {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.readNDEF(this.session, callback);
- return callback.promise;
- },
-
- writeNDEF: function writeNDEF(records) {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- if (this.isReadOnly) {
- throw new this._window.Error("NFCTag object is read-only");
- }
-
- let ndefLen = 0;
- for (let record of records) {
- ndefLen += record.size;
- }
-
- if (ndefLen > this.maxNDEFSize) {
- throw new this._window.Error("Exceed max NDEF size");
- }
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.writeNDEF(records, false, this.session, callback);
- return callback.promise;
- },
-
- makeReadOnly: function makeReadOnly() {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- if (!this.canBeMadeReadOnly) {
- throw new this._window.Error("NFCTag object cannot be made read-only");
- }
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.makeReadOnly(this.session, callback);
- return callback.promise;
- },
-
- format: function format() {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- if (!this.isFormatable) {
- throw new this._window.Error("NFCTag object is not formatable");
- }
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.format(this.session, callback);
- return callback.promise;
- },
-
- selectTech: function selectTech(tech) {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- if (this.techList.indexOf(tech) == -1) {
- throw new this._window.Error(
- "NFCTag does not contain selected tag technology");
- }
-
- if (this.createTech[tech] === undefined) {
- throw new this._window.Error("Technology is not supported now");
- }
-
- return this.createTech[tech](this._window, this._contentObj);
- },
-
- transceive: function transceive(tech, cmd) {
- if (this.isLost) {
- throw new this._window.Error("NFCTag object is invalid");
- }
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.transceive(this.session, tech, cmd, callback);
- return callback.promise;
- },
-
- notifyLost: function notifyLost() {
- this.isLost = true;
- },
-
- classID: Components.ID("{4e1e2e90-3137-11e3-aa6e-0800200c9a66}"),
- contractID: "@mozilla.org/nfc/tag;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsIDOMGlobalPropertyInitializer]),
-};
-
-/**
- * Implementation of NFCPeer.
- *
- * @param window global window object.
- * @param sessionToken session token received from parent process.
- */
-function MozNFCPeerImpl(aWindow, aSessionToken) {
- debug("In MozNFCPeerImpl Constructor");
- this._nfcContentHelper = Cc["@mozilla.org/nfc/content-helper;1"]
- .getService(Ci.nsINfcContentHelper);
-
- this._window = aWindow;
- this.session = aSessionToken;
-}
-MozNFCPeerImpl.prototype = {
- _nfcContentHelper: null,
- _window: null,
- isLost: false,
-
- // NFCPeer interface:
- sendNDEF: function sendNDEF(records) {
- if (this.isLost) {
- throw new this._window.Error("NFCPeer object is invalid");
- }
-
- // Just forward sendNDEF to writeNDEF
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.writeNDEF(records, true, this.session, callback);
- return callback.promise;
- },
-
- sendFile: function sendFile(blob) {
- if (this.isLost) {
- throw new this._window.Error("NFCPeer object is invalid");
- }
-
- let data = {
- "blob": blob
- };
-
- let callback = new NfcCallback(this._window);
- this._nfcContentHelper.sendFile(Cu.cloneInto(data, this._window),
- this.session, callback);
- return callback.promise;
- },
-
- notifyLost: function notifyLost() {
- this.isLost = true;
- },
-
- classID: Components.ID("{c1b2bcf0-35eb-11e3-aa6e-0800200c9a66}"),
- contractID: "@mozilla.org/nfc/peer;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsIDOMGlobalPropertyInitializer]),
-};
-
-// Should be mapped to the RFState defined in WebIDL.
-var RFState = {
- IDLE: "idle",
- LISTEN: "listen",
- DISCOVERY: "discovery"
-};
-
-/**
- * Implementation of navigator NFC object.
- */
-function MozNFCImpl() {
- debug("In MozNFCImpl Constructor");
- try {
- this._nfcContentHelper = Cc["@mozilla.org/nfc/content-helper;1"]
- .getService(Ci.nsINfcContentHelper);
- } catch(e) {
- debug("No NFC support.");
- }
-
- this.eventService = Cc["@mozilla.org/eventlistenerservice;1"]
- .getService(Ci.nsIEventListenerService);
-}
-MozNFCImpl.prototype = {
- _nfcContentHelper: null,
- window: null,
- _tabId: null,
- _innerWindowId: null,
- _rfState: null,
- _contentObj: null,
- nfcPeer: null,
- nfcTag: null,
- eventService: null,
-
- init: function init(aWindow) {
- debug("MozNFCImpl init called");
- this.window = aWindow;
- let util = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
- this._innerWindowId = util.currentInnerWindowID;
-
- this.defineEventHandlerGetterSetter("ontagfound");
- this.defineEventHandlerGetterSetter("ontaglost");
- this.defineEventHandlerGetterSetter("onpeerready");
- this.defineEventHandlerGetterSetter("onpeerfound");
- this.defineEventHandlerGetterSetter("onpeerlost");
-
- Services.obs.addObserver(this, "inner-window-destroyed",
- /* weak-ref */ false);
-
- if (this._nfcContentHelper) {
- 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);
- this._nfcContentHelper.checkP2PRegistration(appID, callback);
- return callback.promise;
- },
-
- notifyUserAcceptedP2P: function notifyUserAcceptedP2P(manifestUrl) {
- let appID = appsService.getAppLocalIdByManifestURL(manifestUrl);
- // Notify chrome process of user's acknowledgement
- this._nfcContentHelper.notifyUserAcceptedP2P(appID);
- },
-
- notifySendFileStatus: function notifySendFileStatus(status, requestId) {
- this._nfcContentHelper.notifySendFileStatus(status, requestId);
- },
-
- startPoll: function startPoll() {
- let callback = new NfcCallback(this.window);
- this._nfcContentHelper.changeRFState(RFState.DISCOVERY, callback);
- return callback.promise;
- },
-
- stopPoll: function stopPoll() {
- let callback = new NfcCallback(this.window);
- this._nfcContentHelper.changeRFState(RFState.LISTEN, callback);
- return callback.promise;
- },
-
- powerOff: function powerOff() {
- let callback = new NfcCallback(this.window);
- this._nfcContentHelper.changeRFState(RFState.IDLE, callback);
- return callback.promise;
- },
-
- get enabled() {
- return this._rfState != RFState.IDLE;
- },
-
- observe: function observe(subject, topic, data) {
- if (topic !== "inner-window-destroyed") {
- return;
- }
-
- let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
- if (wId != this._innerWindowId) {
- return;
- }
-
- this._nfcContentHelper.removeEventListener(this._tabId);
- },
-
- defineEventHandlerGetterSetter: function defineEventHandlerGetterSetter(name) {
- Object.defineProperty(this, name, {
- get: function get() {
- return this.__DOM_IMPL__.getEventHandler(name);
- },
- set: function set(handler) {
- this.__DOM_IMPL__.setEventHandler(name, handler);
- }
- });
- },
-
- eventListenerWasAdded: function(eventType) {
- if (eventType !== "peerready") {
- return;
- }
-
- let appId = this.window.document.nodePrincipal.appId;
- this._nfcContentHelper.registerTargetForPeerReady(appId);
- },
-
- eventListenerWasRemoved: function(eventType) {
- if (eventType !== "peerready") {
- return;
- }
-
- let appId = this.window.document.nodePrincipal.appId;
- this._nfcContentHelper.unregisterTargetForPeerReady(appId);
- },
-
- notifyTagFound: function notifyTagFound(sessionToken, tagInfo, ndefInfo, records) {
- if (!this.handleTagFound(sessionToken, tagInfo, ndefInfo, records)) {
- this._nfcContentHelper.callDefaultFoundHandler(sessionToken, false, records);
- };
- },
-
- /**
- * Handles Tag Found event.
- *
- * returns true if the app could process this event, false otherwise.
- */
- handleTagFound: function handleTagFound(sessionToken, tagInfo, ndefInfo, records) {
- if (this.hasDeadWrapper()) {
- dump("this.window or this.__DOM_IMPL__ is a dead wrapper.");
- return false;
- }
-
- if (!this.eventService.hasListenersFor(this.__DOM_IMPL__, "tagfound")) {
- debug("ontagfound is not registered.");
- return false;
- }
-
- if (!this.checkPermissions(["nfc"])) {
- return false;
- }
-
- let tagImpl = new MozNFCTagImpl(this.window, sessionToken, tagInfo, ndefInfo);
- let tag = this.window.MozNFCTag._create(this.window, tagImpl);
-
- tagImpl._contentObj = tag;
- this.nfcTag = tag;
-
- let length = records ? records.length : 0;
- let ndefRecords = records ? [] : null;
- for (let i = 0; i < length; i++) {
- let record = records[i];
- ndefRecords.push(new this.window.MozNDEFRecord({tnf: record.tnf,
- type: record.type,
- id: record.id,
- payload: record.payload}));
- }
-
- let eventData = {
- "cancelable": true,
- "tag": tag,
- "ndefRecords": ndefRecords
- };
-
- debug("fire ontagfound " + sessionToken);
- let tagEvent = new this.window.MozNFCTagEvent("tagfound", eventData);
- this.__DOM_IMPL__.dispatchEvent(tagEvent);
-
- // If defaultPrevented is false, means we need to take the default action
- // for this event - redirect this event to System app. Before redirecting to
- // System app, we need revoke the tag object first.
- if (!tagEvent.defaultPrevented) {
- this.notifyTagLost(sessionToken);
- }
-
- return tagEvent.defaultPrevented;
- },
-
- notifyTagLost: function notifyTagLost(sessionToken) {
- if (!this.handleTagLost(sessionToken)) {
- this._nfcContentHelper.callDefaultLostHandler(sessionToken, false);
- }
- },
-
- handleTagLost: function handleTagLost(sessionToken) {
- if (this.hasDeadWrapper()) {
- dump("this.window or this.__DOM_IMPL__ is a dead wrapper.");
- return false;
- }
-
- if (!this.checkPermissions(["nfc"])) {
- return false;
- }
-
- if (!this.nfcTag) {
- debug("No NFCTag object existing.");
- return false;
- }
-
- this.nfcTag.notifyLost();
- this.nfcTag = null;
-
- debug("fire ontaglost " + sessionToken);
- let event = new this.window.Event("taglost");
- this.__DOM_IMPL__.dispatchEvent(event);
-
- return true;
- },
-
- notifyPeerFound: function notifyPeerFound(sessionToken, isPeerReady) {
- if (!this.handlePeerFound(sessionToken, isPeerReady)) {
- this._nfcContentHelper.callDefaultFoundHandler(sessionToken, true, null);
- }
- },
-
- /**
- * Handles Peer Found/Peer Ready event.
- *
- * returns true if the app could process this event, false otherwise.
- */
- handlePeerFound: function handlePeerFound(sessionToken, isPeerReady) {
- if (this.hasDeadWrapper()) {
- dump("this.window or this.__DOM_IMPL__ is a dead wrapper.");
- return false;
- }
-
- if (!isPeerReady &&
- !this.eventService.hasListenersFor(this.__DOM_IMPL__, "peerfound")) {
- debug("onpeerfound is not registered.");
- return false;
- }
-
- let perm = isPeerReady ? ["nfc-share"] : ["nfc"];
- if (!this.checkPermissions(perm)) {
- return false;
- }
-
- let peerImpl = new MozNFCPeerImpl(this.window, sessionToken);
- this.nfcPeer = this.window.MozNFCPeer._create(this.window, peerImpl);
-
- let eventType;
- let eventData = {
- "peer": this.nfcPeer
- };
-
- if (isPeerReady) {
- eventType = "peerready";
- } else {
- eventData.cancelable = true;
- eventType = "peerfound";
- }
-
- debug("fire on" + eventType + " " + sessionToken);
- let event = new this.window.MozNFCPeerEvent(eventType, eventData);
- this.__DOM_IMPL__.dispatchEvent(event);
-
- // For peerready we don't take the default action.
- if (isPeerReady) {
- return true;
- }
-
- // If defaultPrevented is false, means we need to take the default action
- // for this event - redirect this event to System app. Before redirecting to
- // System app, we need revoke the peer object first.
- if (!event.defaultPrevented) {
- this.notifyPeerLost(sessionToken);
- }
-
- return event.defaultPrevented;
- },
-
- notifyPeerLost: function notifyPeerLost(sessionToken) {
- if (!this.handlePeerLost(sessionToken)) {
- this._nfcContentHelper.callDefaultLostHandler(sessionToken, true);
- }
- },
-
- handlePeerLost: function handlePeerLost(sessionToken) {
- if (this.hasDeadWrapper()) {
- dump("this.window or this.__DOM_IMPL__ is a dead wrapper.");
- return false;
- }
-
- if (!this.checkPermissions(["nfc", "nfc-share"])) {
- return false;
- }
-
- if (!this.nfcPeer) {
- debug("No NFCPeer object existing.");
- return false;
- }
-
- this.nfcPeer.notifyLost();
- this.nfcPeer = null;
-
- debug("fire onpeerlost");
- let event = new this.window.Event("peerlost");
- this.__DOM_IMPL__.dispatchEvent(event);
-
- return true;
- },
-
- notifyRFStateChanged: function notifyRFStateChanged(rfState) {
- this._rfState = rfState;
- },
-
- notifyFocusChanged: function notifyFocusChanged(focus) {
- if (focus) {
- return;
- }
-
- if (this.nfcTag) {
- debug("losing focus, call taglost.");
- this.notifyTagLost(this.nfcTag.session);
- }
-
- if (this.nfcPeer) {
- debug("losing focus, call peerlost.");
- this.notifyPeerLost(this.nfcPeer.session);
- }
- },
-
- checkPermissions: function checkPermissions(perms) {
- let principal = this.window.document.nodePrincipal;
- for (let perm of perms) {
- let permValue =
- Services.perms.testExactPermissionFromPrincipal(principal, perm);
- if (permValue == Ci.nsIPermissionManager.ALLOW_ACTION) {
- return true;
- } else {
- debug("doesn't have " + perm + " permission.");
- }
- }
-
- return false;
- },
-
- hasDeadWrapper: function hasDeadWrapper() {
- return Cu.isDeadWrapper(this.window) || Cu.isDeadWrapper(this.__DOM_IMPL__);
- },
-
- classID: Components.ID("{6ff2b290-2573-11e3-8224-0800200c9a66}"),
- contractID: "@mozilla.org/nfc/manager;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsIDOMGlobalPropertyInitializer,
- Ci.nsINfcEventListener,
- Ci.nsIObserver]),
-};
-
-function NFCSendFileWrapper() {
-}
-NFCSendFileWrapper.prototype = {
- // nsISystemMessagesWrapper implementation.
- wrapMessage: function wrapMessage(aMessage, aWindow) {
- let peerImpl = new MozNFCPeerImpl(aWindow, aMessage.sessionToken);
- let peer = aWindow.MozNFCPeer._create(aWindow, peerImpl);
-
- delete aMessage.sessionToken;
- aMessage = Cu.cloneInto(aMessage, aWindow);
- aMessage.peer = peer;
- return aMessage;
- },
-
- classDescription: "NFCSendFileWrapper",
- classID: Components.ID("{c5063a5c-8cb9-41d2-baf5-56062a2e30e9}"),
- contractID: "@mozilla.org/dom/system-messages/wrapper/nfc-manager-send-file;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISystemMessagesWrapper])
-};
-
-function NFCTechDiscoveredWrapper() {
-}
-NFCTechDiscoveredWrapper.prototype = {
- // nsISystemMessagesWrapper implementation.
- wrapMessage: function wrapMessage(aMessage, aWindow) {
- aMessage = Cu.cloneInto(aMessage, aWindow);
- if (aMessage.isP2P) {
- let peerImpl = new MozNFCPeerImpl(aWindow, aMessage.sessionToken);
- let peer = aWindow.MozNFCPeer._create(aWindow, peerImpl);
- aMessage.peer = peer;
- }
-
- delete aMessage.isP2P;
- delete aMessage.sessionToken;
-
- return aMessage;
- },
-
- classDescription: "NFCTechDiscoveredWrapper",
- classID: Components.ID("{2e7f9285-3c72-4e1f-b985-141a00a23a75}"),
- contractID: "@mozilla.org/dom/system-messages/wrapper/nfc-manager-tech-discovered;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISystemMessagesWrapper])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MozNFCTagImpl,
- MozNFCPeerImpl, MozNFCImpl, NFCSendFileWrapper, NFCTechDiscoveredWrapper]);
deleted file mode 100644
--- a/dom/nfc/nsNfc.manifest
+++ /dev/null
@@ -1,14 +0,0 @@
-component {6ff2b290-2573-11e3-8224-0800200c9a66} nsNfc.js
-contract @mozilla.org/nfc/manager;1 {6ff2b290-2573-11e3-8224-0800200c9a66}
-
-component {4e1e2e90-3137-11e3-aa6e-0800200c9a66} nsNfc.js
-contract @mozilla.org/nfc/tag;1 {4e1e2e90-3137-11e3-aa6e-0800200c9a66}
-
-component {c1b2bcf0-35eb-11e3-aa6e-0800200c9a66} nsNfc.js
-contract @mozilla.org/nfc/peer;1 {c1b2bcf0-35eb-11e3-aa6e-0800200c9a66}
-
-component {c5063a5c-8cb9-41d2-baf5-56062a2e30e9} nsNfc.js
-contract @mozilla.org/dom/system-messages/wrapper/nfc-manager-send-file;1 {c5063a5c-8cb9-41d2-baf5-56062a2e30e9}
-
-component {2e7f9285-3c72-4e1f-b985-141a00a23a75} nsNfc.js
-contract @mozilla.org/dom/system-messages/wrapper/nfc-manager-tech-discovered;1 {2e7f9285-3c72-4e1f-b985-141a00a23a75}
deleted file mode 100644
--- a/dom/nfc/tests/marionette/head.js
+++ /dev/null
@@ -1,385 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const Cu = SpecialPowers.Cu;
-
-var Promise = Cu.import("resource://gre/modules/Promise.jsm").Promise;
-var nfc = window.navigator.mozNfc;
-
-SpecialPowers.addPermission("nfc-manager", true, document);
-
-/**
- * Emulator helper.
- */
-var emulator = (function() {
- let pendingCmdCount = 0;
- let originalRunEmulatorCmd = runEmulatorCmd;
-
- // Overwritten it so people could not call this function directly.
- runEmulatorCmd = function() {
- throw "Use emulator.run(cmd, callback) instead of runEmulatorCmd";
- };
-
- function run(cmd, callback) {
- log("Executing emulator command '" + cmd + "'");
- pendingCmdCount++;
- originalRunEmulatorCmd(cmd, function(result) {
- pendingCmdCount--;
- if (callback && typeof callback === "function") {
- callback(result);
- }
- });
- };
-
- return {
- run: run,
- pendingCmdCount: pendingCmdCount,
- P2P_RE_INDEX_0 : 0,
- P2P_RE_INDEX_1 : 1,
- T1T_RE_INDEX : 2,
- T2T_RE_INDEX : 3,
- T3T_RE_INDEX : 4,
- T4T_RE_INDEX : 5
- };
-}());
-
-var sysMsgHelper = (function() {
- function techDiscovered(msg) {
- log("system message nfc-manager-tech-discovered");
- let discovered = mDiscovered.shift();
- if (discovered) {
- discovered(msg);
- }
- }
-
- function techLost(msg) {
- log("system message nfc-manager-tech-lost");
- let lost = mLost.shift();
- if (lost) {
- lost(msg);
- }
- }
-
- function sendFile(msg) {
- log("system message nfc-manager-send-file");
- let send = mSendFile.shift();
- if (send) {
- send(msg);
- }
- }
-
- let mDiscovered = [], mLost = [], mSendFile = [];
- window.navigator.mozSetMessageHandler("nfc-manager-tech-discovered",
- techDiscovered);
- window.navigator.mozSetMessageHandler("nfc-manager-tech-lost", techLost);
- window.navigator.mozSetMessageHandler("nfc-manager-send-file", sendFile);
-
- return {
- waitForTechDiscovered: function(discovered) {
- mDiscovered.push(discovered);
- },
-
- waitForTechLost: function(lost) {
- mLost.push(lost);
- },
-
- waitForSendFile: function(sendFile) {
- mSendFile.push(sendFile);
- },
-
- };
-}());
-
-var NCI = (function() {
- function activateRE(re) {
- let deferred = Promise.defer();
- let cmd = 'nfc nci rf_intf_activated_ntf ' + re;
-
- emulator.run(cmd, function(result) {
- is(result.pop(), 'OK', 'check activation of RE' + re);
- deferred.resolve();
- });
-
- return deferred.promise;
- };
-
- function deactivate() {
- let deferred = Promise.defer();
- let cmd = 'nfc nci rf_intf_deactivate_ntf';
-
- emulator.run(cmd, function(result) {
- is(result.pop(), 'OK', 'check deactivate');
- deferred.resolve();
- });
-
- return deferred.promise;
- };
-
- function notifyDiscoverRE(re, type) {
- let deferred = Promise.defer();
- let cmd = 'nfc nci rf_discover_ntf ' + re + ' ' + type;
-
- emulator.run(cmd, function(result) {
- is(result.pop(), 'OK', 'check discovery of RE' + re);
- deferred.resolve();
- });
-
- return deferred.promise;
- };
-
- return {
- activateRE: activateRE,
- deactivate: deactivate,
- notifyDiscoverRE: notifyDiscoverRE,
- LAST_NOTIFICATION: 0,
- LIMIT_NOTIFICATION: 1,
- MORE_NOTIFICATIONS: 2
- };
-}());
-
-var TAG = (function() {
- function setData(re, flag, tnf, type, payload) {
- let deferred = Promise.defer();
- let tnfNum = NDEF.getTNFNum(tnf);
- let cmd = "nfc tag set " + re +
- " [" + flag + "," + tnfNum + "," + type + ",," + payload + "]";
-
- emulator.run(cmd, function(result) {
- is(result.pop(), "OK", "set NDEF data of tag" + re);
- deferred.resolve();
- });
-
- return deferred.promise;
- };
-
- function clearData(re) {
- let deferred = Promise.defer();
- let cmd = "nfc tag clear " + re;
-
- emulator.run(cmd, function(result) {
- is(result.pop(), "OK", "clear tag" + re);
- deferred.resolve();
- });
- }
-
- return {
- setData: setData,
- clearData: clearData
- };
-}());
-
-var SNEP = (function() {
- function put(dsap, ssap, flags, tnf, type, id, payload) {
- let deferred = Promise.defer();
- let tnfNum = NDEF.getTNFNum(tnf);
- let cmd = "nfc snep put " + dsap + " " + ssap + " [" + flags + "," +
- tnfNum + "," +
- type + "," +
- id + "," +
- payload + "]";
- emulator.run(cmd, function(result) {
- is(result.pop(), "OK", "send SNEP PUT");
- deferred.resolve();
- });
-
- return deferred.promise;
- };
-
- return {
- put: put,
- SAP_NDEF: 4
- };
-}());
-
-function toggleNFC(enabled) {
- let deferred = Promise.defer();
-
- // In bug 1109592, nfcd will only run when nfc is enabled.
- // The way we activate/deactivate nfcd is by using set property "ctl.start" & "ctl.stop".
- // In emulator it seems sometimes enable/disable NFC too quick will cause nfcd won't starat,
- // So here we use a simple workaround to delay enable or disable for 100ms, bug 1164786 is
- // created to track this issue.
- setTimeout(function() {
- let promise;
- if (enabled) {
- promise = nfc.startPoll();
- } else {
- promise = nfc.powerOff();
- }
-
- promise.then(() => {
- deferred.resolve();
- }).catch(() => {
- ok(false, 'operation failed, error ' + req.error.name);
- deferred.reject();
- finish();
- });
- }, 100);
-
- return deferred.promise;
-}
-
-function activateAndwaitForTechDiscovered(re) {
- let deferred = Promise.defer();
-
- sysMsgHelper.waitForTechDiscovered(function() {
- deferred.resolve();
- });
-
- NCI.activateRE(re);
-
- return deferred.promise;
-}
-
-function deactivateAndWaitForTechLost() {
- let deferred = Promise.defer();
-
- sysMsgHelper.waitForTechLost(function() {
- deferred.resolve();
- });
-
- NCI.deactivate();
-
- return deferred.promise;
-}
-
-function deactivateAndWaitForPeerLost() {
- let deferred = Promise.defer();
-
- nfc.onpeerlost = function() {
- deferred.resolve();
- };
-
- NCI.deactivate();
-
- return deferred.promise;
-}
-
-function clearPendingMessages(type) {
- if (!window.navigator.mozHasPendingMessage(type)) {
- return;
- }
-
- // setting a handler removes all messages from queue
- window.navigator.mozSetMessageHandler(type, function() {
- window.navigator.mozSetMessageHandler(type, null);
- });
-}
-
-function cleanUp() {
- log('Cleaning up');
- waitFor(function() {
- SpecialPowers.removePermission("nfc-manager", document);
- finish()
- },
- function() {
- return emulator.pendingCmdCount === 0;
- });
-}
-
-function runNextTest() {
- clearPendingMessages('nfc-manager-tech-discovered');
- clearPendingMessages('nfc-manager-tech-lost');
-
- let test = tests.shift();
- if (!test) {
- cleanUp();
- return;
- }
- test();
-}
-
-// run this function to start tests
-function runTests() {
- if ('mozNfc' in window.navigator) {
- runNextTest();
- } else {
- // succeed immediately on systems without NFC
- log('Skipping test on system without NFC');
- ok(true, 'Skipping test on system without NFC');
- finish();
- }
-}
-
-const NDEF = {
- TNF_WELL_KNOWN: "well-known",
-
- tnfValues: ["empty", "well-known", "media-type", "absolute-uri", "external",
- "unknown", "unchanged", "reserved"],
-
- getTNFNum: function (tnfString) {
- return this.tnfValues.indexOf(tnfString);
- },
-
- getTNFString: function(tnfNum) {
- return this.tnfValues[tnfNum];
- },
-
- // compares two NDEF messages
- compare: function(ndef1, ndef2) {
- isnot(ndef1, null, "LHS message is not null");
- isnot(ndef2, null, "RHS message is not null");
- is(ndef1.length, ndef2.length,
- "NDEF messages have the same number of records");
- ndef1.forEach(function(record1, index) {
- let record2 = this[index];
- is(record1.tnf, record2.tnf, "test for equal TNF fields");
- let fields = ["type", "id", "payload"];
- fields.forEach(function(value) {
- let field1 = Cu.waiveXrays(record1)[value];
- let field2 = Cu.waiveXrays(record2)[value];
- if (!field1 || !field2) {
- return;
- }
-
- is(field1.length, field2.length,
- value + " fields have the same length");
- let eq = true;
- for (let i = 0; eq && i < field1.length; ++i) {
- eq = (field1[i] === field2[i]);
- }
- ok(eq, value + " fields contain the same data");
- });
- }, ndef2);
- },
-
- // parses an emulator output string into an NDEF message
- parseString: function(str) {
- // make it an object
- let arr = null;
- try {
- arr = JSON.parse(str);
- } catch (e) {
- ok(false, "Parser error: " + e.message);
- return null;
- }
- // and build NDEF array
- let ndef = arr.map(function(value) {
- let type = NfcUtils.fromUTF8(this.atob(value.type));
- let id = NfcUtils.fromUTF8(this.atob(value.id));
- let payload = NfcUtils.fromUTF8(this.atob(value.payload));
- return new MozNDEFRecord({tnf: NDEF.getTNFString(value.tnf), type: type, id: id, payload: payload});
- }, window);
- return ndef;
- }
-};
-
-var NfcUtils = {
- fromUTF8: function(str) {
- let buf = new Uint8Array(str.length);
- for (let i = 0; i < str.length; ++i) {
- buf[i] = str.charCodeAt(i);
- }
- return buf;
- },
- toUTF8: function(array) {
- if (!array) {
- return null;
- }
- let str = "";
- for (var i = 0; i < array.length; i++) {
- str += String.fromCharCode(array[i]);
- }
- return str;
- }
-};
deleted file mode 100644
--- a/dom/nfc/tests/marionette/manifest.ini
+++ /dev/null
@@ -1,16 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'b2g'
-
-[test_ndef.js]
-[test_nfc_enabled.js]
-[test_nfc_manager_tech_discovered.js]
-[test_nfc_manager_tech_discovered_ndef.js]
-[test_nfc_manager_tech_lost.js]
-[test_nfc_peer.js]
-[test_nfc_peer_sendndef.js]
-[test_nfc_peer_sendFile.js]
-[test_nfc_read_tag.js]
-[test_nfc_checkP2PRegistration.js]
-[test_nfc_error_messages.js]
-[test_nfc_tag_found.js]
-[test_nfc_tag_lost.js]
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_ndef.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function testConstructNDEF() {
- try {
- // omit type, id and payload.
- let r = new MozNDEFRecord();
- is(r.tnf, "empty", "r.tnf should be 'empty'");
- is(r.type, null, "r.type should be null");
- is(r.id, null, "r.id should be null");
- is(r.payload, null, "r.payload should be null");
-
- ok(true);
- } catch (e) {
- ok(false, 'type, id or payload should be optional. error:' + e);
- }
-
- try {
- new MozNDEFRecord({type: new Uint8Array(1)});
- ok(false, "new MozNDEFRecord should fail, type should be null for empty tnf");
- } catch (e){
- ok(true);
- }
-
- try {
- new MozNDEFRecord({tnf: "unknown", type: new Uint8Array(1)});
- ok(false, "new MozNDEFRecord should fail, type should be null for unknown tnf");
- } catch (e){
- ok(true);
- }
-
- try {
- new MozNDEFRecord({tnf: "unchanged", type: new Uint8Array(1)});
- ok(false, "new MozNDEFRecord should fail, type should be null for unchanged tnf");
- } catch (e){
- ok(true);
- }
-
- try {
- new MozNDEFRecord({tnf: "illegal", type: new Uint8Array(1)});
- ok(false, "new MozNDEFRecord should fail, invalid tnf");
- } catch (e){
- ok(true);
- }
-
- runNextTest();
-}
-
-var tests = [
- testConstructNDEF
-];
-
-runTests();
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_checkP2PRegistration.js
+++ /dev/null
@@ -1,141 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-'use strict';
-
-/* globals log, is, ok, runTests, toggleNFC, runNextTest,
- SpecialPowers, nfc */
-
-const MARIONETTE_TIMEOUT = 60000;
-const MARIONETTE_HEAD_JS = 'head.js';
-
-const MANIFEST_URL = 'app://system.gaiamobile.org/manifest.webapp';
-const FAKE_MANIFEST_URL = 'app://fake.gaiamobile.org/manifest.webapp';
-
-/**
- * Failure scenarion without onpeerread handler registration
- * Nfc not enabled -> no session token.
- */
-function testNoTargetNoSessionToken() {
- log('testNoTargetNoSessionToken');
- nfc.checkP2PRegistration(MANIFEST_URL)
- .then((result) => {
- is(result, false, 'No target, no sesionToken, result should be false');
- runNextTest();
- })
- .catch(handleRejectedPromise);
-}
-
-/**
- * Failure scenario onpeerready handler registered but Nfc not enabled
- * -> no session token.
- */
-function testWithTargetNoSessionToken() {
- log('testWithTargetNoSessionToken');
- registerOnpeerready()
- .then(() => nfc.checkP2PRegistration(MANIFEST_URL))
- .then((result) => {
- is(result, false,
- 'session token is available and it shouldnt be');
- nfc.onpeerready = null;
- runNextTest();
- })
- .catch(handleRejectedPromise);
-}
-
-/**
- * Success scenario, nfc enabled, activated RE0 (p2p ndef is received,
- * creates session token) opeerreadyhandler registered.
- */
-function testWithSessionTokenWithTarget() {
- log('testWithSessionTokenWithTarget');
- toggleNFC(true)
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(registerOnpeerready)
- .then(() => nfc.checkP2PRegistration(MANIFEST_URL))
- .then((result) => {
- is(result, true, 'should be true, onpeerready reg, sessionToken set');
- nfc.onpeerready = null;
- return deactivateAndWaitForTechLost().then(() => toggleNFC(false));
- })
- .then(runNextTest)
- .catch(handleRejectedPromiseWithNfcOn);
-}
-
-/**
- * Failure scenario, nfc enabled, activated RE0 (p2p ndef is received,
- * creates session token) opeerready handler not registered.
- */
-function testWithSessionTokenNoTarget() {
- log('testWithSessionTokenNoTarget');
- toggleNFC(true)
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(() => nfc.checkP2PRegistration(MANIFEST_URL))
- .then((result) => {
- is(result, false,
- 'session token avilable but onpeerready not registered');
- return deactivateAndWaitForTechLost().then(() => toggleNFC(false));
- })
- .then(runNextTest)
- .catch(handleRejectedPromiseWithNfcOn);
-}
-
-/**
- * Failure scenario, nfc enabled, re0 activated, onpeerready registered,
- * checking wrong manifest url.
- */
-function testWithSessionTokenWrongTarget() {
- log('testWithSessionTokenWrongTarget');
- toggleNFC(true)
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(registerOnpeerready)
- .then(() => nfc.checkP2PRegistration(FAKE_MANIFEST_URL))
- .then((result) => {
- is(result, false, 'should be false, fake manifest, sessionToken set');
- nfc.onpeerready = null;
- return deactivateAndWaitForTechLost().then(() => toggleNFC(false));
- })
- .then(runNextTest)
- .catch(handleRejectedPromiseWithNfcOn);
-}
-
-function registerOnpeerready() {
- nfc.onpeerready = function() {
- ok(false, 'onpeerready callback cannot be fired');
- };
- let d = Promise.defer();
- d.resolve();
- return d.promise;
-}
-
-function handleRejectedPromise() {
- ok(false, 'Promise rejected. This should not happen');
- nfc.onpeerready = null;
- runNextTest();
-}
-
-function handleRejectedPromiseWithNfcOn() {
- ok(false, 'Promise rejected. This should not happen. Turning off nfc');
- nfc.onpeerready = null;
- toggleNFC(false).then(runNextTest);
-}
-
-var tests = [
- testNoTargetNoSessionToken,
- testWithTargetNoSessionToken,
- testWithSessionTokenWithTarget,
- testWithSessionTokenNoTarget,
- testWithSessionTokenWrongTarget
-];
-
-/**
- * nfc-manager for mozNfc.checkP2PRegistration(manifestUrl)
- * -> "NFC:CheckP2PRegistration" IPC
- * nfc-share to set/unset onpeerready
- * -> "NFC:RegisterPeerTarget", "NFC:UnregisterPeerTarget" IPC
- */
-SpecialPowers.pushPermissions(
- [
- {'type': 'nfc-manager', 'allow': true, context: document},
- {'type': 'nfc-share', 'allow': true, context: document}
- ], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_enabled.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function testEnableNFC() {
- log('Running \'testEnableNFC\'');
- let promise = nfc.startPoll();
- promise.then(() => {
- ok(true);
- runNextTest();
- }).catch(() => {
- ok(false, "startPoll failed");
- runNextTest();
- });
-}
-
-function testDisableNFC() {
- log('Running \'testDisableNFC\'');
- let promise = nfc.powerOff();
- promise.then(() => {
- ok(true);
- runNextTest();
- }).catch(() => {
- ok(false, "powerOff failed");
- runNextTest();
- });
-}
-
-function testStopPollNFC() {
- log('Running \'testStopPollNFC\'');
- let promise = nfc.stopPoll();
- promise.then(() => {
- ok(true);
- runNextTest();
- }).catch(() => {
- ok(false, "stopPoll failed");
- runNextTest();
- });
-}
-
-var tests = [
- testEnableNFC,
- testStopPollNFC,
- testDisableNFC
-];
-
-SpecialPowers.pushPermissions(
- [{'type': 'nfc-manager', 'allow': true, 'context': document}],
- runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_error_messages.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-'use strict';
-
-/* globals log, is, ok, runTests, toggleNFC, runNextTest,
- SpecialPowers, nfc, MozNDEFRecord, emulator */
-
-const MARIONETTE_TIMEOUT = 60000;
-const MARIONETTE_HEAD_JS = 'head.js';
-
-const MANIFEST_URL = 'app://system.gaiamobile.org/manifest.webapp';
-const NDEF_MESSAGE = [new MozNDEFRecord({tnf: "well-known",
- type: new Uint8Array(0x84),
- payload: new Uint8Array(0x20)})];
-
-var nfcPeers = [];
-
-/**
- * Enables nfc and RE0 then registers onpeerready callback and once
- * it's fired it creates mozNFCPeer and stores it for later.
- * After disabling nfc tries to do mozNFCPeer.sendNDEF which should
- * fail with NfcNotEnabledError.
- */
-function testNfcNotEnabledError() {
- log('testNfcNotEnabledError');
- toggleNFC(true)
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(registerAndFireOnpeerready)
- .then(() => deactivateAndWaitForPeerLost())
- .then(() => toggleNFC(false))
- .then(() => sendNDEFExpectError(nfcPeers[0]))
- .then(endTest)
- .catch(handleRejectedPromise);
-}
-
-/**
- * Enables nfc and RE0, register onpeerready callback, once it's fired
- * it creates and stores mozNFCPeer. Disables nfc, enables nfc and
- * once again registers and fires new onpeerready callback and stores
- * mozNfcPeer. Than fires sendNDEF on the first stored peer which
- * should have invalid session token and we should get NfcBadSessionIdError
- */
-function testNfcBadSessionIdError() {
- log('testNfcBadSessionIdError');
- toggleNFC(true)
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(registerAndFireOnpeerready)
- .then(() => NCI.deactivate())
- .then(() => activateAndwaitForTechDiscovered(emulator.P2P_RE_INDEX_0))
- .then(registerAndFireOnpeerready)
- // we have 2 peers in nfcPeers array, peer0 has old/invalid session token
- .then(() => sendNDEFExpectError(nfcPeers[0]))
- .then(() => deactivateAndWaitForPeerLost())
- .then(() => toggleNFC(false))
- .then(endTest)
- .catch(handleRejectedPromise);
-}
-
-/**
- * Enables nfc and RE0, registers tech-discovered msg handler, once it's
- * fired set tech-lost handler and disables nfc. In both handlers checks
- * if error message is not present.
- */
-function testNoErrorInTechMsg() {
- log('testNoErrorInTechMsg');
-
- let techDiscoveredHandler = function(msg) {
- ok('Message handler for nfc-manager-tech-discovered');
- ok(msg.peer, 'check for correct tech type');
- is(msg.errorMsg, undefined, 'Should not get error msg in tech discovered');
-
- setAndFireTechLostHandler()
- .then(() => toggleNFC(false))
- .then(endTest)
- .catch(handleRejectedPromise);
- };
-
- sysMsgHelper.waitForTechDiscovered(techDiscoveredHandler);
-
- toggleNFC(true)
- .then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0))
- .catch(handleRejectedPromise);
-}
-
-function endTest() {
- nfcPeers = [];
- runNextTest();
-}
-
-function handleRejectedPromise() {
- ok(false, 'Handling rejected promise');
- toggleNFC(false).then(endTest);
-}
-
-function registerAndFireOnpeerready() {
- let deferred = Promise.defer();
-
- nfc.onpeerready = function(event) {
- log("onpeerready called");
- nfcPeers.push(event.peer);
- nfc.onpeerready = null;
- deferred.resolve();
- };
-
- nfc.notifyUserAcceptedP2P(MANIFEST_URL);
- return deferred.promise;
-}
-
-function sendNDEFExpectError(peer) {
- let deferred = Promise.defer();
-
- peer.sendNDEF(NDEF_MESSAGE)
- .then(() => {
- deferred.reject();
- }).catch((e) => {
- ok(true, 'this should happen ' + e);
- deferred.resolve();
- });
-
- return deferred.promise;
-}
-
-function setAndFireTechLostHandler() {
- let deferred = Promise.defer();
-
- let techLostHandler = function(msg) {
- ok('Message handler for nfc-manager-tech-lost');
- is(msg.errorMsg, undefined, 'Should not get error msg in tech lost');
-
- deferred.resolve();
- };
-
- sysMsgHelper.waitForTechLost(techLostHandler);
-
- // triggers tech-lost
- NCI.deactivate();
- return deferred.promise;
-}
-
-var tests = [
- testNfcNotEnabledError,
- testNfcBadSessionIdError,
- testNoErrorInTechMsg
-];
-
-/**
- * nfc-manager for mozNfc.checkP2PRegistration(manifestUrl)
- * -> "NFC:CheckP2PRegistration" IPC
- * nfc-share to set/unset onpeerready
- * -> "NFC:RegisterPeerTarget", "NFC:UnregisterPeerTarget" IPC
- */
-SpecialPowers.pushPermissions(
- [
- {'type': 'nfc-manager', 'allow': true, context: document},
- {'type': 'nfc-share', 'allow': true, context: document}
- ], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_manager_tech_discovered.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function handleTechnologyDiscoveredRE0(msg) {
- log('Received \'nfc-manager-tech-discovered\'');
- ok(msg.peer, 'check for correct tech type');
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
-}
-
-function testActivateRE0() {
- log('Running \'testActivateRE0\'');
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-// Check NCI Spec 5.2, this will change NCI state from
-// DISCOVERY -> W4_ALL_DISCOVERIES -> W4_HOST_SELECT -> POLL_ACTIVE
-function testRfDiscover() {
- log('Running \'testRfDiscover\'');
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
-
- toggleNFC(true)
- .then(() => NCI.notifyDiscoverRE(emulator.P2P_RE_INDEX_0, NCI.MORE_NOTIFICATIONS))
- .then(() => NCI.notifyDiscoverRE(emulator.P2P_RE_INDEX_1, NCI.LAST_NOTIFICATION))
- .then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testActivateRE0,
- testRfDiscover
-];
-
-SpecialPowers.pushPermissions(
- [{'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_manager_tech_discovered_ndef.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-var tnf = NDEF.TNF_WELL_KNOWN;
-var type = "U";
-var id = "";
-var payload = "https://www.example.com";
-
-var ndef = null;
-
-function handleSnep(msg) {
- ok(msg.records != null, "msg.records should have values");
- // validate received NDEF message against reference
- let ndef = [new MozNDEFRecord({tnf: tnf,
- type: NfcUtils.fromUTF8(type),
- payload: NfcUtils.fromUTF8(payload)})];
- NDEF.compare(ndef, msg.records);
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
-}
-
-function handleTechnologyDiscoveredRE0(msg) {
- log("Received 'nfc-manager-tech-discovered'");
- ok(msg.peer, "check for correct tech type");
-
- sysMsgHelper.waitForTechDiscovered(handleSnep);
- SNEP.put(SNEP.SAP_NDEF, SNEP.SAP_NDEF, 0, tnf, btoa(type), btoa(id), btoa(payload));
-}
-
-function testReceiveNDEF() {
- log("Running 'testReceiveNDEF'");
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testReceiveNDEF
-];
-
-SpecialPowers.pushPermissions(
- [{'type': 'nfc', 'allow': true,
- 'read': true, 'write': true, context: document},
- {'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_manager_tech_lost.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function handleTechnologyLost(msg) {
- log('Received \'nfc-manager-tech-lost\'');
- ok(true);
-
- toggleNFC(false).then(runNextTest)
-}
-
-function handleTechnologyDiscoveredRE0(msg) {
- log('Received \'nfc-manager-tech-discovered\'');
- ok(msg.peer, 'check for correct tech type');
-
- NCI.deactivate();
-}
-
-function testTechLost() {
- log('Running \'testTechLost\'');
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
- sysMsgHelper.waitForTechLost(handleTechnologyLost);
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testTechLost
-];
-
-SpecialPowers.pushPermissions(
- [{'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_peer.js
+++ /dev/null
@@ -1,187 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-var MANIFEST_URL = "app://system.gaiamobile.org/manifest.webapp";
-var INCORRECT_MANIFEST_URL = "app://xyz.gaiamobile.org/manifest.webapp";
-
-function peerReadyCb(evt) {
- log("peerReadyCb called");
- let peer = evt.peer;
- ok(peer instanceof MozNFCPeer, "Should get a NFCPeer object.");
-
- NCI.deactivate();
-}
-
-function peerLostCb(evt) {
- log("peerLostCb called");
- ok(evt.detail === undefined, "evt.detail should be undefined");
- ok(true);
-
- // reset callback.
- nfc.onpeerready = null;
- nfc.onpeerlost = null;
- toggleNFC(false).then(runNextTest);
-}
-
-function handleTechnologyDiscoveredRE0(msg) {
- log("Received \'nfc-manager-tech-discovered\'");
- ok(msg.peer, "check for correct tech type");
-
- nfc.onpeerready = peerReadyCb;
- nfc.onpeerlost = peerLostCb;
-
- nfc.notifyUserAcceptedP2P(MANIFEST_URL);
-}
-
-function handleTechnologyDiscoveredRE0ForP2PRegFailure(msg) {
- log("Received \'nfc-manager-tech-discovered\'");
- ok(msg.peer, "check for correct tech type");
-
- nfc.onpeerready = peerReadyCb;
-
- nfc.checkP2PRegistration(INCORRECT_MANIFEST_URL)
- .then((result) => {
- is(result, false, "check for P2P registration result");
-
- nfc.onpeerready = null;
- NCI.deactivate().then(() => toggleNFC(false)).then(runNextTest);
- });
-}
-
-function testPeerReady() {
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-function testGetNFCPeer() {
- sysMsgHelper.waitForTechDiscovered(function (msg) {
- ok(msg.peer instanceof MozNFCPeer, "Should get a NFCPeer object.");
-
- NCI.deactivate().then(() => toggleNFC(false)).then(runNextTest);
- });
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-function testCheckP2PRegFailure() {
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0ForP2PRegFailure);
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-/**
- * test for onpeerlost still should be called even onpeerready resets itself.
- */
-function testPeerLostShouldBeCalled() {
- nfc.onpeerready = function() {
- NCI.deactivate();
- nfc.onpeerready = null;
- };
-
- nfc.onpeerlost = function() {
- ok(true, "peerlost should be called even peerready is reset");
- toggleNFC(false).then(runNextTest);
- };
-
- sysMsgHelper.waitForTechDiscovered(function() {
- log("testPeerLostShouldBeCalled techDiscoverd");
- nfc.notifyUserAcceptedP2P(MANIFEST_URL);
- });
-
- toggleNFC(true)
- .then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-/**
- * test case for
- * 1. tech-discovered
- * 2. tech-lost -> onpeerlost shouldn't be called.
- */
-function testPeerLostShouldNotBeCalled() {
- log("testPeerLostShouldNotBeCalled");
- nfc.onpeerlost = function () {
- ok(false, "onpeerlost shouldn't be called");
- };
-
- let isDiscovered = false;
- sysMsgHelper.waitForTechDiscovered(function() {
- log("testPeerLostShouldNotBeCalled techDiscoverd");
- isDiscovered = true;
- NCI.deactivate();
- });
-
- sysMsgHelper.waitForTechLost(function() {
- log("testPeerLostShouldNotBeCalled techLost");
- // if isDiscovered is still false, means this techLost is fired from
- // previous test.
- ok(isDiscovered, "tech-discovered should be fired first");
- nfc.onpeerlost = null;
- toggleNFC(false).then(runNextTest);
- });
-
- toggleNFC(true)
- .then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-function testPeerShouldThrow() {
- log("testPeerShouldThrow");
- let peer;
- let tnf = NDEF.TNF_WELL_KNOWN;
- let type = new Uint8Array(NfcUtils.fromUTF8("U"));
- let payload = new Uint8Array(NfcUtils.fromUTF8("http://www.hi.com"));
- let ndef = [new MozNDEFRecord({tnf: tnf, type: type, payload: payload})];
-
- nfc.onpeerready = function (evt) {
- log("testPeerShouldThrow peerready");
- peer = evt.peer;
- NCI.deactivate();
- };
-
- nfc.onpeerlost = function () {
- log("testPeerShouldThrow peerlost");
- peer.sendNDEF(ndef)
- .then(() => {
- ok(false, "sendNDEF should throw error");
- }).catch((e) => {
- ok(true, "Exception expected " + e);
- });
-
- peer.sendFile(new Blob())
- .then(() => {
- ok(false, "sendfile should throw error");
- }).catch((e) => {
- ok(true, "Exception expected" + e);
- });
-
- nfc.onpeerready = null;
- nfc.onpeerlost = null;
- toggleNFC(false).then(runNextTest);
- };
-
- sysMsgHelper.waitForTechDiscovered(function() {
- log("testPeerShouldThrow techDiscovered");
- nfc.notifyUserAcceptedP2P(MANIFEST_URL);
- });
-
- toggleNFC(true)
- .then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testPeerReady,
- testGetNFCPeer,
- testCheckP2PRegFailure,
- testPeerLostShouldBeCalled,
- testPeerLostShouldNotBeCalled,
- testPeerShouldThrow
-];
-
-SpecialPowers.pushPermissions(
- [{"type": "nfc-manager", "allow": true, context: document},
- {"type": "nfc", "allow": true, context: document},
- {"type": "nfc-share", "allow": true, context: document}], runTests);
-
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_peer_sendFile.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-var MANIFEST_URL = "app://system.gaiamobile.org/manifest.webapp";
-
-function sendFile(msg) {
- log("sendFile msg="+JSON.stringify(msg));
- ok(msg.peer instanceof MozNFCPeer, "should get a MozNFCPeer");
- ok(msg.blob instanceof Blob, "should get a Blob");
-
- nfc.peerready = null;
- NCI.deactivate().then(() => toggleNFC(false)).then(runNextTest);
-}
-
-function testSendFile() {
- nfc.onpeerready = function(evt) {
- let peer = evt.peer;
- peer.sendFile(new Blob());
- sysMsgHelper.waitForSendFile(sendFile);
- };
-
- sysMsgHelper.waitForTechDiscovered(function(msg) {
- nfc.checkP2PRegistration(MANIFEST_URL).then(result => {
- if (result) {
- nfc.notifyUserAcceptedP2P(MANIFEST_URL);
- } else {
- ok(false, "checkP2PRegistration failed.");
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
- }
- });
- });
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testSendFile
-];
-
-SpecialPowers.pushPermissions(
- [{"type": "nfc-share", "allow": true, context: document},
- {"type": "nfc-manager", 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_peer_sendndef.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-var url = "https://www.example.com";
-
-function sendNDEF(peer) {
- let tnf = NDEF.TNF_WELL_KNOWN;
- let type = new Uint8Array(NfcUtils.fromUTF8("U"));
- let payload = new Uint8Array(NfcUtils.fromUTF8(url));
- let ndef = [new MozNDEFRecord({tnf: tnf, type: type, payload: payload})];
-
- let promise = peer.sendNDEF(ndef);
- promise.then(() => {
- log("Successfully sent NDEF message");
-
- let cmd = "nfc snep put -1 -1"; /* read last SNEP PUT from emulator */
- log("Executing \'" + cmd + "\'");
- emulator.run(cmd, function(result) {
- is(result.pop(), "OK", "check SNEP PUT result");
- NDEF.compare(ndef, NDEF.parseString(result.pop()));
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
- });
- }).catch(() => {
- ok(false, "Failed to send NDEF message, error \'" + this.error + "\'");
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
- });
-}
-
-function handleTechnologyDiscoveredRE0(msg) {
- log("Received \'nfc-manager-tech-discovered\' " + JSON.stringify(msg));
- ok(msg.peer, "techDiscovered", "check for correct message type");
- sendNDEF(msg.peer);
-}
-
-function testOnPeerReadyRE0() {
- log("Running \'testOnPeerReadyRE0\'");
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testOnPeerReadyRE0
-];
-
-SpecialPowers.pushPermissions(
- [{"type": "nfc", "allow": true,
- "read": true, 'write': true, context: document},
- {"type": "nfc-manager", 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_read_tag.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-var url = "http://www.mozilla.org";
-
-function testUrlTagDiscover(re) {
- log("Running \'testUrlTagDiscover\'");
- // TODO : Make flag value readable.
- let flag = 0xd0;
- let tnf = NDEF.TNF_WELL_KNOWN;
- let type = "U";
- let payload = url;
-
- sysMsgHelper.waitForTechDiscovered(function(msg) {
- log("Received \'nfc-manager-tech-ndiscovered\'");
- ok(msg.peer === undefined, "peer object should be undefined");
-
- let records = msg.records;
- ok(records.length > 0);
-
- is(tnf, records[0].tnf, "check for TNF field in NDEF");
- is(type, NfcUtils.toUTF8(Cu.waiveXrays(records[0].type)), "check for type field in NDEF");
- is(payload, NfcUtils.toUTF8(Cu.waiveXrays(records[0].payload)), "check for payload field in NDEF");
-
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
- });
-
- toggleNFC(true)
- .then(() => TAG.setData(re, flag, tnf, btoa(type), btoa(payload)))
- .then(() => NCI.activateRE(re));
-}
-
-function testEmptyTagDiscover(re) {
- log("Running \'testEmptyTagDiscover\'");
-
- sysMsgHelper.waitForTechDiscovered(function(msg) {
- log("Received \'nfc-manager-tech-ndiscovered\'");
- ok(msg.peer === undefined, "peer object should be undefined");
-
- let records = msg.records;
- ok(records == null);
-
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
- });
-
- toggleNFC(true)
- .then(() => TAG.clearData(re))
- .then(() => NCI.activateRE(re));
-}
-
-function testUrlT1TDiscover() {
- testUrlTagDiscover(emulator.T1T_RE_INDEX);
-}
-
-function testUrlT2TDiscover() {
- testUrlTagDiscover(emulator.T2T_RE_INDEX);
-}
-
-function testUrlT3TDiscover() {
- testUrlTagDiscover(emulator.T3T_RE_INDEX);
-}
-
-function testUrlT4TDiscover() {
- testUrlTagDiscover(emulator.T4T_RE_INDEX);
-}
-
-function testEmptyT1TDiscover() {
- testEmptyTagDiscover(emulator.T1T_RE_INDEX);
-}
-
-function testEmptyT2TDiscover() {
- testEmptyTagDiscover(emulator.T2T_RE_INDEX);
-}
-
-function testEmptyT3TDiscover() {
- testEmptyTagDiscover(emulator.T3T_RE_INDEX);
-}
-
-function testEmptyT4TDiscover() {
- testEmptyTagDiscover(emulator.T4T_RE_INDEX);
-}
-
-var tests = [
- testUrlT1TDiscover,
- testUrlT2TDiscover,
- testUrlT3TDiscover,
- testUrlT4TDiscover,
- testEmptyT1TDiscover,
- testEmptyT2TDiscover,
- testEmptyT3TDiscover,
- testEmptyT4TDiscover
-];
-
-SpecialPowers.pushPermissions(
- [{'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_tag_found.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function handleTechnologyDiscoveredRE0(msg) {
- log('Received \'nfc-manager-tech-discovered\'');
- ok(msg.peer, 'check for correct tech type');
-
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
-}
-
-function tagFoundCb(evt) {
- log("tagFoundCb called ");
- ok(evt.tag instanceof MozNFCTag, "Should get a NFCTag object.");
-
- nfc.ontagfound = null;
- deactivateAndWaitForTechLost().then(() => toggleNFC(false)).then(runNextTest);
-}
-
-function tagFoundErrorCb(evt) {
- ok(false, "ontagfound shouldn't be called");
-}
-
-function testTagFound() {
- nfc.ontagfound = tagFoundCb;
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.T1T_RE_INDEX));
-}
-
-function testTagFoundShouldNotFired() {
- nfc.ontagfound = tagFoundErrorCb;
- sysMsgHelper.waitForTechDiscovered(handleTechnologyDiscoveredRE0);
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.P2P_RE_INDEX_0));
-}
-
-var tests = [
- testTagFound,
- testTagFoundShouldNotFired
-];
-
-SpecialPowers.pushPermissions(
- [{"type": "nfc", "allow": true, context: document},
- {'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/marionette/test_nfc_tag_lost.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 30000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function tagFoundCb(evt) {
- log("tagFoundCb called ");
- ok(evt.tag instanceof MozNFCTag, "Should get a NFCTag object.");
-
- NCI.deactivate();
-}
-
-function tagLostCb(evt) {
- log("tagLostCb called ");
- ok(true);
-
- nfc.ontagfound = null;
- nfc.ontaglost = null;
- toggleNFC(false).then(runNextTest);
-}
-
-function testTagLost() {
- nfc.ontagfound = tagFoundCb;
- nfc.ontaglost = tagLostCb;
-
- toggleNFC(true).then(() => NCI.activateRE(emulator.T1T_RE_INDEX));
-}
-
-var tests = [
- testTagLost
-];
-
-SpecialPowers.pushPermissions(
- [{"type": "nfc", "allow": true, context: document},
- {'type': 'nfc-manager', 'allow': true, context: document}], runTests);
deleted file mode 100644
--- a/dom/nfc/tests/unit/header_helpers.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-let NFC_CONSTS = {};
-let subscriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader);
-
-Cu.import("resource://gre/modules/nfc_consts.js", NFC_CONSTS);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsISyncMessageSender");
-
-function waitAsyncMessage(msg, callback) {
- let handler = {
- receiveMessage: function (message) {
- if (message.name !== msg) {
- return;
- }
- cpmm.removeMessageListener(msg, handler);
- callback(message);
- }
- };
-
- cpmm.addMessageListener(msg, handler);
-}
-
-function sendAsyncMessage(msg, rsp, payload, callback) {
- waitAsyncMessage(rsp, callback);
- cpmm.sendAsyncMessage(msg, payload);
-}
-
-function sendSyncMessage(msg, payload) {
- return cpmm.sendSyncMessage(msg, payload);
-}
-
deleted file mode 100644
--- a/dom/nfc/tests/unit/test_HCIEventTransactionSystemMessageConfigurator.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const MANIFEST_URL = "app://system.gaiamobile.org/manifest.webapp";
-// secure element access rule format: <secure element name>/<hex string aid>
-const MANIFEST = {
- secure_element_access: [
- // rule0, full AID, SIM1 Secure Element
- "SIM1/000102030405060708090A0B0C0D0E",
- // rule1, every AID from embedded Secure Element
- "eSE/*",
- // rule2, every AID which starts with 0xA0, from every Secure Element
- "*/a0*"
- ]
-};
-const APPID = 1111;
-const PAGE_URL = "app://system.gaiamobile.org/index.html";
-const TYPE = "nfc-hci-event-transaction";
-
-// dummy messages for testing with additional test property - |expectedResult|
-const TEST_MESSAGES = [
- { origin: "SIM1", expectedResult: false },
- { aid: new Uint8Array([0xA0]), expectedResult: true },
- { aid: new Uint8Array([0xDF]), origin: "eSE", expectedResult: true },
- { aid: new Uint8Array([0xA0, 0x01, 0x02, 0x03]), origin: "SIM2", expectedResult: true },
- { aid: new Uint8Array([0x02]), origin: "SIM3", expectedResult: false },
- { aid: new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E]),
- origin: "SIM1", expectedResult: true }
-];
-
-var HCIEvtTransactionConfigurator = null;
-var aceAccessAllowed = true;
-
-function setMockServices(manifest) {
- XPCOMUtils.defineLazyServiceGetter = (obj, service) => {
- if (service === "appsService") {
- obj.appsService = {
- getManifestFor: (manifestURL) => {
- equal(manifestURL, MANIFEST_URL, "should pass proper manifestUrl");
- return Promise.resolve(manifest);
- },
- getAppLocalIdByManifestURL: (manifestURL) => {
- equal(manifestURL, MANIFEST_URL, "should pass proper manifestUrl");
- return APPID;
- },
- };
- }
- else if (service === "aceService") {
- obj.aceService = {
- isAccessAllowed: () => {
- return Promise.resolve(aceAccessAllowed);
- }
- };
- }
- };
-}
-
-function getSystemMessageConfigurator() {
- return Cc[
- "@mozilla.org/dom/system-messages/configurator/nfc-hci-event-transaction;1"
- ].createInstance(Ci.nsISystemMessagesConfigurator);
-}
-
-function handleRejectedPromise() {
- ok(false, "Promise should not be rejected");
-}
-
-function run_test() {
- setMockServices(MANIFEST);
- HCIEvtTransactionConfigurator = getSystemMessageConfigurator();
-
- ok(!!HCIEvtTransactionConfigurator, "Configurator should be instantiated");
- ok((typeof HCIEvtTransactionConfigurator.shouldDispatch) === "function",
- "shouldDispatch should be a function");
-
- run_next_test();
-}
-
-add_test(function test_shouldDispatch_no_message() {
- HCIEvtTransactionConfigurator
- .shouldDispatch(MANIFEST_URL, PAGE_URL, TYPE, null)
- .then((result) => {
- ok(!result, "Should be false without message");
- })
- .catch(handleRejectedPromise)
- .then(run_next_test);
-});
-
-add_test(function test_shouldDispatch_general_rule_validation() {
- let promises = TEST_MESSAGES.map((m) => {
- return HCIEvtTransactionConfigurator
- .shouldDispatch(MANIFEST_URL, PAGE_URL, TYPE, m);
- });
-
- Promise.all(promises).then((results) => {
- results.forEach((result, idx) => {
- ok(result === TEST_MESSAGES[idx].expectedResult, "tested message: " + JSON.stringify(TEST_MESSAGES[idx]));
- });
- })
- .catch(handleRejectedPromise)
- .then(run_next_test);
-});
-
-add_test(function test_shouldDispatch_aceIsAccessAllowed() {
- var testAccessAllowed = () => {
- return HCIEvtTransactionConfigurator
- .shouldDispatch(MANIFEST_URL, PAGE_URL, TYPE, TEST_MESSAGES[1])
- .then((result) => {
- ok(result === aceAccessAllowed, "Should be equal to ACE access decision");
- });
- };
-
- aceAccessAllowed = false;
- testAccessAllowed().then(() => {
- aceAccessAllowed = true;
- return testAccessAllowed();
- })
- .catch(handleRejectedPromise)
- .then(run_next_test);
-});
deleted file mode 100644
--- a/dom/nfc/tests/unit/test_Nfc.js
+++ /dev/null
@@ -1,479 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-let NFC = {};
-subscriptLoader.loadSubScript("resource://gre/components/Nfc.js", NFC);
-
-// Mock nfc service
-// loadSubScript could not load const and let variables, type defined
-// here should be consistent with type defined in Nfc.js
-const MockReqType = {
- CHANGE_RF_STATE: "changeRFState",
- READ_NDEF: "readNDEF",
- WRITE_NDEF: "writeNDEF",
- MAKE_READ_ONLY: "makeReadOnly",
- FORMAT: "format",
- TRANSCEIVE: "transceive"
-};
-
-const MockRspType = {};
-MockRspType[MockReqType.CHANGE_RF_STATE] = "changeRFStateRsp";
-MockRspType[MockReqType.READ_NDEF] = "readNDEFRsp";
-MockRspType[MockReqType.WRITE_NDEF] = "writeNDEFRsp";
-MockRspType[MockReqType.MAKE_READ_ONLY] = "makeReadOnlyRsp";
-MockRspType[MockReqType.FORMAT] = "formatRsp";
-MockRspType[MockReqType.TRANSCEIVE] = "transceiveRsp";
-
-const MockNtfType = {
- INITIALIZED: "initialized",
- TECH_DISCOVERED: "techDiscovered",
- TECH_LOST: "techLost",
-};
-
-const MOCK_RECORDS = {"payload":{"0":4,"1":119,"2":119,
- "3":119,"4":46,"5":109,
- "6":111,"7":122,"8":105},
- "tnf":"well-known",
- "type":{"0":85}};
-
-let MockNfcService = {
- listener: null,
-
- setListener: function (listener) {
- this.listener = listener;
- },
-
- notifyEvent: function (event) {
- if (this.listener && this.listener.onEvent) {
- this.listener.onEvent(event);
- }
- },
-
- start: function (eventListener) {
- this.setListener(eventListener);
- },
-
- shutdown: function () {
- this.listener = null;
- },
-
- sendCommand: function (message) {
- switch (message.type) {
- case MockReqType.CHANGE_RF_STATE:
- this.notifyEvent({ errorMsg: "",
- requestId: message.requestId,
- rfState: message.rfState,
- rspType: MockRspType[message.type] });
- break;
- case MockReqType.READ_NDEF:
- this.notifyEvent({ errorMsg: "",
- requestId: message.requestId,
- records: MOCK_RECORDS,
- sessionId: message.sessionId,
- rspType: MockRspType[message.type] });
- break;
- case MockReqType.WRITE_NDEF:
- case MockReqType.MAKE_READ_ONLY:
- case MockReqType.TRANSCEIVE:
- case MockReqType.FORMAT:
- this.notifyEvent({ errorMsg: "",
- requestId: message.requestId,
- sessionId: message.sessionId,
- rspType: MockRspType[message.type] });
- break;
- default:
- throw new Error("Don't know about this message type: " + message.type);
- }
- }
-};
-// end of nfc service mock.
-
-let messageManager = NFC.gMessageManager;
-let sessionHelper = NFC.SessionHelper;
-
-new NFC.Nfc(/* isXPCShell */ true);
-
-// It would better to use MockRegistrar but nsINfcService contains
-// method marked with implicit_context which may not be implemented in js.
-// Use a simple assignment to mock nfcService
-
-MockNfcService.start(messageManager.nfc);
-messageManager.nfc.nfcService = MockNfcService;
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_setFocusTab() {
- let tabId = 1;
- let rsp = "NFC:DOMEvent";
- let focusOnCb = function (message) {
- let result = message.data;
-
- deepEqual(result,
- { tabId: tabId,
- event: NFC_CONSTS.FOCUS_CHANGED,
- focus: true },
- "Correct result SetFocusTab On");
-
- let focusOffCb = function (msg) {
- let result = msg.data;
-
- deepEqual(result,
- { tabId: tabId,
- event: NFC_CONSTS.FOCUS_CHANGED,
- focus: false },
- "Correct result SetFocusTab Off");
-
- equal(messageManager.focusId, NFC_CONSTS.SYSTEM_APP_ID);
-
- sendSyncMessage("NFC:RemoveEventListener", { tabId: tabId });
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:SetFocusTab", rsp, { tabId: tabId, isFocus: false },
- focusOffCb);
- };
-
- sendSyncMessage("NFC:AddEventListener", { tabId: tabId });
- sendAsyncMessage("NFC:SetFocusTab", rsp, { tabId: tabId, isFocus: true },
- focusOnCb);
-});
-
-add_test(function test_checkP2PRegistrationSucceed() {
- let appId = 1;
- let requestId = 10;
- let rsp = "NFC:CheckP2PRegistrationResponse";
- let sessionId = 1;
- let isP2P = true;
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.errorMsg, undefined);
-
- sendSyncMessage("NFC:UnregisterPeerReadyTarget", { appId: appId });
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sessionHelper.registerSession(sessionId, isP2P);
- sendSyncMessage("NFC:RegisterPeerReadyTarget", { appId: appId });
- sendAsyncMessage("NFC:CheckP2PRegistration",
- rsp,
- { appId: appId,
- requestId: requestId },
- callback);
-});
-
-add_test(function test_checkP2PRegistrationFailed() {
- let appId = 1;
- let requestId = 10;
- let rsp = "NFC:CheckP2PRegistrationResponse";
- let errorMsg =
- NFC_CONSTS.NFC_ERROR_MSG[NFC_CONSTS.NFC_GECKO_ERROR_P2P_REG_INVALID];
- let callback = function (message) {
- let result = message.data;
-
- deepEqual(result,
- { requestId: requestId,
- errorMsg: errorMsg },
- "Correct result checkP2PRegistrationFailed");
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:CheckP2PRegistration",
- rsp,
- { appId: 10,
- requestId: requestId },
- callback);
-});
-
-add_test(function test_notifyUserAcceptedP2P() {
- let appId = 1;
- let requestId = 10;
- let rsp = "NFC:DOMEvent";
- let sessionId = 1;
- let isP2P = true;
- let callback = function (message) {
- let result = message.data;
-
- ok(true, "received CheckP2PRegistrationResponse")
-
- sendSyncMessage("NFC:UnregisterPeerReadyTarget", { appId: appId });
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sessionHelper.registerSession(sessionId, isP2P);
- sendSyncMessage("NFC:RegisterPeerReadyTarget", { appId: appId });
- sendAsyncMessage("NFC:NotifyUserAcceptedP2P", rsp, { appId: appId },
- callback);
-});
-
-add_test(function test_changeRFState() {
- let tabId = 1;
- let requestId = 10;
- let msg = "NFC:DOMEvent";
- let rfState = NFC_CONSTS.NFC_RF_STATE_LISTEN;
- let callback = function (message) {
- let result = message.data;
-
- deepEqual(result,
- { tabId: tabId,
- event: NFC_CONSTS.RF_EVENT_STATE_CHANGED,
- rfState: rfState },
- "Correct result onRFStateChanged");
-
- sendSyncMessage("NFC:RemoveEventListener", { tabId: tabId });
-
- run_next_test();
- };
-
- sendSyncMessage("NFC:AddEventListener", { tabId: tabId });
- sendAsyncMessage("NFC:ChangeRFState",
- msg,
- { requestId: requestId,
- rfState: rfState },
- callback);
-});
-
-add_test(function test_queryRFState() {
- equal(sendSyncMessage("NFC:QueryInfo")[0].rfState, NFC_CONSTS.NFC_RF_STATE_LISTEN);
- run_next_test();
-});
-
-add_test(function test_onTagFound() {
- let tabId = 1;
- let msg = "NFC:DOMEvent";
- let sessionId = 10;
- let setFocusCb = function (focusMsg) {
- let callback = function (message) {
- let result = message.data;
-
- equal(result.tabId, tabId);
- equal(result.event, NFC_CONSTS.TAG_EVENT_FOUND);
-
- run_next_test();
- };
-
- waitAsyncMessage(msg, callback);
- MockNfcService.notifyEvent({ ntfType: MockNtfType.TECH_DISCOVERED,
- sessionId: sessionId,
- isP2P: false });
- };
-
- sendSyncMessage("NFC:AddEventListener", { tabId: tabId });
- sendAsyncMessage("NFC:SetFocusTab",
- msg,
- { tabId: tabId,
- isFocus: true },
- setFocusCb);
-});
-
-add_test(function test_onTagLost() {
- let tabId = 1;
- let msg = "NFC:DOMEvent";
- let sessionId = 10;
- let callback = function (message) {
- let result = message.data;
-
- equal(result.tabId, tabId);
- equal(result.event, NFC_CONSTS.TAG_EVENT_LOST);
-
- sendSyncMessage("NFC:RemoveEventListener", { tabId: tabId });
- sessionHelper.tokenMap = {};
- sendSyncMessage("NFC:SetFocusTab",
- { tabId: tabId,
- isFocus: false });
-
- run_next_test();
- };
-
- waitAsyncMessage(msg, callback);
- MockNfcService.notifyEvent({ ntfType: MockNtfType.TECH_LOST,
- sessionId: sessionId,
- isP2P: false });
-});
-
-add_test(function test_onPeerFound() {
- let tabId = 1;
- let msg = "NFC:DOMEvent";
- let sessionId = 10;
- let setFocusCb = function (focusMsg) {
- let callback = function (message) {
- let result = message.data;
-
- equal(result.tabId, tabId);
- equal(result.event, NFC_CONSTS.PEER_EVENT_FOUND);
-
- run_next_test();
- };
-
- waitAsyncMessage(msg, callback);
- MockNfcService.notifyEvent({ ntfType: MockNtfType.TECH_DISCOVERED,
- sessionId: sessionId,
- isP2P: true });
- };
-
- sendSyncMessage("NFC:AddEventListener", { tabId: tabId });
- sendAsyncMessage("NFC:SetFocusTab",
- msg,
- { tabId: tabId,
- isFocus: true },
- setFocusCb);
-
-});
-
-add_test(function test_onPeerLost() {
- let tabId = 1;
- let msg = "NFC:DOMEvent";
- let sessionId = 10;
- let callback = function (message) {
- let result = message.data;
-
- equal(result.tabId, tabId);
- equal(result.event, NFC_CONSTS.PEER_EVENT_LOST);
-
- sendSyncMessage("NFC:RemoveEventListener", { tabId: tabId });
- sessionHelper.tokenMap = {};
- sendSyncMessage("NFC:SetFocusTab",
- { tabId: tabId,
- isFocus: false });
-
- run_next_test();
- };
-
- waitAsyncMessage(msg, callback);
- MockNfcService.notifyEvent({ ntfType: MockNtfType.TECH_LOST,
- sessionId: sessionId,
- isP2P: true });
-
-});
-
-add_test(function test_readNDEF() {
- let requestId = 10;
- let sessionId = 15;
- let msg = "NFC:ReadNDEFResponse";
- let sessionToken = sessionHelper.registerSession(sessionId, false);
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.sessionId, sessionId);
- deepEqual(result.records, MOCK_RECORDS);
-
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:ReadNDEF",
- msg,
- { requestId: requestId,
- sessionToken: sessionToken },
- callback);
-});
-
-add_test(function test_writeNDEF() {
- let requestId = 10;
- let sessionId = 15;
- let msg = "NFC:WriteNDEFResponse";
- let sessionToken = sessionHelper.registerSession(sessionId, false);
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.sessionId, sessionId);
-
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:WriteNDEF",
- msg,
- { requestId: requestId,
- sessionToken: sessionToken,
- records: MOCK_RECORDS,
- isP2P: true },
- callback);
-});
-
-add_test(function test_format() {
- let requestId = 10;
- let sessionId = 15;
- let msg = "NFC:FormatResponse";
- let sessionToken = sessionHelper.registerSession(sessionId, false);
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.sessionId, sessionId);
-
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:Format",
- msg,
- { requestId: requestId,
- sessionToken: sessionToken },
- callback);
-});
-
-add_test(function test_makeReadOnly() {
- let requestId = 10;
- let sessionId = 15;
- let msg = "NFC:MakeReadOnlyResponse";
- let sessionToken = sessionHelper.registerSession(sessionId, false);
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.sessionId, sessionId);
-
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:MakeReadOnly",
- msg,
- { requestId: requestId,
- sessionToken: sessionToken },
- callback);
-});
-
-
-add_test(function test_transceive() {
- let requestId = 10;
- let sessionId = 15;
- let msg = "NFC:TransceiveResponse";
- let sessionToken = sessionHelper.registerSession(sessionId, false);
- let callback = function (message) {
- let result = message.data;
-
- equal(result.requestId, requestId);
- equal(result.sessionId, sessionId);
-
- sessionHelper.tokenMap = {};
-
- run_next_test();
- };
-
- sendAsyncMessage("NFC:Transceive",
- msg,
- { requestId: requestId,
- sessionToken: sessionToken,
- technology: "NFCA",
- command: "0x50" },
- callback);
-});
deleted file mode 100644
--- a/dom/nfc/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-head = header_helpers.js
-tail =
-
-[test_HCIEventTransactionSystemMessageConfigurator.js]
-[test_Nfc.js]
--- a/dom/webidl/BrowserElement.webidl
+++ b/dom/webidl/BrowserElement.webidl
@@ -147,21 +147,16 @@ interface BrowserElementPrivileged {
[Throws,
Pref="dom.mozBrowserFramesEnabled",
ChromeOnly]
DOMRequest setInputMethodActive(boolean isActive);
[Throws,
Pref="dom.mozBrowserFramesEnabled",
ChromeOnly]
- void setNFCFocus(boolean isFocus);
-
- [Throws,
- Pref="dom.mozBrowserFramesEnabled",
- ChromeOnly]
void findAll(DOMString searchString, BrowserFindCaseSensitivity caseSensitivity);
[Throws,
Pref="dom.mozBrowserFramesEnabled",
ChromeOnly]
void findNext(BrowserFindDirection direction);
[Throws,
deleted file mode 100644
--- a/dom/webidl/MozIsoDepTech.webidl
+++ /dev/null
@@ -1,13 +0,0 @@
-/* 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/. */
-
-[Func="Navigator::HasNFCSupport", ChromeOnly,
- ChromeConstructor(MozNFCTag tag)]
-interface MozIsoDepTech {
- /**
- * Send raw ISO-DEP command to tag and receive the response.
- */
- [Throws]
- Promise<Uint8Array> transceive(Uint8Array command);
-};
deleted file mode 100644
--- a/dom/webidl/MozNDEFRecord.webidl
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* 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/. */
-
-/* Copyright © 2013 Deutsche Telekom, Inc. */
-
-/**
- * Type Name Format.
- *
- * @see NFCForum-TS-NDEF 3.2.6 TNF
- */
-enum TNF {
- "empty",
- "well-known",
- "media-type",
- "absolute-uri",
- "external",
- "unknown",
- "unchanged"
-};
-
-/**
- * Prefixes of well-known URI.
- *
- * @see NFCForum-TS-RTD_URI Table 3. Abbreviation Table.
- */
-enum WellKnownURIPrefix {
- "",
- "http://www.",
- "https://www.",
- "http://",
- "https://",
- "tel:",
- "mailto:",
- "ftp://anonymous:anonymous@",
- "ftp://ftp.",
- "ftps://",
- "sftp://",
- "smb://",
- "nfs://",
- "ftp://",
- "dav://",
- "news:",
- "telnet://",
- "imap:",
- "rtsp://",
- "urn:",
- "pop:",
- "sip:",
- "sips:",
- "tftp:",
- "btspp://",
- "btl2cap://",
- "btgoep://",
- "tcpobex://",
- "irdaobex://",
- "file://",
- "urn:epc:id:",
- "urn:epc:tag:",
- "urn:epc:pat:",
- "urn:epc:raw:",
- "urn:epc:",
- "urn:nfc:"
-};
-
-/**
- * Record Type Description.
- *
- * Record Types from well-known NDEF Records.
- * @see NFCForum-TS-RTD
- */
-enum RTD {
- "U", // URI
-};
-
-[Constructor(optional MozNDEFRecordOptions options),
- Constructor(DOMString uri)]
-interface MozNDEFRecord
-{
- /**
- * Type Name Field - Specifies the NDEF record type in general.
- */
- [Constant]
- readonly attribute TNF tnf;
-
- /**
- * type - Describes the content of the payload. This can be a mime type.
- */
- [Constant]
- readonly attribute Uint8Array? type;
-
- /**
- * id - Identifer is application dependent.
- */
- [Constant]
- readonly attribute Uint8Array? id;
-
- /**
- * payload - Binary data blob. The meaning of this field is application
- * dependent.
- */
- [Constant]
- readonly attribute Uint8Array? payload;
-
- /**
- * Get the size of this NDEF Record.
- */
- [Constant]
- readonly attribute unsigned long size;
-
- /**
- * Returns this NDEF Record as URI, return null if this record cannot be
- * decoded as a well-known URI record.
- */
- DOMString? getAsURI();
-};
-
-dictionary MozNDEFRecordOptions {
- TNF tnf = "empty";
- Uint8Array? type;
- Uint8Array? id;
- Uint8Array? payload;
-};
deleted file mode 100644
--- a/dom/webidl/MozNFC.webidl
+++ /dev/null
@@ -1,138 +0,0 @@
-/* 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/. */
-
- /* Copyright © 2013 Deutsche Telekom, Inc. */
-
-enum NfcErrorMessage {
- "",
- "IOError",
- "Timeout",
- "Busy",
- "ErrorConnect",
- "ErrorDisconnect",
- "ErrorRead",
- "ErrorWrite",
- "InvalidParameter",
- "InsufficientResource",
- "ErrorSocketCreation",
- "FailEnableDiscovery",
- "FailDisableDiscovery",
- "NotInitialize",
- "InitializeFail",
- "DeinitializeFail",
- "NotSupport",
- "FailEnableLowPowerMode",
- "FailDisableLowPowerMode"
-};
-
-[NoInterfaceObject]
-interface MozNFCManager {
- /**
- * API to check if the given application's manifest
- * URL is registered with the Chrome Process or not.
- *
- * Returns success if given manifestUrl is registered for 'onpeerready',
- * otherwise error
- */
- [ChromeOnly]
- Promise<boolean> checkP2PRegistration(DOMString manifestUrl);
-
- /**
- * Notify that user has accepted to share nfc message on P2P UI
- */
- [ChromeOnly]
- void notifyUserAcceptedP2P(DOMString manifestUrl);
-
- /**
- * Notify the status of sendFile operation
- */
- [ChromeOnly]
- void notifySendFileStatus(octet status, DOMString requestId);
-
- /**
- * Power on the NFC hardware and start polling for NFC tags or devices.
- */
- [ChromeOnly]
- Promise<void> startPoll();
-
- /**
- * Stop polling for NFC tags or devices. i.e. enter low power mode.
- */
- [ChromeOnly]
- Promise<void> stopPoll();
-
- /**
- * Power off the NFC hardware.
- */
- [ChromeOnly]
- Promise<void> powerOff();
-};
-
-[JSImplementation="@mozilla.org/nfc/manager;1",
- NavigatorProperty="mozNfc",
- Func="Navigator::HasNFCSupport",
- ChromeOnly,
- UnsafeInPrerendering]
-interface MozNFC : EventTarget {
- /**
- * Indicate if NFC is enabled.
- */
- readonly attribute boolean enabled;
-
- /**
- * This event will be fired when another NFCPeer is detected, and user confirms
- * to share data to the NFCPeer object by calling mozNFC.notifyUserAcceptedP2P.
- * The event will be type of NFCPeerEvent.
- */
- attribute EventHandler onpeerready;
-
- /**
- * This event will be fired when a NFCPeer is detected. The application has to
- * be running on the foreground (decided by System app) to receive this event.
- *
- * The default action of this event is to dispatch the event in System app
- * again, and System app will run the default UX behavior (like vibration).
- * So if the application would like to cancel the event, the application
- * should call event.preventDefault() or return false in this event handler.
- */
- attribute EventHandler onpeerfound;
-
- /**
- * This event will be fired when NFCPeer, earlier detected in onpeerready
- * or onpeerfound, moves out of range, or if the application has been switched
- * to the background (decided by System app).
- */
- attribute EventHandler onpeerlost;
-
- /**
- * This event will be fired when a NFCTag is detected. The application has to
- * be running on the foreground (decided by System app) to receive this event.
- *
- * The default action of this event is to dispatch the event in System app
- * again, and System app will run the default UX behavior (like vibration) and
- * launch MozActivity to handle the content of the tag. (For example, System
- * app will launch Browser if the tag contains URL). So if the application
- * would like to cancel the event, i.e. in the above example, the application
- * would process the URL by itself without launching Browser, the application
- * should call event.preventDefault() or return false in this event handler.
- */
- attribute EventHandler ontagfound;
-
- /**
- * This event will be fired if the tag detected in ontagfound has been
- * removed, or if the application has been switched to the background (decided
- * by System app).
- */
- attribute EventHandler ontaglost;
-};
-
-// Mozilla Only
-partial interface MozNFC {
- [ChromeOnly]
- void eventListenerWasAdded(DOMString aType);
- [ChromeOnly]
- void eventListenerWasRemoved(DOMString aType);
-};
-
-MozNFC implements MozNFCManager;
deleted file mode 100644
--- a/dom/webidl/MozNFCPeer.webidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/.
- *
- * Part of this IDL file is from:
- * http://w3c.github.io/nfc/proposals/common/nfc.html#idl-def-NFCPeer
- *
- * Copyright © 2013 Deutsche Telekom, Inc.
- */
-
-[JSImplementation="@mozilla.org/nfc/peer;1", ChromeOnly]
-interface MozNFCPeer {
- /**
- * Indicate if this peer is already lost.
- */
- readonly attribute boolean isLost;
-
- /**
- * Send NDEF data to peer device.
- */
- [Throws]
- Promise<void> sendNDEF(sequence<MozNDEFRecord> records);
-
- /**
- * Send file to peer device.
- */
- [Throws]
- Promise<void> sendFile(Blob blob);
-};
-
-// Mozilla Only
-partial interface MozNFCPeer {
- [ChromeOnly]
- attribute DOMString session;
-
- [ChromeOnly]
- void notifyLost();
-};
deleted file mode 100644
--- a/dom/webidl/MozNFCPeerEvent.webidl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* 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/.
- */
-
-[Constructor(DOMString type, optional MozNFCPeerEventInit eventInitDict),
- Func="Navigator::HasNFCSupport", ChromeOnly]
-interface MozNFCPeerEvent : Event
-{
- /**
- * The detected NFCPeer.
- */
- readonly attribute MozNFCPeer? peer;
-};
-
-dictionary MozNFCPeerEventInit : EventInit
-{
- MozNFCPeer? peer = null;
-};
deleted file mode 100644
--- a/dom/webidl/MozNFCTag.webidl
+++ /dev/null
@@ -1,121 +0,0 @@
-/* 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/.
- *
- * Part of this idl is from:
- * http://w3c.github.io/nfc/proposals/common/nfc.html#nfctag-interface
- *
- * Copyright © 2013 Deutsche Telekom, Inc.
- */
-
-/**
- * The enumeration of NFC Tag technologies.
- */
-enum NFCTechType {
- "NFC-A", // NFCForum-TS-DigitalProtocol-1.1 NFC-A.
- "NFC-B", // NFCForum-TS-DigitalProtocol-1.1 NFC-B.
- "NFC-F", // NFCForum-TS-DigitalProtocol-1.1 NFC-F.
- "NFC-V", // ISO 15693.
- "ISO-DEP", // NFCForum-TS-DigitalProtocol-1.1 ISO-DEP.
- "MIFARE-Classic", // MIFARE Classic from NXP.
- "MIFARE-Ultralight", // MIFARE Ultralight from NXP.
- "NFC-Barcode", // NFC Barcode from Kovio.
- "Unknown"
-};
-
-/**
- * The enumeration of the types of the tag, the type of a tag could be either
- * one of those types defined in NFC Forum Tag Types (Type1 ~ Type 4), or it
- * could be a NXP-specific tag, like MIFARE Classic.
- */
-enum NFCTagType {
- "Type1",
- "Type2",
- "Type3",
- "Type4",
- "MIFARE-Classic"
-};
-
-typedef (MozIsoDepTech or MozNfcATech) MozTagTech;
-
-[JSImplementation="@mozilla.org/nfc/tag;1", ChromeOnly]
-interface MozNFCTag {
- /**
- * The supported technologies of this tag, null if unknown.
- */
- [Cached, Pure] readonly attribute sequence<NFCTechType>? techList;
-
- /**
- * The identifier of this tag.
- */
- [Constant] readonly attribute Uint8Array? id;
-
- /**
- * The type of this tag, null if unknown.
- */
- readonly attribute NFCTagType? type;
-
- /**
- * The maximum size of the NDEF supported on this tag, null if unknown.
- */
- readonly attribute long? maxNDEFSize;
-
- /**
- * Indicate if this tag is Read-Only, null if unknown.
- */
- readonly attribute boolean? isReadOnly;
-
- /**
- * Indicate if this tag is formatable, null if unknown.
- */
- readonly attribute boolean? isFormatable;
-
- /**
- * Indicate if this tag could be made Read-Only, null if unknown.
- */
- readonly attribute boolean? canBeMadeReadOnly;
-
- /**
- * Indicate if this tag is already lost.
- */
- readonly attribute boolean isLost;
-
- /**
- * Read current NDEF data on the tag.
- */
- [Throws]
- Promise<sequence<MozNDEFRecord>> readNDEF();
-
- /**
- * Write NDEF data to the tag.
- */
- [Throws]
- Promise<void> writeNDEF(sequence<MozNDEFRecord> records);
-
- /**
- * Make a tag read-only.
- */
- [Throws]
- Promise<void> makeReadOnly();
-
- /**
- * Format a tag as NDEF.
- */
- [Throws]
- Promise<void> format();
-
- [NewObject, Throws]
- MozTagTech selectTech(NFCTechType tech);
-};
-
-// Mozilla Only
-partial interface MozNFCTag {
- [ChromeOnly]
- attribute DOMString session;
-
- [ChromeOnly]
- void notifyLost();
-
- [ChromeOnly, Throws]
- Promise<Uint8Array> transceive(NFCTechType tech, Uint8Array command);
-};
deleted file mode 100644
--- a/dom/webidl/MozNFCTagEvent.webidl
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* 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/.
- */
-
-[Constructor(DOMString type, optional MozNFCTagEventInit eventInitDict),
- Func="Navigator::HasNFCSupport", ChromeOnly]
-interface MozNFCTagEvent : Event
-{
- /**
- * The detected NFCTag.
- */
- readonly attribute MozNFCTag? tag;
-
- /**
- * The MozNDEFRecords pre-read during tag-discovered.
- */
- [Cached, Pure]
- readonly attribute sequence<MozNDEFRecord>? ndefRecords;
-};
-
-dictionary MozNFCTagEventInit : EventInit
-{
- MozNFCTag? tag = null;
-
- sequence<MozNDEFRecord>? ndefRecords = [];
-};
deleted file mode 100644
--- a/dom/webidl/MozNfcATech.webidl
+++ /dev/null
@@ -1,13 +0,0 @@
-/* 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/. */
-
-[Func="Navigator::HasNFCSupport", ChromeOnly,
- ChromeConstructor(MozNFCTag tag)]
-interface MozNfcATech {
- /**
- * Send raw NFC-A command to tag and receive the response.
- */
- [Throws]
- Promise<Uint8Array> transceive(Uint8Array command);
-};
deleted file mode 100644
--- a/dom/webidl/NfcOptions.webidl
+++ /dev/null
@@ -1,105 +0,0 @@
-/* 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/. */
-
-enum RFState {
- "idle",
- "listen",
- "discovery"
-};
-
-/**
- * Type of the Request used in NfcCommandOptions.
- */
-enum NfcRequestType {
- "changeRFState",
- "readNDEF",
- "writeNDEF",
- "makeReadOnly",
- "format",
- "transceive"
-};
-
-/**
- * Type of the Response used in NfcEventOptions.
- */
-enum NfcResponseType {
- "changeRFStateRsp",
- "readNDEFRsp",
- "writeNDEFRsp",
- "makeReadOnlyRsp",
- "formatRsp",
- "transceiveRsp",
-};
-
-/**
- * Type of the Notification used in NfcEventOptions.
- */
-enum NfcNotificationType {
- "initialized",
- "techDiscovered",
- "techLost",
- "hciEventTransaction",
- "ndefReceived",
-};
-
-/**
- * The source of HCI Transaction Event.
- */
-enum HCIEventOrigin {
- "SIM",
- "eSE",
- "ASSD"
-};
-
-dictionary NfcCommandOptions
-{
- required NfcRequestType type;
-
- long sessionId;
- required DOMString requestId;
-
- RFState rfState;
-
- long techType;
-
- boolean isP2P;
- sequence<MozNDEFRecordOptions> records;
-
- NFCTechType technology;
- Uint8Array command;
-};
-
-dictionary NfcEventOptions
-{
- NfcResponseType rspType;
- NfcNotificationType ntfType;
-
- long status;
- NfcErrorMessage errorMsg;
- long sessionId;
- DOMString requestId;
-
- long majorVersion;
- long minorVersion;
-
- boolean isP2P;
- sequence<NFCTechType> techList;
- Uint8Array tagId;
- sequence<MozNDEFRecordOptions> records;
-
- NFCTagType tagType;
- long maxNDEFSize;
- boolean isReadOnly;
- boolean isFormatable;
-
- RFState rfState;
-
- // HCI Event Transaction fields
- DOMString origin;
- Uint8Array aid;
- Uint8Array payload;
-
- // Tag transceive response data
- Uint8Array response;
-};
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -711,27 +711,16 @@ if CONFIG['MOZ_B2G_BT']:
'BluetoothObexAuthHandle.webidl',
'BluetoothPairingHandle.webidl',
'BluetoothPairingListener.webidl',
'BluetoothPbapParameters.webidl',
'BluetoothPbapRequestHandle.webidl',
'BluetoothUUID.webidl',
]
-if CONFIG['MOZ_NFC']:
- WEBIDL_FILES += [
- 'MozIsoDepTech.webidl',
- 'MozNDEFRecord.webidl',
- 'MozNFC.webidl',
- 'MozNfcATech.webidl',
- 'MozNFCPeer.webidl',
- 'MozNFCTag.webidl',
- 'NfcOptions.webidl',
- ]
-
if CONFIG['MOZ_SECUREELEMENT']:
WEBIDL_FILES += [
'SecureElement.webidl',
'SecureElementManager.webidl',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
WEBIDL_FILES += [
@@ -850,22 +839,16 @@ if CONFIG['MOZ_B2G_BT']:
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
GENERATED_EVENTS_WEBIDL_FILES += [
'MozWifiConnectionInfoEvent.webidl',
'MozWifiP2pStatusChangeEvent.webidl',
'MozWifiStationInfoEvent.webidl',
'MozWifiStatusChangeEvent.webidl',
]
-if CONFIG['MOZ_NFC']:
- GENERATED_EVENTS_WEBIDL_FILES += [
- 'MozNFCPeerEvent.webidl',
- 'MozNFCTagEvent.webidl',
- ]
-
if CONFIG['MOZ_BUILD_APP'] in ['browser', 'xulrunner'] or CONFIG['MOZ_SUITE']:
WEBIDL_FILES += [
'BrowserFeedWriter.webidl',
]
if CONFIG['MOZ_BUILD_APP'] in ['browser', 'mobile/android', 'xulrunner']:
WEBIDL_FILES += [
'External.webidl',
--- a/ipc/moz.build
+++ b/ipc/moz.build
@@ -12,20 +12,17 @@ DIRS += [
]
if CONFIG['MOZ_B2G_RIL']:
DIRS += ['ril']
if CONFIG['MOZ_ENABLE_DBUS'] or CONFIG['MOZ_B2G_BT_BLUEZ']:
DIRS += ['dbus']
-if CONFIG['MOZ_NFC']:
- DIRS += ['nfc']
-
-if CONFIG['MOZ_B2G_RIL'] or CONFIG['MOZ_B2G_BT'] or CONFIG['MOZ_NFC'] or CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
+if CONFIG['MOZ_B2G_RIL'] or CONFIG['MOZ_B2G_BT'] or CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
DIRS += ['unixfd', 'unixsocket']
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
DIRS += ['hal', 'keystore', 'netd']
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
DIRS += ['contentproc']
deleted file mode 100644
--- a/ipc/nfc/NfcConnector.cpp
+++ /dev/null
@@ -1,207 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp: */
-
-/* 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/. */
-
-#include "NfcConnector.h"
-#include <fcntl.h>
-#include <sys/un.h>
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "nsThreadUtils.h" // For NS_IsMainThread.
-
-namespace mozilla {
-namespace ipc {
-
-NfcConnector::NfcConnector(const nsACString& aAddressString)
- : mAddressString(aAddressString)
-{
- MOZ_COUNT_CTOR_INHERITED(NfcConnector, UnixSocketConnector);
-}
-
-NfcConnector::~NfcConnector()
-{
- MOZ_COUNT_DTOR_INHERITED(NfcConnector, UnixSocketConnector);
-}
-
-nsresult
-NfcConnector::CreateSocket(int& aFd) const
-{
- aFd = socket(AF_LOCAL, SOCK_SEQPACKET, 0);
- if (aFd < 0) {
- NS_WARNING("Could not open NFC socket!");
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::SetSocketFlags(int aFd) const
-{
- static const int sReuseAddress = 1;
-
- // Set close-on-exec bit.
- int flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFD));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= FD_CLOEXEC;
- int res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFD, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set non-blocking status flag.
- flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFL));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= O_NONBLOCK;
- res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFL, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set socket addr to be reused even if kernel is still waiting to close.
- res = setsockopt(aFd, SOL_SOCKET, SO_REUSEADDR, &sReuseAddress,
- sizeof(sReuseAddress));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const
-{
- static const size_t sNameOffset = 1;
-
- struct sockaddr_un* address =
- reinterpret_cast<struct sockaddr_un*>(&aAddress);
-
- size_t namesiz = mAddressString.Length() + 1; // include trailing '\0'
-
- if (NS_WARN_IF((sNameOffset + namesiz) > sizeof(address->sun_path))) {
- return NS_ERROR_FAILURE;
- }
-
- address->sun_family = AF_UNIX;
- memset(address->sun_path, '\0', sNameOffset); // abstract socket
- memcpy(address->sun_path + sNameOffset, mAddressString.get(), namesiz);
-
- aAddressLength =
- offsetof(struct sockaddr_un, sun_path) + sNameOffset + namesiz;
-
- return NS_OK;
-}
-
-// |UnixSocketConnector|
-//
-
-nsresult
-NfcConnector::ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString)
-{
- MOZ_ASSERT(aAddress.sa_family == AF_UNIX);
-
- const struct sockaddr_un* un =
- reinterpret_cast<const struct sockaddr_un*>(&aAddress);
-
- size_t len = aAddressLength - offsetof(struct sockaddr_un, sun_path);
-
- aAddressString.Assign(un->sun_path, len);
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd)
-{
- ScopedClose fd;
-
- nsresult rv = CreateSocket(fd.rwget());
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
- if (aAddress && aAddressLength) {
- rv = CreateAddress(*aAddress, *aAddressLength);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
-
- aListenFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- ScopedClose fd(
- TEMP_FAILURE_RETRY(accept(aListenFd, aAddress, aAddressLength)));
- if (fd < 0) {
- NS_WARNING("Cannot accept file descriptor!");
- return NS_ERROR_FAILURE;
- }
- nsresult rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- aStreamFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- ScopedClose fd;
-
- nsresult rv = CreateSocket(fd.rwget());
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
- if (aAddress && aAddressLength) {
- rv = CreateAddress(*aAddress, *aAddressLength);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
-
- aStreamFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-NfcConnector::Duplicate(UnixSocketConnector*& aConnector)
-{
- aConnector = new NfcConnector(*this);
-
- return NS_OK;
-}
-
-}
-}
deleted file mode 100644
--- a/ipc/nfc/NfcConnector.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp: */
-
-/* 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/. */
-
-#ifndef mozilla_ipc_NfcConnector_h
-#define mozilla_ipc_NfcConnector_h
-
-#include "mozilla/ipc/UnixSocketConnector.h"
-
-namespace mozilla {
-namespace ipc {
-
-/**
- * |NfcConnector| creates sockets for communicating with
- * the NFC daemon.
- */
-class NfcConnector final : public UnixSocketConnector
-{
-public:
- NfcConnector(const nsACString& aAddressString);
- ~NfcConnector();
-
- // Methods for |UnixSocketConnector|
- //
-
- nsresult ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString) override;
-
- nsresult CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd) override;
-
- nsresult AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLen,
- int& aStreamFd) override;
-
- nsresult CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd) override;
-
- nsresult Duplicate(UnixSocketConnector*& aConnector) override;
-
-private:
- nsresult CreateSocket(int& aFd) const;
- nsresult SetSocketFlags(int aFd) const;
- nsresult CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const;
-
- nsCString mAddressString;
-};
-
-}
-}
-
-#endif
deleted file mode 100644
--- a/ipc/nfc/moz.build
+++ /dev/null
@@ -1,16 +0,0 @@
-# vim: set filetype=python:
-# 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/.
-
-if CONFIG['MOZ_NFC']:
- EXPORTS.mozilla.ipc += [
- 'NfcConnector.h',
- ]
- SOURCES += [
- 'NfcConnector.cpp',
- ]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
--- a/js/xpconnect/src/ExportHelpers.cpp
+++ b/js/xpconnect/src/ExportHelpers.cpp
@@ -9,19 +9,16 @@
#include "AccessCheck.h"
#include "jsfriendapi.h"
#include "jswrapper.h"
#include "js/Proxy.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/BlobBinding.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/StructuredCloneHolder.h"
-#ifdef MOZ_NFC
-#include "mozilla/dom/MozNDEFRecord.h"
-#endif
#include "nsGlobalWindow.h"
#include "nsJSUtils.h"
#include "nsIDOMFileList.h"
using namespace mozilla;
using namespace mozilla::dom;
using namespace JS;
@@ -36,17 +33,16 @@ IsReflector(JSObject* obj)
return IS_WN_REFLECTOR(obj) || dom::IsDOMObject(obj);
}
enum StackScopedCloneTags {
SCTAG_BASE = JS_SCTAG_USER_MIN,
SCTAG_REFLECTOR,
SCTAG_BLOB,
SCTAG_FUNCTION,
- SCTAG_DOM_NFC_NDEF
};
// The HTML5 structured cloning algorithm includes a few DOM objects, notably
// FileList. That wouldn't in itself be a reason to support them here,
// but we've historically supported them for Cu.cloneInto (where we didn't support
// other reflectors), so we need to continue to do so in the wrapReflectors == false
// case to maintain compatibility.
//
@@ -140,36 +136,16 @@ public:
if (!ToJSValue(aCx, blob, &val)) {
return nullptr;
}
}
return val.toObjectOrNull();
}
- if (aTag == SCTAG_DOM_NFC_NDEF) {
-#ifdef MOZ_NFC
- nsIGlobalObject* global = xpc::NativeGlobal(JS::CurrentGlobalOrNull(aCx));
- if (!global) {
- return nullptr;
- }
-
- // Prevent the return value from being trashed by a GC during ~nsRefPtr.
- JS::Rooted<JSObject*> result(aCx);
- {
- RefPtr<MozNDEFRecord> ndefRecord = new MozNDEFRecord(global);
- result = ndefRecord->ReadStructuredClone(aCx, aReader) ?
- ndefRecord->WrapObject(aCx, nullptr) : nullptr;
- }
- return result;
-#else
- return nullptr;
-#endif
- }
-
MOZ_ASSERT_UNREACHABLE("Encountered garbage in the clone stream!");
return nullptr;
}
bool CustomWriteHandler(JSContext* aCx,
JSStructuredCloneWriter* aWriter,
JS::Handle<JSObject*> aObj)
{
@@ -208,26 +184,16 @@ public:
return false;
return JS_WriteUint32Pair(aWriter, SCTAG_FUNCTION, mFunctions.length() - 1);
} else {
JS_ReportErrorASCII(aCx, "Permission denied to pass a Function via structured clone");
return false;
}
}
-#ifdef MOZ_NFC
- {
- MozNDEFRecord* ndefRecord;
- if (NS_SUCCEEDED(UNWRAP_OBJECT(MozNDEFRecord, aObj, ndefRecord))) {
- return JS_WriteUint32Pair(aWriter, SCTAG_DOM_NFC_NDEF, 0) &&
- ndefRecord->WriteStructuredClone(aCx, aWriter);
- }
- }
-#endif
-
JS_ReportErrorASCII(aCx, "Encountered unsupported value type writing stack-scoped structured clone");
return false;
}
StackScopedCloneOptions* mOptions;
AutoObjectVector mReflectors;
AutoObjectVector mFunctions;
nsTArray<RefPtr<BlobImpl>> mBlobImpls;
--- a/layout/build/moz.build
+++ b/layout/build/moz.build
@@ -11,21 +11,16 @@ EXPORTS += [
]
UNIFIED_SOURCES += [
'nsContentDLF.cpp',
'nsLayoutModule.cpp',
'nsLayoutStatics.cpp',
]
-if CONFIG['MOZ_NFC']:
- LOCAL_INCLUDES += [
- '/dom/nfc'
- ]
-
include('/ipc/chromium/chromium-config.mozbuild')
LOCAL_INCLUDES += [
'../base',
'../forms',
'../generic',
'../inspector',
'../mathml',
--- a/old-configure.in
+++ b/old-configure.in
@@ -102,38 +102,34 @@ if test -n "$gonkdir"; then
export gonkdir
kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
android_source="$gonkdir"
ANDROID_SOURCE="$android_source"
case "$android_version" in
15)
CPPFLAGS="-I$gonkdir/frameworks/base/opengl/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/frameworks/base/include -I$gonkdir/frameworks/base/services/camera -I$gonkdir/frameworks/base/include/media/ -I$gonkdir/frameworks/base/include/media/stagefright -I$gonkdir/frameworks/base/include/media/stagefright/openmax -I$gonkdir/frameworks/base/media/libstagefright/rtsp -I$gonkdir/frameworks/base/media/libstagefright/include -I$gonkdir/external/dbus -I$gonkdir/external/bluetooth/bluez/lib -I$gonkdir/dalvik/libnativehelper/include/nativehelper $CPPFLAGS"
- MOZ_NFC=1
MOZ_SECUREELEMENT=1
;;
17|18)
CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
- MOZ_NFC=1
MOZ_SECUREELEMENT=1
;;
19)
CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
- MOZ_NFC=1
MOZ_AUDIO_OFFLOAD=1
MOZ_SECUREELEMENT=1
AC_SUBST(MOZ_AUDIO_OFFLOAD)
AC_DEFINE(MOZ_AUDIO_OFFLOAD)
;;
21|22)
CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
MOZ_AUDIO_OFFLOAD=1
AC_SUBST(MOZ_AUDIO_OFFLOAD)
AC_DEFINE(MOZ_AUDIO_OFFLOAD)
- MOZ_NFC=1
;;
*)
AC_MSG_ERROR([Unsupported platform version: $android_version])
;;
esac
dnl Enable Bluetooth backends depending on available drivers
if test -d "$gonkdir/system/bluetoothd"; then
@@ -4785,28 +4781,16 @@ MOZ_ARG_ENABLE_BOOL(b2g-bt,
if test -n "$MOZ_B2G_BT"; then
AC_DEFINE(MOZ_B2G_BT)
fi
AC_SUBST(MOZ_B2G_BT)
AC_SUBST(MOZ_B2G_BT_BLUEZ)
AC_SUBST(MOZ_B2G_BT_DAEMON)
dnl ========================================================
-dnl = Enable NFC Interface for B2G (Gonk usually)
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(nfc,
-[ --enable-nfc Set compile flags necessary for compiling NFC API ],
- MOZ_NFC=1,
- MOZ_NFC= )
-if test -n "$MOZ_NFC"; then
- AC_DEFINE(MOZ_NFC)
-fi
-AC_SUBST(MOZ_NFC)
-
-dnl ========================================================
dnl = Enable Pico Speech Synthesis (Gonk usually)
dnl ========================================================
MOZ_ARG_ENABLE_BOOL(synth-pico,
[ --enable-synth-pico Set compile flags necessary for compiling Pico Web Speech API ],
MOZ_SYNTH_PICO=1,
MOZ_SYNTH_PICO= )
if test -n "$MOZ_SYNTH_PICO"; then
AC_DEFINE(MOZ_SYNTH_PICO)
--- a/testing/marionette/harness/marionette/tests/webapi-tests.ini
+++ b/testing/marionette/harness/marionette/tests/webapi-tests.ini
@@ -1,14 +1,13 @@
[include:../../../../../dom/bluetooth/tests/marionette/manifest.ini]
[include:../../../../../dom/telephony/test/marionette/manifest.ini]
[include:../../../../../dom/battery/test/marionette/manifest.ini]
[include:../../../../../dom/mobileconnection/tests/marionette/manifest.ini]
[include:../../../../../dom/system/gonk/tests/marionette/manifest.ini]
[include:../../../../../dom/icc/tests/marionette/manifest.ini]
[include:../../../../../dom/system/tests/marionette/manifest.ini]
-[include:../../../../../dom/nfc/tests/marionette/manifest.ini]
skip-if = android_version > '15' # Bug 1203072
[include:../../../../../dom/events/test/marionette/manifest.ini]
[include:../../../../../dom/wifi/test/marionette/manifest.ini]
[include:../../../../../dom/tethering/tests/marionette/manifest.ini]
skip-if = android_version > '15' # Bug 1203075
[include:../../../../../dom/network/tests/marionette/manifest.ini]