merge mozilla-central to mozilla-inbound

This commit is contained in:
Carsten "Tomcat" Book 2013-11-07 16:07:34 +01:00
Родитель 8fe3207dca 2490b7a836
Коммит d8daefc008
95 изменённых файлов: 3606 добавлений и 1084 удалений

Просмотреть файл

@ -72,7 +72,7 @@ config.status: $(topsrcdir)/configure
backend.RecursiveMakeBackend:
@echo "Build configuration changed. Regenerating backend."
./config.status
$(PYTHON) config.status
Makefile: backend.RecursiveMakeBackend
@$(TOUCH) $@

Просмотреть файл

@ -1,4 +1,4 @@
{
"revision": "1f7e70f3ad1c7a79dc03410d774e32a07093da3f",
"revision": "207a81a6816b8627674a956b521772de2ac6b572",
"repo_path": "/integration/gaia-central"
}

Просмотреть файл

@ -248,6 +248,7 @@ BluetoothAdapter::SetPropertyByValue(const BluetoothNamedValue& aValue)
nsresult rv;
nsIScriptContext* sc = GetContextForEventHandlers(&rv);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_TRUE_VOID(sc);
AutoPushJSContext cx(sc->GetNativeContext());
JS::Rooted<JSObject*> uuids(cx);
@ -263,6 +264,7 @@ BluetoothAdapter::SetPropertyByValue(const BluetoothNamedValue& aValue)
nsresult rv;
nsIScriptContext* sc = GetContextForEventHandlers(&rv);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_TRUE_VOID(sc);
AutoPushJSContext cx(sc->GetNativeContext());
JS::Rooted<JSObject*> deviceAddresses(cx);

Просмотреть файл

@ -125,6 +125,7 @@ BluetoothDevice::SetPropertyByValue(const BluetoothNamedValue& aValue)
nsresult rv;
nsIScriptContext* sc = GetContextForEventHandlers(&rv);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_TRUE_VOID(sc);
AutoPushJSContext cx(sc->GetNativeContext());
@ -140,6 +141,7 @@ BluetoothDevice::SetPropertyByValue(const BluetoothNamedValue& aValue)
nsresult rv;
nsIScriptContext* sc = GetContextForEventHandlers(&rv);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_TRUE_VOID(sc);
AutoPushJSContext cx(sc->GetNativeContext());

Просмотреть файл

@ -7,7 +7,6 @@
#include "base/basictypes.h"
#include "BluetoothOppManager.h"
#include "BluetoothProfileController.h"
#include "BluetoothService.h"
#include "BluetoothSocket.h"
#include "BluetoothUtils.h"
@ -189,7 +188,6 @@ BluetoothOppManager::BluetoothOppManager() : mConnected(false)
, mSentFileLength(0)
, mWaitingToSendPutFinal(false)
, mCurrentBlobIndex(-1)
, mController(nullptr)
{
mConnectedDeviceAddress.AssignLiteral(BLUETOOTH_ADDRESS_NONE);
}
@ -278,48 +276,6 @@ BluetoothOppManager::ConnectInternal(const nsAString& aDeviceAddress)
new BluetoothSocket(this, BluetoothSocketType::RFCOMM, true, true);
}
void
BluetoothOppManager::Connect(const nsAString& aDeviceAddress,
BluetoothProfileController* aController)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aController && !mController);
BluetoothService* bs = BluetoothService::Get();
if (!bs || sInShutdown) {
aController->OnConnect(NS_LITERAL_STRING(ERR_NO_AVAILABLE_RESOURCE));
return;
}
if (mSocket) {
if (mConnectedDeviceAddress == aDeviceAddress) {
aController->OnConnect(NS_LITERAL_STRING(ERR_ALREADY_CONNECTED));
} else {
aController->OnConnect(NS_LITERAL_STRING(ERR_REACHED_CONNECTION_LIMIT));
}
return;
}
mController = aController;
OnConnect(EmptyString());
}
void
BluetoothOppManager::Disconnect(BluetoothProfileController* aController)
{
if (!mSocket) {
if (aController) {
aController->OnDisconnect(NS_LITERAL_STRING(ERR_ALREADY_DISCONNECTED));
}
return;
}
MOZ_ASSERT(!mController);
mController = aController;
mSocket->Disconnect();
}
void
BluetoothOppManager::HandleShutdown()
{
@ -1582,37 +1538,27 @@ BluetoothOppManager::AcquireSdcardMountLock()
return true;
}
void
BluetoothOppManager::Connect(const nsAString& aDeviceAddress,
BluetoothProfileController* aController)
{
MOZ_ASSERT(false);
}
void
BluetoothOppManager::Disconnect(BluetoothProfileController* aController)
{
MOZ_ASSERT(false);
}
void
BluetoothOppManager::OnConnect(const nsAString& aErrorStr)
{
MOZ_ASSERT(NS_IsMainThread());
if (!aErrorStr.IsEmpty()) {
mSocket = nullptr;
Listen();
}
/**
* On the one hand, notify the controller that we've done for outbound
* connections. On the other hand, we do nothing for inbound connections.
*/
NS_ENSURE_TRUE_VOID(mController);
nsRefPtr<BluetoothProfileController> controller = mController.forget();
controller->OnConnect(aErrorStr);
MOZ_ASSERT(false);
}
void
BluetoothOppManager::OnDisconnect(const nsAString& aErrorStr)
{
MOZ_ASSERT(NS_IsMainThread());
/**
* On the one hand, notify the controller that we've done for outbound
* connections. On the other hand, we do nothing for inbound connections.
*/
NS_ENSURE_TRUE_VOID(mController);
nsRefPtr<BluetoothProfileController> controller = mController.forget();
controller->OnDisconnect(aErrorStr);
MOZ_ASSERT(false);
}

Просмотреть файл

@ -82,17 +82,6 @@ public:
aName.AssignLiteral("OPP");
}
/*
* If an application wants to send a file, first, it needs to
* call Connect() to create a valid RFCOMM connection. After
* that, call SendFile()/StopSendingFile() to control file-sharing
* process. During the file transfering process, the application
* will receive several system messages which contain the processed
* percentage of file. At the end, the application will get another
* system message indicating that the process is complete, then it can
* either call Disconnect() to close RFCOMM connection or start another
* file-sending thread via calling SendFile() again.
*/
virtual void Connect(const nsAString& aDeviceAddress,
BluetoothProfileController* aController) MOZ_OVERRIDE;
virtual void Disconnect(BluetoothProfileController* aController) MOZ_OVERRIDE;
@ -222,7 +211,6 @@ private:
nsCOMPtr<nsIOutputStream> mOutputStream;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIVolumeMountLock> mMountLock;
nsRefPtr<BluetoothProfileController> mController;
nsRefPtr<DeviceStorageFile> mDsFile;
// If a connection has been established, mSocket will be the socket

Просмотреть файл

@ -10,7 +10,6 @@
#include "BluetoothA2dpManager.h"
#include "BluetoothHfpManager.h"
#include "BluetoothHidManager.h"
#include "BluetoothOppManager.h"
#include "BluetoothUtils.h"
#include "mozilla/dom/bluetooth/BluetoothTypes.h"
@ -80,9 +79,6 @@ BluetoothProfileController::AddProfileWithServiceClass(
case BluetoothServiceClass::A2DP:
profile = BluetoothA2dpManager::Get();
break;
case BluetoothServiceClass::OBJECT_PUSH:
profile = BluetoothOppManager::Get();
break;
case BluetoothServiceClass::HID:
profile = BluetoothHidManager::Get();
break;
@ -132,7 +128,6 @@ BluetoothProfileController::SetupProfiles(bool aAssignServiceClass)
// For a disconnect request, all connected profiles are put into array.
if (!mConnect) {
AddProfile(BluetoothHidManager::Get(), true);
AddProfile(BluetoothOppManager::Get(), true);
AddProfile(BluetoothA2dpManager::Get(), true);
AddProfile(BluetoothHfpManager::Get(), true);
return;
@ -143,17 +138,13 @@ BluetoothProfileController::SetupProfiles(bool aAssignServiceClass)
* all of them sequencely.
*/
bool hasAudio = HAS_AUDIO(mTarget.cod);
bool hasObjectTransfer = HAS_OBJECT_TRANSFER(mTarget.cod);
bool hasRendering = HAS_RENDERING(mTarget.cod);
bool isPeripheral = IS_PERIPHERAL(mTarget.cod);
NS_ENSURE_TRUE_VOID(hasAudio || hasObjectTransfer ||
hasRendering || isPeripheral);
NS_ENSURE_TRUE_VOID(hasAudio || hasRendering || isPeripheral);
/**
* Connect to HFP/HSP first. Then, connect A2DP if Rendering bit is set.
* It's almost impossible to send file to a remote device which is an Audio
* device or a Rendering device, so we won't connect OPP in that case.
*/
if (hasAudio) {
AddProfile(BluetoothHfpManager::Get());
@ -161,9 +152,6 @@ BluetoothProfileController::SetupProfiles(bool aAssignServiceClass)
if (hasRendering) {
AddProfile(BluetoothA2dpManager::Get());
}
if (hasObjectTransfer && !hasAudio && !hasRendering) {
AddProfile(BluetoothOppManager::Get());
}
if (isPeripheral) {
AddProfile(BluetoothHidManager::Get());
}

Просмотреть файл

@ -37,9 +37,6 @@ BEGIN_BLUETOOTH_NAMESPACE
// Bit 21: Major service class = 0x100, Audio
#define HAS_AUDIO(cod) (cod & 0x200000)
// Bit 20: Major service class = 0x80, Object Transfer
#define HAS_OBJECT_TRANSFER(cod) (cod & 0x100000)
// Bit 18: Major service class = 0x20, Rendering
#define HAS_RENDERING(cod) (cod & 0x40000)

Просмотреть файл

@ -1009,19 +1009,21 @@ var steps = [
next();
},
function() {
ok(true, "Undefined strings should be treated as null");
ok(true, "Undefined properties of fields should be treated correctly");
var c = new mozContact({
adr: [{value: undefined}],
adr: [{streetAddress: undefined}],
email: [{value: undefined}],
url: [{value: undefined}],
impp: [{value: undefined}],
tel: [{value: undefined}],
});
is(c.adr[0].type, null, "adr is null");
is(c.email[0].type, null, "email is null");
is(c.url[0].type, null, "url is null");
is(c.impp[0].type, null, "impp is null");
is(c.tel[0].type, null, "tel is null");
ise(c.adr[0].streetAddress, null, "adr.streetAddress is null");
ise(c.adr[0].locality, null, "adr.locality is null");
ise(c.adr[0].pref, null, "adr.pref is null");
ise(c.email[0].value, null, "email.value is null");
ise(c.url[0].value, null, "url.value is null");
ise(c.impp[0].value, null, "impp.value is null");
ise(c.tel[0].value, null, "tel.value is null");
next();
},
function() {

Просмотреть файл

@ -310,7 +310,7 @@ interface nsIDOMMozIccManager : nsIDOMEventTarget
* 'pukRequired', 'personalizationInProgress', 'networkLocked',
* 'corporateLocked', 'serviceProviderLocked', 'networkPukRequired',
* 'corporatePukRequired', 'serviceProviderPukRequired',
* 'personalizationReady', 'ready'.
* 'personalizationReady', 'ready', 'permanentBlocked'.
*/
readonly attribute DOMString cardState;

Просмотреть файл

@ -0,0 +1,48 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
if (expect) {
func(evt.command, expect);
} else {
func(evt.command);
}
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect);
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testDisplayText(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -96,40 +91,4 @@ let tests = [
timeInterval: 0x0A}}},
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testGetInKey(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -107,40 +102,4 @@ let tests = [
timeInterval: 0x0A}}},
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testGetInput(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -174,40 +169,4 @@ let tests = [
maxLength: 10}},
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testLaunchBrowser(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -251,40 +246,4 @@ let tests = [
text: "ル"}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testPollOff(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -23,40 +18,4 @@ let tests = [
commandQualifier: 0x00}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testLocalInfoLocation(cmd) {
log("STK CMD " + JSON.stringify(cmd));
@ -109,39 +104,4 @@ let tests = [
func: testTimerManagementGetCurrentValue},
];
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(cmd, func) {
++pendingEmulatorCmdCount;
runEmulatorCmd(cmd, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let cmd = "stk pdu " + test.command;
sendStkPduToEmulator(cmd, test.func)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testRefresh(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -27,40 +22,4 @@ let tests = [
commandQualifier: 0x04}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSelectItem(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -312,40 +307,4 @@ let tests = [
items: [{identifier: 1, text: "82ル1"}, {identifier: 2, text: "82ル2"}, {identifier: 3, text: "82ル3"}]}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSendDTMF(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -192,40 +187,4 @@ let tests = [
text: "ル"}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSendSMS(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -242,40 +237,4 @@ let tests = [
title: "82ル2"}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSendSS(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -202,40 +197,4 @@ let tests = [
title: "ル"}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSendUSSD(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -207,40 +202,4 @@ let tests = [
title: "ル"}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSetupCall(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -346,40 +341,4 @@ let tests = [
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSetupEventList(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -52,40 +47,4 @@ let tests = [
eventList: [7]}}
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSetupIdleModeText(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -195,40 +190,4 @@ let tests = [
text: "80ル0"}},
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -1,12 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
MARIONETTE_TIMEOUT = 30000;
SpecialPowers.addPermission("mobileconnection", true, document);
let icc = navigator.mozIccManager;
ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
MARIONETTE_HEAD_JS = "stk_helper.js";
function testSetupMenu(command, expect) {
log("STK CMD " + JSON.stringify(command));
@ -234,40 +229,4 @@ let tests = [
];
// TODO - Bug 843455: Import scripts for marionette tests.
let pendingEmulatorCmdCount = 0;
function sendStkPduToEmulator(command, func, expect) {
++pendingEmulatorCmdCount;
runEmulatorCmd(command, function (result) {
--pendingEmulatorCmdCount;
is(result[0], "OK");
});
icc.onstkcommand = function (evt) {
func(evt.command, expect);
}
}
function runNextTest() {
let test = tests.pop();
if (!test) {
cleanUp();
return;
}
let command = "stk pdu " + test.command;
sendStkPduToEmulator(command, test.func, test.expect)
}
function cleanUp() {
if (pendingEmulatorCmdCount) {
window.setTimeout(cleanUp, 100);
return;
}
SpecialPowers.removePermission("mobileconnection", document);
finish();
}
runNextTest();

Просмотреть файл

@ -7,7 +7,7 @@
if CONFIG['MOZ_WEBRTC']:
DIRS += ['bridge']
TEST_DIRS += ['tests/mochitest']
TEST_DIRS += ['tests/mochitest', 'tests/ipc']
XPIDL_SOURCES += [
'nsIDOMMediaStream.idl',

Просмотреть файл

@ -0,0 +1,4 @@
# 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/.

Просмотреть файл

@ -0,0 +1,3 @@
[DEFAULT]
[test_ipc.html]

Просмотреть файл

@ -0,0 +1,7 @@
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
# 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/.
MOCHITEST_MANIFESTS += ['mochitest.ini']

Просмотреть файл

@ -0,0 +1,175 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Test for OOP PeerConncection</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<script type="application/javascript;version=1.7">
"use strict";
SimpleTest.waitForExplicitFinish();
// This isn't a single test. It runs the entirety of the PeerConnection
// tests. Each of those has a normal timeout handler, so there's no point in
// having a timeout here. I'm setting this really high just to avoid getting
// killed.
SimpleTest.requestLongerTimeout(100);
// Disable crash observers as it breaks later tests.
function iframeScriptFirst() {
SpecialPowers.prototype.registerProcessCrashObservers = function() { };
SpecialPowers.prototype.unregisterProcessCrashObservers = function() { };
content.wrappedJSObject.RunSet.reloadAndRunAll({
preventDefault: function() { },
__exposedProps__: { preventDefault: 'r' }
});
}
function iframeScriptSecond() {
let TestRunner = content.wrappedJSObject.TestRunner;
let oldComplete = TestRunner.onComplete;
TestRunner.onComplete = function() {
TestRunner.onComplete = oldComplete;
sendAsyncMessage("test:PeerConnection:ipcTestComplete", {
result: JSON.stringify(TestRunner._failedTests)
});
if (oldComplete) {
oldComplete();
}
};
let oldLog = TestRunner.log;
TestRunner.log = function(msg) {
sendAsyncMessage("test:PeerConnection:ipcTestMessage", { msg: msg });
}
}
let regex = /^(TEST-PASS|TEST-UNEXPECTED-PASS|TEST-KNOWN-FAIL|TEST-UNEXPECTED-FAIL|TEST-DEBUG-INFO) \| ([^\|]+) \|(.*)/;
function onTestMessage(data) {
let message = SpecialPowers.wrap(data).json.msg;
let match = regex.exec(message);
if (match) {
let state = match[1];
let details = match[2] + " | " + match[3];
switch (state) {
case "TEST-PASS":
case "TEST-KNOWN-FAIL":
ok(true, details);
break;
case "TEST-UNEXPECTED-FAIL":
case "TEST-UNEXPECTED-PASS":
ok(false, details);
break;
case "TEST-DEBUG-INFO":
default:
info(details);
}
}
}
function onTestComplete() {
let comp = SpecialPowers.wrap(SpecialPowers.Components);
let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
let spObserver = comp.classes["@mozilla.org/special-powers-observer;1"]
.getService(comp.interfaces.nsIMessageListener);
mm.removeMessageListener("SPPrefService", spObserver);
mm.removeMessageListener("SPProcessCrashService", spObserver);
mm.removeMessageListener("SPPingService", spObserver);
mm.removeMessageListener("SpecialPowers.Quit", spObserver);
mm.removeMessageListener("SPPermissionManager", spObserver);
mm.removeMessageListener("test:PeerConnection:ipcTestMessage", onTestMessage);
mm.removeMessageListener("test:PeerConnection:ipcTestComplete", onTestComplete);
SimpleTest.executeSoon(function () { SimpleTest.finish(); });
}
function runTests() {
let iframe = document.createElement("iframe");
SpecialPowers.wrap(iframe).mozbrowser = true;
iframe.id = "iframe";
iframe.style.width = "100%";
iframe.style.height = "1000px";
function iframeLoadSecond() {
ok(true, "Got second iframe load event.");
iframe.removeEventListener("mozbrowserloadend", iframeLoadSecond);
let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
mm.loadFrameScript("data:,(" + iframeScriptSecond.toString() + ")();",
false);
}
function iframeLoadFirst() {
ok(true, "Got first iframe load event.");
iframe.removeEventListener("mozbrowserloadend", iframeLoadFirst);
iframe.addEventListener("mozbrowserloadend", iframeLoadSecond);
let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
let comp = SpecialPowers.wrap(SpecialPowers.Components);
let spObserver =
comp.classes["@mozilla.org/special-powers-observer;1"]
.getService(comp.interfaces.nsIMessageListener);
mm.addMessageListener("SPPrefService", spObserver);
mm.addMessageListener("SPProcessCrashService", spObserver);
mm.addMessageListener("SPPingService", spObserver);
mm.addMessageListener("SpecialPowers.Quit", spObserver);
mm.addMessageListener("SPPermissionManager", spObserver);
mm.addMessageListener("test:PeerConnection:ipcTestMessage", onTestMessage);
mm.addMessageListener("test:PeerConnection:ipcTestComplete", onTestComplete);
let specialPowersBase = "chrome://specialpowers/content/";
mm.loadFrameScript(specialPowersBase + "MozillaLogger.js", false);
mm.loadFrameScript(specialPowersBase + "specialpowersAPI.js", false);
mm.loadFrameScript(specialPowersBase + "specialpowers.js", false);
mm.loadFrameScript("data:,(" + iframeScriptFirst.toString() + ")();", false);
}
iframe.addEventListener("mozbrowserloadend", iframeLoadFirst);
// Strip this filename and one directory level and then add "/mochitest".
let href = window.location.href;
href = href.substring(0, href.lastIndexOf('/'));
href = href.substring(0, href.lastIndexOf('/'));
iframe.src = href + "/mochitest?consoleLevel=INFO";
document.body.appendChild(iframe);
}
addEventListener("load", function() {
SpecialPowers.addPermission("browser", true, document);
SpecialPowers.pushPrefEnv({
"set": [
["media.peerconnection.ipc.enabled", true],
// TODO: remove this as part of bug 820712
["network.disable.ipc.security", true],
["dom.ipc.browser_frames.oop_by_default", true],
["dom.mozBrowserFramesEnabled", true],
["browser.pagethumbnails.capturing_disabled", true]
]
}, runTests);
});
</script>
</body>
</html>

Просмотреть файл

@ -13,6 +13,7 @@ XPIDL_SOURCES += [
'nsITCPServerSocketParent.idl',
'nsITCPSocketChild.idl',
'nsITCPSocketParent.idl',
'nsIUDPSocketChild.idl',
]
if CONFIG['MOZ_B2G_RIL']:

Просмотреть файл

@ -0,0 +1,52 @@
/* 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"
#include "nsINetAddr.idl"
interface nsIUDPSocketInternal;
%{ C++
#include "mozilla/net/DNS.h"
%}
native NetAddr(mozilla::net::NetAddr);
[ptr] native NetAddrPtr(mozilla::net::NetAddr);
[scriptable, uuid(B47E5A0F-D384-48EF-8885-4259793D9CF0)]
interface nsIUDPSocketChild : nsISupports
{
readonly attribute unsigned short localPort;
readonly attribute AUTF8String localAddress;
// Tell the chrome process to bind the UDP socket to a given local host and port
void bind(in nsIUDPSocketInternal socket, in AUTF8String host, in unsigned short port);
// Tell the chrome process to perform equivalent operations to all following methods
void send(in AUTF8String host, in unsigned short port,
[const, array, size_is(byteLength)] in uint8_t bytes,
in unsigned long byteLength);
// Send without DNS query
void sendWithAddr(in nsINetAddr addr,
[const, array, size_is(byteLength)] in uint8_t bytes,
in unsigned long byteLength);
[noscript] void sendWithAddress([const] in NetAddrPtr addr,
[const, array, size_is(byteLength)] in uint8_t bytes,
in unsigned long byteLength);
void close();
};
/*
* Internal interface for callback from chrome process
*/
[scriptable, uuid(1E27E9B3-C1C8-4B05-A415-1A2C1A641C60)]
interface nsIUDPSocketInternal : nsISupports
{
void callListenerError(in AUTF8String type, in AUTF8String message, in AUTF8String filename,
in uint32_t lineNumber, in uint32_t columnNumber);
void callListenerReceivedData(in AUTF8String type, in AUTF8String host, in unsigned short port,
[array, size_is(dataLength)] in uint8_t data,
in unsigned long dataLength);
void callListenerVoid(in AUTF8String type);
void callListenerSent(in AUTF8String type, in nsresult status);
void updateReadyState(in AUTF8String readyState);
};

Просмотреть файл

@ -0,0 +1,69 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 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 protocol PNecko;
include "mozilla/net/NeckoMessageUtils.h";
include "mozilla/net/DNS.h";
include "prio.h";
using mozilla::net::NetAddr from "mozilla/net/DNS.h";
using struct mozilla::void_t from "ipc/IPCMessageUtils.h";
struct UDPError {
nsCString message;
nsCString filename;
uint32_t lineNumber;
uint32_t columnNumber;
};
struct UDPMessage {
nsCString fromAddr;
uint16_t port;
uint8_t[] data;
};
struct UDPAddressInfo {
nsCString local;
uint16_t port;
};
struct UDPSendResult {
nsresult value;
};
union UDPCallbackData {
void_t;
UDPMessage;
UDPAddressInfo;
UDPSendResult;
UDPError;
};
namespace mozilla {
namespace net {
//-------------------------------------------------------------------
protocol PUDPSocket
{
manager PNecko;
parent:
Data(uint8_t[] data, nsCString remoteAddress, uint16_t port);
DataWithAddress(uint8_t[] data, NetAddr addr);
Close();
RequestDelete();
child:
Callback(nsCString type, UDPCallbackData data, nsCString aState);
__delete__();
};
} // namespace net
} // namespace mozilla

Просмотреть файл

@ -0,0 +1,192 @@
/* 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 "UDPSocketChild.h"
#include "mozilla/net/NeckoChild.h"
using mozilla::net::gNeckoChild;
namespace mozilla {
namespace dom {
NS_IMPL_ISUPPORTS1(UDPSocketChildBase, nsIUDPSocketChild)
UDPSocketChildBase::UDPSocketChildBase()
: mIPCOpen(false)
{
}
UDPSocketChildBase::~UDPSocketChildBase()
{
}
void
UDPSocketChildBase::ReleaseIPDLReference()
{
MOZ_ASSERT(mIPCOpen);
mIPCOpen = false;
this->Release();
}
void
UDPSocketChildBase::AddIPDLReference()
{
MOZ_ASSERT(!mIPCOpen);
mIPCOpen = true;
this->AddRef();
}
NS_IMETHODIMP_(nsrefcnt) UDPSocketChild::Release(void)
{
nsrefcnt refcnt = UDPSocketChildBase::Release();
if (refcnt == 1 && mIPCOpen) {
PUDPSocketChild::SendRequestDelete();
return 1;
}
return refcnt;
}
UDPSocketChild::UDPSocketChild()
:mLocalPort(0)
{
}
UDPSocketChild::~UDPSocketChild()
{
}
// nsIUDPSocketChild Methods
NS_IMETHODIMP
UDPSocketChild::Bind(nsIUDPSocketInternal *aSocket,
const nsACString& aHost,
uint16_t aPort)
{
NS_ENSURE_ARG(aSocket);
mSocket = aSocket;
AddIPDLReference();
gNeckoChild->SendPUDPSocketConstructor(this, nsCString(aHost), aPort);
return NS_OK;
}
NS_IMETHODIMP
UDPSocketChild::Close()
{
SendClose();
return NS_OK;
}
NS_IMETHODIMP
UDPSocketChild::Send(const nsACString& aHost,
uint16_t aPort,
const uint8_t *aData,
uint32_t aByteLength)
{
NS_ENSURE_ARG(aData);
FallibleTArray<uint8_t> fallibleArray;
if (!fallibleArray.InsertElementsAt(0, aData, aByteLength)) {
return NS_ERROR_OUT_OF_MEMORY;
}
InfallibleTArray<uint8_t> array;
array.SwapElements(fallibleArray);
SendData(array, nsCString(aHost), aPort);
return NS_OK;
}
NS_IMETHODIMP
UDPSocketChild::SendWithAddr(nsINetAddr *aAddr,
const uint8_t *aData,
uint32_t aByteLength)
{
NS_ENSURE_ARG(aAddr);
NS_ENSURE_ARG(aData);
NetAddr addr;
aAddr->GetNetAddr(&addr);
return SendWithAddress(&addr, aData, aByteLength);
}
NS_IMETHODIMP
UDPSocketChild::SendWithAddress(const NetAddr *aAddr,
const uint8_t *aData,
uint32_t aByteLength)
{
NS_ENSURE_ARG(aAddr);
NS_ENSURE_ARG(aData);
FallibleTArray<uint8_t> fallibleArray;
if (!fallibleArray.InsertElementsAt(0, aData, aByteLength)) {
return NS_ERROR_OUT_OF_MEMORY;
}
InfallibleTArray<uint8_t> array;
array.SwapElements(fallibleArray);
SendDataWithAddress(array, *aAddr);
return NS_OK;
}
NS_IMETHODIMP
UDPSocketChild::GetLocalPort(uint16_t *aLocalPort)
{
NS_ENSURE_ARG_POINTER(aLocalPort);
*aLocalPort = mLocalPort;
return NS_OK;
}
NS_IMETHODIMP
UDPSocketChild::GetLocalAddress(nsACString &aLocalAddress)
{
aLocalAddress = mLocalAddress;
return NS_OK;
}
// PUDPSocketChild Methods
bool
UDPSocketChild::RecvCallback(const nsCString &aType,
const UDPCallbackData &aData,
const nsCString &aState)
{
if (NS_FAILED(mSocket->UpdateReadyState(aState)))
NS_ERROR("Shouldn't fail!");
nsresult rv = NS_ERROR_FAILURE;
if (aData.type() == UDPCallbackData::Tvoid_t) {
rv = mSocket->CallListenerVoid(aType);
} else if (aData.type() == UDPCallbackData::TUDPError) {
const UDPError& err(aData.get_UDPError());
rv = mSocket->CallListenerError(aType, err.message(), err.filename(),
err.lineNumber(), err.columnNumber());
} else if (aData.type() == UDPCallbackData::TUDPMessage) {
const UDPMessage& message(aData.get_UDPMessage());
InfallibleTArray<uint8_t> data(message.data());
rv = mSocket->CallListenerReceivedData(aType, message.fromAddr(), message.port(),
data.Elements(), data.Length());
} else if (aData.type() == UDPCallbackData::TUDPAddressInfo) {
//update local address and port.
const UDPAddressInfo& addressInfo(aData.get_UDPAddressInfo());
mLocalAddress = addressInfo.local();
mLocalPort = addressInfo.port();
rv = mSocket->CallListenerVoid(aType);
} else if (aData.type() == UDPCallbackData::TUDPSendResult) {
const UDPSendResult& returnValue(aData.get_UDPSendResult());
rv = mSocket->CallListenerSent(aType, returnValue.value());
} else {
MOZ_ASSERT("Invalid callback type!");
}
NS_ENSURE_SUCCESS(rv, true);
return true;
}
} // namespace dom
} // namespace mozilla

Просмотреть файл

@ -0,0 +1,54 @@
/* 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_UDPSocketChild_h__
#define mozilla_dom_UDPSocketChild_h__
#include "mozilla/net/PUDPSocketChild.h"
#include "nsIUDPSocketChild.h"
#include "nsCycleCollectionParticipant.h"
#include "nsCOMPtr.h"
#define UDPSOCKETCHILD_CID \
{0xb47e5a0f, 0xd384, 0x48ef, { 0x88, 0x85, 0x42, 0x59, 0x79, 0x3d, 0x9c, 0xf0 }}
namespace mozilla {
namespace dom {
class UDPSocketChildBase : public nsIUDPSocketChild {
public:
NS_DECL_ISUPPORTS
void AddIPDLReference();
void ReleaseIPDLReference();
protected:
UDPSocketChildBase();
virtual ~UDPSocketChildBase();
nsCOMPtr<nsIUDPSocketInternal> mSocket;
bool mIPCOpen;
};
class UDPSocketChild : public mozilla::net::PUDPSocketChild
, public UDPSocketChildBase
{
public:
NS_DECL_NSIUDPSOCKETCHILD
NS_IMETHOD_(nsrefcnt) Release() MOZ_OVERRIDE;
UDPSocketChild();
virtual ~UDPSocketChild();
virtual bool RecvCallback(const nsCString& aType,
const UDPCallbackData& aData,
const nsCString& aState) MOZ_OVERRIDE;
private:
uint16_t mLocalPort;
nsCString mLocalAddress;
};
} // namespace dom
} // namespace mozilla
#endif // !defined(mozilla_dom_UDPSocketChild_h__)

Просмотреть файл

@ -0,0 +1,239 @@
/* 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 "UDPSocketParent.h"
#include "nsComponentManagerUtils.h"
#include "nsIUDPSocket.h"
#include "nsINetAddr.h"
#include "mozilla/unused.h"
#include "mozilla/net/DNS.h"
namespace mozilla {
namespace dom {
static void
FireInternalError(mozilla::net::PUDPSocketParent *aActor, uint32_t aLineNo)
{
mozilla::unused <<
aActor->SendCallback(NS_LITERAL_CSTRING("onerror"),
UDPError(NS_LITERAL_CSTRING("Internal error"),
NS_LITERAL_CSTRING(__FILE__), aLineNo, 0),
NS_LITERAL_CSTRING("connecting"));
}
static nsresult
ConvertNetAddrToString(mozilla::net::NetAddr &netAddr, nsACString *address, uint16_t *port)
{
NS_ENSURE_ARG_POINTER(address);
NS_ENSURE_ARG_POINTER(port);
*port = 0;
uint32_t bufSize = 0;
switch(netAddr.raw.family) {
case AF_INET:
*port = PR_ntohs(netAddr.inet.port);
bufSize = mozilla::net::kIPv4CStrBufSize;
break;
case AF_INET6:
*port = PR_ntohs(netAddr.inet6.port);
bufSize = mozilla::net::kIPv6CStrBufSize;
break;
default:
//impossible
MOZ_ASSERT("Unexpected address family");
return NS_ERROR_INVALID_ARG;
}
address->SetCapacity(bufSize);
NetAddrToString(&netAddr, address->BeginWriting(), bufSize);
address->SetLength(strlen(address->BeginReading()));
return NS_OK;
}
NS_IMPL_ISUPPORTS1(UDPSocketParent, nsIUDPSocketListener)
UDPSocketParent::~UDPSocketParent()
{
}
// PUDPSocketParent methods
bool
UDPSocketParent::Init(const nsCString &aHost, const uint16_t aPort)
{
nsresult rv;
nsCOMPtr<nsIUDPSocket> sock =
do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv);
if (NS_FAILED(rv)) {
FireInternalError(this, __LINE__);
return true;
}
if (aHost.IsEmpty()) {
rv = sock->Init(aPort, false);
} else {
PRNetAddr prAddr;
PR_InitializeNetAddr(PR_IpAddrAny, aPort, &prAddr);
PRStatus status = PR_StringToNetAddr(aHost.BeginReading(), &prAddr);
if (status != PR_SUCCESS) {
FireInternalError(this, __LINE__);
return true;
}
mozilla::net::NetAddr addr;
PRNetAddrToNetAddr(&prAddr, &addr);
rv = sock->InitWithAddress(&addr);
}
if (NS_FAILED(rv)) {
FireInternalError(this, __LINE__);
return true;
}
mSocket = sock;
net::NetAddr localAddr;
mSocket->GetAddress(&localAddr);
uint16_t port;
nsCString addr;
rv = ConvertNetAddrToString(localAddr, &addr, &port);
if (NS_FAILED(rv)) {
FireInternalError(this, __LINE__);
return true;
}
// register listener
mSocket->AsyncListen(this);
mozilla::unused <<
PUDPSocketParent::SendCallback(NS_LITERAL_CSTRING("onopen"),
UDPAddressInfo(addr, port),
NS_LITERAL_CSTRING("connected"));
return true;
}
bool
UDPSocketParent::RecvData(const InfallibleTArray<uint8_t> &aData,
const nsCString& aRemoteAddress,
const uint16_t& aPort)
{
NS_ENSURE_TRUE(mSocket, true);
uint32_t count;
nsresult rv = mSocket->Send(aRemoteAddress,
aPort, aData.Elements(),
aData.Length(), &count);
mozilla::unused <<
PUDPSocketParent::SendCallback(NS_LITERAL_CSTRING("onsent"),
UDPSendResult(rv),
NS_LITERAL_CSTRING("connected"));
NS_ENSURE_SUCCESS(rv, true);
NS_ENSURE_TRUE(count > 0, true);
return true;
}
bool
UDPSocketParent::RecvDataWithAddress(const InfallibleTArray<uint8_t>& aData,
const mozilla::net::NetAddr& aAddr)
{
NS_ENSURE_TRUE(mSocket, true);
uint32_t count;
nsresult rv = mSocket->SendWithAddress(&aAddr, aData.Elements(),
aData.Length(), &count);
mozilla::unused <<
PUDPSocketParent::SendCallback(NS_LITERAL_CSTRING("onsent"),
UDPSendResult(rv),
NS_LITERAL_CSTRING("connected"));
NS_ENSURE_SUCCESS(rv, true);
NS_ENSURE_TRUE(count > 0, true);
return true;
}
bool
UDPSocketParent::RecvClose()
{
NS_ENSURE_TRUE(mSocket, true);
nsresult rv = mSocket->Close();
mSocket = nullptr;
NS_ENSURE_SUCCESS(rv, true);
return true;
}
bool
UDPSocketParent::RecvRequestDelete()
{
mozilla::unused << Send__delete__(this);
return true;
}
void
UDPSocketParent::ActorDestroy(ActorDestroyReason why)
{
MOZ_ASSERT(mIPCOpen);
mIPCOpen = false;
if (mSocket) {
mSocket->Close();
}
mSocket = nullptr;
}
// nsIUDPSocketListener
NS_IMETHODIMP
UDPSocketParent::OnPacketReceived(nsIUDPSocket* aSocket, nsIUDPMessage* aMessage)
{
// receiving packet from remote host, forward the message content to child process
if (!mIPCOpen) {
return NS_OK;
}
uint16_t port;
nsCString ip;
nsCOMPtr<nsINetAddr> fromAddr;
aMessage->GetFromAddr(getter_AddRefs(fromAddr));
fromAddr->GetPort(&port);
fromAddr->GetAddress(ip);
nsCString data;
aMessage->GetData(data);
const char* buffer = data.get();
uint32_t len = data.Length();
FallibleTArray<uint8_t> fallibleArray;
if (!fallibleArray.InsertElementsAt(0, buffer, len)) {
FireInternalError(this, __LINE__);
return NS_ERROR_OUT_OF_MEMORY;
}
InfallibleTArray<uint8_t> infallibleArray;
infallibleArray.SwapElements(fallibleArray);
// compose callback
mozilla::unused <<
PUDPSocketParent::SendCallback(NS_LITERAL_CSTRING("ondata"),
UDPMessage(ip, port, infallibleArray),
NS_LITERAL_CSTRING("connected"));
return NS_OK;
}
NS_IMETHODIMP
UDPSocketParent::OnStopListening(nsIUDPSocket* aSocket, nsresult aStatus)
{
// underlying socket is dead, send state update to child process
if (mIPCOpen) {
mozilla::unused <<
PUDPSocketParent::SendCallback(NS_LITERAL_CSTRING("onclose"),
mozilla::void_t(),
NS_LITERAL_CSTRING("closed"));
}
return NS_OK;
}
} // namespace dom
} // namespace mozilla

Просмотреть файл

@ -0,0 +1,45 @@
/* 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_UDPSocketParent_h__
#define mozilla_dom_UDPSocketParent_h__
#include "mozilla/net/PUDPSocketParent.h"
#include "nsCOMPtr.h"
#include "nsIUDPSocket.h"
namespace mozilla {
namespace dom {
class UDPSocketParent : public mozilla::net::PUDPSocketParent
, public nsIUDPSocketListener
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSOCKETLISTENER
UDPSocketParent() : mIPCOpen(true) {}
virtual ~UDPSocketParent();
bool Init(const nsCString& aHost, const uint16_t aPort);
virtual bool RecvClose() MOZ_OVERRIDE;
virtual bool RecvData(const InfallibleTArray<uint8_t>& aData,
const nsCString& aRemoteAddress,
const uint16_t& aPort) MOZ_OVERRIDE;
virtual bool RecvDataWithAddress( const InfallibleTArray<uint8_t>& data,
const mozilla::net::NetAddr& addr);
virtual bool RecvRequestDelete() MOZ_OVERRIDE;
private:
virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
bool mIPCOpen;
nsCOMPtr<nsIUDPSocket> mSocket;
};
} // namespace dom
} // namespace mozilla
#endif // !defined(mozilla_dom_UDPSocketParent_h__)

Просмотреть файл

@ -11,6 +11,8 @@ EXPORTS.mozilla.dom.network += [
'TCPSocketChild.h',
'TCPSocketParent.h',
'Types.h',
'UDPSocketChild.h',
'UDPSocketParent.h',
]
SOURCES += [
@ -19,6 +21,8 @@ SOURCES += [
'TCPServerSocketParent.cpp',
'TCPSocketChild.cpp',
'TCPSocketParent.cpp',
'UDPSocketChild.cpp',
'UDPSocketParent.cpp',
]
if CONFIG['MOZ_B2G_RIL']:
@ -56,6 +60,7 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
IPDL_SOURCES += [
'PTCPServerSocket.ipdl',
'PTCPSocket.ipdl',
'PUDPSocket.ipdl',
]
FAIL_ON_WARNINGS = True

Просмотреть файл

@ -0,0 +1,9 @@
Components.utils.import("resource://gre/modules/Services.jsm");
function run_test() {
Services.prefs.setBoolPref('media.peerconnection.ipc.enabled', true);
run_test_in_child("/udpsocket_child.js", function() {
Services.prefs.clearUserPref('media.peerconnection.ipc.enabled');
do_test_finished();
});
}

Просмотреть файл

@ -0,0 +1,164 @@
/* -*- Mode: Java; 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/. */
'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');
const SERVER_PORT = 12345;
const DATA_ARRAY = [0, 255, 254, 0, 1, 2, 3, 0, 255, 255, 254, 0];
function UDPSocketInternalImpl() {
}
UDPSocketInternalImpl.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIUDPSocketInternal]),
callListenerError: function(type, message, filename, lineNumber, columnNumber) {
if (this.onerror) {
this.onerror();
} else {
do_throw('Received unexpected error: ' + message + ' at ' + filename +
':' + lineNumber + ':' + columnNumber);
}
},
callListenerReceivedData: function(type, host, port, data, dataLength) {
do_print('*** recv data(' + dataLength + ')=' + data.join() + '\n');
if (this.ondata) {
try {
this.ondata(data, dataLength);
} catch(ex) {
if (ex === Cr.NS_ERROR_ABORT)
throw ex;
do_print('Caught exception: ' + ex + '\n' + ex.stack);
do_throw('test is broken; bad ondata handler; see above');
}
} else {
do_throw('Received ' + dataLength + ' bytes of unexpected data!');
}
},
callListenerVoid: function(type) {
switch (type) {
case 'onopen':
if (this.onopen) {
this.onopen();
}
break;
case 'onclose':
if (this.onclose) {
this.onclose();
}
break;
}
},
callListenerSent: function(type, value) {
if (value != Cr.NS_OK) {
do_throw('Previous send was failed with cause: ' + value);
}
},
updateReadyState: function(readyState) {
do_print('*** current state: ' + readyState + '\n');
},
onopen: function() {},
onclose: function() {},
};
function makeSuccessCase(name) {
return function() {
do_print('got expected: ' + name);
run_next_test();
};
}
function makeJointSuccess(names) {
let funcs = {}, successCount = 0;
names.forEach(function(name) {
funcs[name] = function() {
do_print('got excepted: ' + name);
if (++successCount === names.length)
run_next_test();
};
});
return funcs;
}
function makeExpectedData(expectedData, callback) {
return function(receivedData, receivedDataLength) {
if (receivedDataLength != expectedData.length) {
do_throw('Received data size mismatched, expected ' + expectedData.length +
' but got ' + receivedDataLength);
}
for (let i = 0; i < receivedDataLength; i++) {
if (receivedData[i] != expectedData[i]) {
do_throw('Received mismatched data at position ' + i);
}
}
if (callback) {
callback();
} else {
run_next_test();
}
};
}
function makeFailureCase(name) {
return function() {
let argstr;
if (arguments.length) {
argstr = '(args: ' +
Array.map(arguments, function(x) {return x.data + ""; }).join(" ") + ')';
} else {
argstr = '(no arguments)';
}
do_throw('got unexpected: ' + name + ' ' + argstr);
};
}
function createSocketChild() {
return Cc['@mozilla.org/udp-socket-child;1']
.createInstance(Ci.nsIUDPSocketChild);
}
var UDPSocket = createSocketChild();
var callback = new UDPSocketInternalImpl();
function connectSock() {
UDPSocket.bind(callback, '127.0.0.1', SERVER_PORT);
callback.onopen = makeSuccessCase('open');
}
function sendData() {
UDPSocket.send('127.0.0.1', SERVER_PORT, DATA_ARRAY, DATA_ARRAY.length);
callback.ondata = makeExpectedData(DATA_ARRAY);
}
function clientClose() {
UDPSocket.close();
callback.ondata = makeFailureCase('data');
callback.onclose = makeSuccessCase('close');
}
function connectError() {
UDPSocket = createSocketChild();
UDPSocket.bind(callback, 'some non-IP string', SERVER_PORT);
callback.onerror = makeSuccessCase('error');
callback.onopen = makeFailureCase('open');
}
function cleanup() {
UDPSocket = null;
run_next_test();
}
add_test(connectSock);
add_test(sendData);
add_test(clientClose);
add_test(connectError);
add_test(cleanup);
function run_test() {
run_next_test();
}

Просмотреть файл

@ -1,7 +1,10 @@
[DEFAULT]
head =
tail =
support-files =
udpsocket_child.js
[test_tcpsocket_ipc.js]
[test_tcpserversocket_ipc.js]
[test_udpsocket_ipc.js]
run-sequentially = Uses hardcoded port, bug 903830.

Просмотреть файл

@ -1434,7 +1434,7 @@ this.PushService = {
return;
}
this._udpServer = Cc["@mozilla.org/network/server-socket-udp;1"]
this._udpServer = Cc["@mozilla.org/network/socket-udp;1"]
.createInstance(Ci.nsIUDPServerSocket);
this._udpServer.init(-1, false);
this._udpServer.asyncListen(this);

Просмотреть файл

@ -479,12 +479,6 @@ AudioManager::SetPhoneState(int32_t aState)
obs->NotifyObservers(nullptr, "phone-state-changed", state.get());
}
// follow the switch audio path logic for android, Bug 897364
int usage;
GetForceForUse(nsIAudioManager::USE_COMMUNICATION, &usage);
if (aState == PHONE_STATE_NORMAL && usage == nsIAudioManager::FORCE_BT_SCO) {
SetForceForUse(nsIAudioManager::USE_COMMUNICATION, nsIAudioManager::FORCE_NONE);
}
#if ANDROID_VERSION < 17
if (AudioSystem::setPhoneState(aState)) {
#else

Просмотреть файл

@ -2389,6 +2389,7 @@ this.GECKO_CARDSTATE_CORPORATE_PUK_REQUIRED = "corporatePukRequired";
this.GECKO_CARDSTATE_SERVICE_PROVIDER_PUK_REQUIRED = "serviceProviderPukRequired";
this.GECKO_CARDSTATE_SIM_PUK_REQUIRED = "simPersonalizationPukRequired";
this.GECKO_CARDSTATE_READY = "ready";
this.GECKO_CARDSTATE_PERMANENT_BLOCKED = "permanentBlocked";
this.GECKO_CARDLOCK_PIN = "pin";
this.GECKO_CARDLOCK_PIN2 = "pin2";

Просмотреть файл

@ -3013,6 +3013,12 @@ let RIL = {
newCardState = GECKO_CARDSTATE_UNKNOWN;
}
let pin1State = app.pin1_replaced ? iccStatus.universalPINState :
app.pin1;
if (pin1State === CARD_PINSTATE_ENABLED_PERM_BLOCKED) {
newCardState = GECKO_CARDSTATE_PERMANENT_BLOCKED;
}
if (this.cardState == newCardState) {
return;
}

Просмотреть файл

@ -1701,6 +1701,41 @@ add_test(function test_card_app_state() {
run_next_test();
});
/**
* Verify permanent blocked for ICC.
*/
add_test(function test_icc_permanent_blocked() {
let worker = newUint8Worker();
let ril = worker.RIL;
function testPermanentBlocked(pin1_replaced, universalPINState, pin1) {
let iccStatus = {
gsmUmtsSubscriptionAppIndex: 0,
universalPINState: universalPINState,
apps: [
{
pin1_replaced: pin1_replaced,
pin1: pin1
}]
};
ril._processICCStatus(iccStatus);
do_check_eq(ril.cardState, GECKO_CARDSTATE_PERMANENT_BLOCKED);
}
testPermanentBlocked(1,
CARD_PINSTATE_ENABLED_PERM_BLOCKED,
CARD_PINSTATE_UNKNOWN);
testPermanentBlocked(1,
CARD_PINSTATE_ENABLED_PERM_BLOCKED,
CARD_PINSTATE_ENABLED_PERM_BLOCKED);
testPermanentBlocked(0,
CARD_PINSTATE_UNKNOWN,
CARD_PINSTATE_ENABLED_PERM_BLOCKED);
run_next_test();
});
/**
* Verify iccSetCardLock - Facility Lock.
*/

Просмотреть файл

@ -7,21 +7,21 @@
[ChromeOnly, Constructor, JSImplementation="@mozilla.org/contactAddress;1"]
interface ContactAddress {
attribute object? type; // DOMString[]
[TreatUndefinedAs=Null] attribute DOMString? streetAddress;
[TreatUndefinedAs=Null] attribute DOMString? locality;
[TreatUndefinedAs=Null] attribute DOMString? region;
[TreatUndefinedAs=Null] attribute DOMString? postalCode;
[TreatUndefinedAs=Null] attribute DOMString? countryName;
attribute DOMString? streetAddress;
attribute DOMString? locality;
attribute DOMString? region;
attribute DOMString? postalCode;
attribute DOMString? countryName;
attribute boolean? pref;
[ChromeOnly]
void initialize(optional sequence<DOMString>? type,
optional DOMString streetAddress,
optional DOMString locality,
optional DOMString region,
optional DOMString postalCode,
optional DOMString countryName,
optional boolean pref);
optional DOMString? streetAddress,
optional DOMString? locality,
optional DOMString? region,
optional DOMString? postalCode,
optional DOMString? countryName,
optional boolean? pref);
object toJSON();
};
@ -40,13 +40,13 @@ dictionary ContactAddressInit {
[ChromeOnly, Constructor, JSImplementation="@mozilla.org/contactField;1"]
interface ContactField {
attribute object? type; // DOMString[]
[TreatUndefinedAs=Null] attribute DOMString? value;
attribute DOMString? value;
attribute boolean? pref;
[ChromeOnly]
void initialize(optional sequence<DOMString>? type,
optional DOMString value,
optional boolean pref);
optional DOMString? value,
optional boolean? pref);
object toJSON();
};
@ -60,13 +60,13 @@ dictionary ContactFieldInit {
[ChromeOnly, Constructor, JSImplementation="@mozilla.org/contactTelField;1"]
interface ContactTelField : ContactField {
[TreatUndefinedAs=Null] attribute DOMString? carrier;
attribute DOMString? carrier;
[ChromeOnly]
void initialize(optional sequence<DOMString>? type,
optional DOMString value,
optional DOMString? value,
optional DOMString? carrier,
optional boolean pref);
optional boolean? pref);
object toJSON();
};
@ -117,8 +117,8 @@ interface mozContact {
attribute Date? bday;
attribute Date? anniversary;
[TreatUndefinedAs=Null] attribute DOMString? sex;
[TreatUndefinedAs=Null] attribute DOMString? genderIdentity;
attribute DOMString? sex;
attribute DOMString? genderIdentity;
attribute object? photo;

Просмотреть файл

@ -151,7 +151,7 @@ partial interface Document {
* True if this document is synthetic : stand alone image, video, audio file,
* etc.
*/
[ChromeOnly] readonly attribute boolean mozSyntheticDocument;
[Func="IsChromeOrXBL"] readonly attribute boolean mozSyntheticDocument;
/**
* Returns the script element whose script is currently being processed.
*

Просмотреть файл

@ -92,6 +92,7 @@
#include "mozilla/dom/network/TCPSocketChild.h"
#include "mozilla/dom/network/TCPSocketParent.h"
#include "mozilla/dom/network/TCPServerSocketChild.h"
#include "mozilla/dom/network/UDPSocketChild.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/OSFileConstants.h"
#include "mozilla/Services.h"
@ -251,6 +252,7 @@ using mozilla::dom::quota::QuotaManager;
using mozilla::dom::TCPSocketChild;
using mozilla::dom::TCPSocketParent;
using mozilla::dom::TCPServerSocketChild;
using mozilla::dom::UDPSocketChild;
using mozilla::dom::time::TimeService;
using mozilla::net::StreamingProtocolControllerService;
@ -646,6 +648,7 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(OSFileConstantsService)
NS_GENERIC_FACTORY_CONSTRUCTOR(TCPSocketChild)
NS_GENERIC_FACTORY_CONSTRUCTOR(TCPSocketParent)
NS_GENERIC_FACTORY_CONSTRUCTOR(TCPServerSocketChild)
NS_GENERIC_FACTORY_CONSTRUCTOR(UDPSocketChild)
#ifdef ACCESSIBILITY
#include "nsAccessibilityService.h"
@ -808,6 +811,7 @@ NS_DEFINE_NAMED_CID(NS_ALARMHALSERVICE_CID);
NS_DEFINE_NAMED_CID(TCPSOCKETCHILD_CID);
NS_DEFINE_NAMED_CID(TCPSOCKETPARENT_CID);
NS_DEFINE_NAMED_CID(TCPSERVERSOCKETCHILD_CID);
NS_DEFINE_NAMED_CID(UDPSOCKETCHILD_CID);
NS_DEFINE_NAMED_CID(NS_TIMESERVICE_CID);
NS_DEFINE_NAMED_CID(NS_MEDIASTREAMCONTROLLERSERVICE_CID);
#ifdef MOZ_WIDGET_GONK
@ -1098,6 +1102,7 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
{ &kTCPSOCKETCHILD_CID, false, nullptr, TCPSocketChildConstructor },
{ &kTCPSOCKETPARENT_CID, false, nullptr, TCPSocketParentConstructor },
{ &kTCPSERVERSOCKETCHILD_CID, false, nullptr, TCPServerSocketChildConstructor },
{ &kUDPSOCKETCHILD_CID, false, nullptr, UDPSocketChildConstructor },
{ &kNS_TIMESERVICE_CID, false, nullptr, nsITimeServiceConstructor },
{ &kNS_MEDIASTREAMCONTROLLERSERVICE_CID, false, nullptr, nsIStreamingProtocolControllerServiceConstructor },
#ifdef MOZ_WIDGET_GONK
@ -1255,6 +1260,7 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
{ "@mozilla.org/tcp-socket-child;1", &kTCPSOCKETCHILD_CID },
{ "@mozilla.org/tcp-socket-parent;1", &kTCPSOCKETPARENT_CID },
{ "@mozilla.org/tcp-server-socket-child;1", &kTCPSERVERSOCKETCHILD_CID },
{ "@mozilla.org/udp-socket-child;1", &kUDPSOCKETCHILD_CID },
{ TIMESERVICE_CONTRACTID, &kNS_TIMESERVICE_CID },
{ MEDIASTREAMCONTROLLERSERVICE_CONTRACTID, &kNS_MEDIASTREAMCONTROLLERSERVICE_CID },
#ifdef MOZ_WIDGET_GONK

Просмотреть файл

@ -102,7 +102,9 @@ nrappkit copyright:
#include "nsNetCID.h"
#include "nsISupportsImpl.h"
#include "nsServiceManagerUtils.h"
#include "nsComponentManagerUtils.h"
#include "nsXPCOM.h"
#include "nsXULAppAPI.h"
#include "runnable_utils.h"
extern "C" {
@ -116,6 +118,63 @@ extern "C" {
// Implement the nsISupports ref counting
namespace mozilla {
// NrSocketBase implementation
// async_event APIs
int NrSocketBase::async_wait(int how, NR_async_cb cb, void *cb_arg,
char *function, int line) {
uint16_t flag;
switch (how) {
case NR_ASYNC_WAIT_READ:
flag = PR_POLL_READ;
break;
case NR_ASYNC_WAIT_WRITE:
flag = PR_POLL_WRITE;
break;
default:
return R_BAD_ARGS;
}
cbs_[how] = cb;
cb_args_[how] = cb_arg;
poll_flags_ |= flag;
return 0;
}
int NrSocketBase::cancel(int how) {
uint16_t flag;
switch (how) {
case NR_ASYNC_WAIT_READ:
flag = PR_POLL_READ;
break;
case NR_ASYNC_WAIT_WRITE:
flag = PR_POLL_WRITE;
break;
default:
return R_BAD_ARGS;
}
poll_flags_ &= ~flag;
return 0;
}
void NrSocketBase::fire_callback(int how) {
// This can't happen unless we are armed because we only set
// the flags if we are armed
MOZ_ASSERT(cbs_[how]);
// Now cancel so that we need to be re-armed. Note that
// the re-arming probably happens in the callback we are
// about to fire.
cancel(how);
cbs_[how](this, how, cb_args_[how]);
}
// NrSocket implementation
NS_IMPL_ISUPPORTS0(NrSocket)
@ -139,56 +198,23 @@ void NrSocket::IsLocal(bool *aIsLocal) {
// async_event APIs
int NrSocket::async_wait(int how, NR_async_cb cb, void *cb_arg,
char *function, int line) {
uint16_t flag;
int r = NrSocketBase::async_wait(how, cb, cb_arg, function, line);
switch (how) {
case NR_ASYNC_WAIT_READ:
flag = PR_POLL_READ;
break;
case NR_ASYNC_WAIT_WRITE:
flag = PR_POLL_WRITE;
break;
default:
return R_BAD_ARGS;
if (!r) {
mPollFlags = poll_flags();
}
cbs_[how] = cb;
cb_args_[how] = cb_arg;
mPollFlags |= flag;
return 0;
return r;
}
int NrSocket::cancel(int how) {
uint16_t flag;
int r = NrSocketBase::cancel(how);
switch (how) {
case NR_ASYNC_WAIT_READ:
flag = PR_POLL_READ;
break;
case NR_ASYNC_WAIT_WRITE:
flag = PR_POLL_WRITE;
break;
default:
return R_BAD_ARGS;
if (!r) {
mPollFlags = poll_flags();
}
mPollFlags &= ~flag;
return 0;
}
void NrSocket::fire_callback(int how) {
// This can't happen unless we are armed because we only set
// the flags if we are armed
MOZ_ASSERT(cbs_[how]);
// Now cancel so that we need to be re-armed. Note that
// the re-arming probably happens in the callback we are
// about to fire.
cancel(how);
cbs_[how](this, how, cb_args_[how]);
return r;
}
// Helper functions for addresses
@ -240,6 +266,54 @@ static int nr_transport_addr_to_praddr(nr_transport_addr *addr,
return(_status);
}
//XXX schien@mozilla.com: copy from PRNetAddrToNetAddr,
// should be removed after fix the link error in signaling_unittests
static int praddr_to_netaddr(const PRNetAddr *prAddr, net::NetAddr *addr)
{
int _status;
switch (prAddr->raw.family) {
case PR_AF_INET:
addr->inet.family = AF_INET;
addr->inet.port = prAddr->inet.port;
addr->inet.ip = prAddr->inet.ip;
break;
case PR_AF_INET6:
addr->inet6.family = AF_INET6;
addr->inet6.port = prAddr->ipv6.port;
addr->inet6.flowinfo = prAddr->ipv6.flowinfo;
memcpy(&addr->inet6.ip, &prAddr->ipv6.ip, sizeof(addr->inet6.ip.u8));
addr->inet6.scope_id = prAddr->ipv6.scope_id;
break;
default:
MOZ_ASSERT(false);
ABORT(R_BAD_ARGS);
}
_status = 0;
abort:
return(_status);
}
static int nr_transport_addr_to_netaddr(nr_transport_addr *addr,
net::NetAddr *naddr)
{
int r, _status;
PRNetAddr praddr;
if((r = nr_transport_addr_to_praddr(addr, &praddr))) {
ABORT(r);
}
if((r = praddr_to_netaddr(&praddr, naddr))) {
ABORT(r);
}
_status = 0;
abort:
return(_status);
}
int nr_netaddr_to_transport_addr(const net::NetAddr *netaddr,
nr_transport_addr *addr)
{
@ -299,6 +373,32 @@ int nr_praddr_to_transport_addr(const PRNetAddr *praddr,
return(_status);
}
/*
* nr_transport_addr_get_addrstring_and_port
* convert nr_transport_addr to IP address string and port number
*/
int nr_transport_addr_get_addrstring_and_port(nr_transport_addr *addr,
nsACString *host, int32_t *port) {
int r, _status;
char addr_string[64];
// We cannot directly use |nr_transport_addr.as_string| because it contains
// more than ip address, therefore, we need to explicity convert it
// from |nr_transport_addr_get_addrstring|.
if ((r=nr_transport_addr_get_addrstring(addr, addr_string, sizeof(addr_string)))) {
ABORT(r);
}
if ((r=nr_transport_addr_get_port(addr, port))) {
ABORT(r);
}
*host = addr_string;
_status=0;
abort:
return(_status);
}
// nr_socket APIs (as member functions)
int NrSocket::create(nr_transport_addr *addr) {
@ -394,7 +494,7 @@ int NrSocket::sendto(const void *msg, size_t len,
if (PR_GetError() == PR_WOULD_BLOCK_ERROR)
ABORT(R_WOULDBLOCK);
r_log_e(LOG_GENERIC, LOG_INFO, "Error in sendto %s", to->as_string);
r_log(LOG_GENERIC, LOG_INFO, "Error in sendto %s", to->as_string);
ABORT(R_IO_ERROR);
}
@ -413,7 +513,7 @@ int NrSocket::recvfrom(void * buf, size_t maxlen,
status = PR_RecvFrom(fd_, buf, maxlen, flags, &nfrom, PR_INTERVAL_NO_WAIT);
if (status <= 0) {
r_log_e(LOG_GENERIC,LOG_ERR,"Error in recvfrom");
r_log(LOG_GENERIC,LOG_ERR,"Error in recvfrom");
ABORT(R_IO_ERROR);
}
*len=status;
@ -438,6 +538,383 @@ void NrSocket::close() {
ASSERT_ON_THREAD(ststhread_);
mCondition = NS_BASE_STREAM_CLOSED;
}
// NrSocketIpc Implementation
NS_IMPL_ISUPPORTS1(NrSocketIpc, nsIUDPSocketInternal)
NrSocketIpc::NrSocketIpc(const nsCOMPtr<nsIEventTarget> &main_thread)
: err_(false),
state_(NR_INIT),
main_thread_(main_thread),
monitor_("NrSocketIpc") {
}
// IUDPSocketInternal interfaces
// callback while error happened in UDP socket operation
NS_IMETHODIMP NrSocketIpc::CallListenerError(const nsACString &type,
const nsACString &message,
const nsACString &filename,
uint32_t line_number,
uint32_t column_number) {
ASSERT_ON_THREAD(main_thread_);
MOZ_ASSERT(type.EqualsLiteral("onerror"));
r_log(LOG_GENERIC, LOG_ERR, "UDP socket error:%s at %s:%d:%d",
message.BeginReading(), filename.BeginReading(),
line_number, column_number);
ReentrantMonitorAutoEnter mon(monitor_);
err_ = true;
monitor_.NotifyAll();
return NS_OK;
}
// callback while receiving UDP packet
NS_IMETHODIMP NrSocketIpc::CallListenerReceivedData(const nsACString &type,
const nsACString &host,
uint16_t port, uint8_t *data,
uint32_t data_length) {
ASSERT_ON_THREAD(main_thread_);
MOZ_ASSERT(type.EqualsLiteral("ondata"));
PRNetAddr addr;
memset(&addr, 0, sizeof(addr));
{
ReentrantMonitorAutoEnter mon(monitor_);
if (PR_SUCCESS != PR_StringToNetAddr(host.BeginReading(), &addr)) {
err_ = true;
MOZ_ASSERT(false, "Failed to convert remote host to PRNetAddr");
return NS_OK;
}
// Use PR_IpAddrNull to avoid address being reset to 0.
if (PR_SUCCESS != PR_SetNetAddr(PR_IpAddrNull, addr.raw.family, port, &addr)) {
err_ = true;
MOZ_ASSERT(false, "Failed to set port in PRNetAddr");
return NS_OK;
}
}
nsAutoPtr<DataBuffer> buf(new DataBuffer(data, data_length));
RefPtr<nr_udp_message> msg(new nr_udp_message(addr, buf));
RUN_ON_THREAD(sts_thread_,
mozilla::WrapRunnable(nsRefPtr<NrSocketIpc>(this),
&NrSocketIpc::recv_callback_s,
msg),
NS_DISPATCH_NORMAL);
return NS_OK;
}
// callback while UDP socket is opened or closed
NS_IMETHODIMP NrSocketIpc::CallListenerVoid(const nsACString &type) {
ASSERT_ON_THREAD(main_thread_);
if (type.EqualsLiteral("onopen")) {
ReentrantMonitorAutoEnter mon(monitor_);
uint16_t port;
if (NS_FAILED(socket_child_->GetLocalPort(&port))) {
err_ = true;
MOZ_ASSERT(false, "Failed to get local port");
return NS_OK;
}
nsAutoCString address;
if(NS_FAILED(socket_child_->GetLocalAddress(address))) {
err_ = true;
MOZ_ASSERT(false, "Failed to get local address");
return NS_OK;
}
PRNetAddr praddr;
if (PR_SUCCESS != PR_InitializeNetAddr(PR_IpAddrAny, port, &praddr)) {
err_ = true;
MOZ_ASSERT(false, "Failed to set port in PRNetAddr");
return NS_OK;
}
if (PR_SUCCESS != PR_StringToNetAddr(address.BeginReading(), &praddr)) {
err_ = true;
MOZ_ASSERT(false, "Failed to convert local host to PRNetAddr");
return NS_OK;
}
nr_transport_addr expected_addr;
if(nr_transport_addr_copy(&expected_addr, &my_addr_)) {
err_ = true;
MOZ_ASSERT(false, "Failed to copy my_addr_");
}
if (nr_praddr_to_transport_addr(&praddr, &my_addr_, 1)) {
err_ = true;
MOZ_ASSERT(false, "Failed to copy local host to my_addr_");
}
if (nr_transport_addr_cmp(&expected_addr, &my_addr_,
NR_TRANSPORT_ADDR_CMP_MODE_ADDR)) {
err_ = true;
MOZ_ASSERT(false, "Address of opened socket is not expected");
}
mon.NotifyAll();
} else if (type.EqualsLiteral("onclose")) {
// Already handled in UpdateReadyState, nothing to do here
} else {
MOZ_ASSERT(false, "Received unexpected event");
}
return NS_OK;
}
// callback while UDP packet is sent
NS_IMETHODIMP NrSocketIpc::CallListenerSent(const nsACString &type,
nsresult result) {
ASSERT_ON_THREAD(main_thread_);
MOZ_ASSERT(type.EqualsLiteral("onsent"));
if (NS_FAILED(result)) {
ReentrantMonitorAutoEnter mon(monitor_);
err_ = true;
}
return NS_OK;
}
// callback for state update after every socket operation
NS_IMETHODIMP NrSocketIpc::UpdateReadyState(const nsACString &readyState) {
ASSERT_ON_THREAD(main_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
if (readyState.EqualsLiteral("closed")) {
MOZ_ASSERT(state_ == NR_CONNECTED || state_ == NR_CLOSING);
state_ = NR_CLOSED;
}
return NS_OK;
}
// nr_socket public APIs
int NrSocketIpc::create(nr_transport_addr *addr) {
ASSERT_ON_THREAD(sts_thread_);
int r, _status;
nsresult rv;
int32_t port;
nsCString host;
ReentrantMonitorAutoEnter mon(monitor_);
if (state_ != NR_INIT) {
ABORT(R_INTERNAL);
}
sts_thread_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
MOZ_ASSERT(false, "Failed to get STS thread");
ABORT(R_INTERNAL);
}
if ((r=nr_transport_addr_get_addrstring_and_port(addr, &host, &port))) {
ABORT(r);
}
// wildcard address will be resolved at NrSocketIpc::CallListenerVoid
if ((r=nr_transport_addr_copy(&my_addr_, addr))) {
ABORT(r);
}
state_ = NR_CONNECTING;
RUN_ON_THREAD(main_thread_,
mozilla::WrapRunnable(nsRefPtr<NrSocketIpc>(this),
&NrSocketIpc::create_m,
host, static_cast<uint16_t>(port)),
NS_DISPATCH_NORMAL);
// Wait until socket creation complete.
mon.Wait();
if (err_) {
ABORT(R_INTERNAL);
}
state_ = NR_CONNECTED;
_status = 0;
abort:
return(_status);
}
int NrSocketIpc::sendto(const void *msg, size_t len, int flags,
nr_transport_addr *to) {
ASSERT_ON_THREAD(sts_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
//If send err happened before, simply return the error.
if (err_) {
return R_IO_ERROR;
}
if (!socket_child_) {
return R_EOD;
}
if (state_ != NR_CONNECTED) {
return R_INTERNAL;
}
int r;
net::NetAddr addr;
if ((r=nr_transport_addr_to_netaddr(to, &addr))) {
return r;
}
nsAutoPtr<DataBuffer> buf(new DataBuffer(static_cast<const uint8_t*>(msg), len));
RUN_ON_THREAD(main_thread_,
mozilla::WrapRunnable(nsRefPtr<NrSocketIpc>(this),
&NrSocketIpc::sendto_m,
addr, buf),
NS_DISPATCH_NORMAL);
return 0;
}
void NrSocketIpc::close() {
ASSERT_ON_THREAD(sts_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
state_ = NR_CLOSING;
RUN_ON_THREAD(main_thread_,
mozilla::WrapRunnable(nsRefPtr<NrSocketIpc>(this),
&NrSocketIpc::close_m),
NS_DISPATCH_NORMAL);
//remove all enqueued messages
std::queue<RefPtr<nr_udp_message> > empty;
std::swap(received_msgs_, empty);
}
int NrSocketIpc::recvfrom(void *buf, size_t maxlen, size_t *len, int flags,
nr_transport_addr *from) {
ASSERT_ON_THREAD(sts_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
int r, _status;
uint32_t consumed_len;
*len = 0;
if (state_ != NR_CONNECTED) {
ABORT(R_INTERNAL);
}
if (received_msgs_.empty()) {
ABORT(R_WOULDBLOCK);
}
{
RefPtr<nr_udp_message> msg(received_msgs_.front());
received_msgs_.pop();
if ((r=nr_praddr_to_transport_addr(&msg->from, from, 0))) {
err_ = true;
MOZ_ASSERT(false, "Get bogus address for received UDP packet");
ABORT(r);
}
consumed_len = std::min(maxlen, msg->data->len());
if (consumed_len < msg->data->len()) {
r_log(LOG_GENERIC, LOG_DEBUG, "Partial received UDP packet will be discard");
}
memcpy(buf, msg->data->data(), consumed_len);
*len = consumed_len;
}
_status = 0;
abort:
return(_status);
}
int NrSocketIpc::getaddr(nr_transport_addr *addrp) {
ASSERT_ON_THREAD(sts_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
if (state_ != NR_CONNECTED) {
return R_INTERNAL;
}
return nr_transport_addr_copy(addrp, &my_addr_);
}
// Main thread executors
void NrSocketIpc::create_m(const nsACString &host, const uint16_t port) {
ASSERT_ON_THREAD(main_thread_);
ReentrantMonitorAutoEnter mon(monitor_);
nsresult rv;
socket_child_ = do_CreateInstance("@mozilla.org/udp-socket-child;1", &rv);
if (NS_FAILED(rv)) {
err_ = true;
MOZ_ASSERT(false, "Failed to create UDPSocketChild");
}
if (NS_FAILED(socket_child_->Bind(this, host, port))) {
err_ = true;
MOZ_ASSERT(false, "Failed to create UDP socket");
}
}
void NrSocketIpc::sendto_m(const net::NetAddr &addr, nsAutoPtr<DataBuffer> buf) {
ASSERT_ON_THREAD(main_thread_);
MOZ_ASSERT(socket_child_);
ReentrantMonitorAutoEnter mon(monitor_);
if (NS_FAILED(socket_child_->SendWithAddress(&addr,
buf->data(),
buf->len()))) {
err_ = true;
}
}
void NrSocketIpc::close_m() {
ASSERT_ON_THREAD(main_thread_);
if (socket_child_) {
socket_child_->Close();
socket_child_ = nullptr;
}
}
void NrSocketIpc::recv_callback_s(RefPtr<nr_udp_message> msg) {
ASSERT_ON_THREAD(sts_thread_);
{
ReentrantMonitorAutoEnter mon(monitor_);
if (state_ != NR_CONNECTED) {
return;
}
}
//enqueue received message
received_msgs_.push(msg);
if ((poll_flags() & PR_POLL_READ)) {
fire_callback(NR_ASYNC_WAIT_READ);
}
}
} // close namespace
@ -462,9 +939,18 @@ static nr_socket_vtbl nr_socket_local_vtbl={
nr_socket_local_close
};
int nr_socket_local_create(nr_transport_addr *addr, nr_socket **sockp) {
NrSocket * sock = new NrSocket();
NrSocketBase *sock = nullptr;
// create IPC bridge for content process
if (XRE_GetProcessType() == GeckoProcessType_Default) {
sock = new NrSocket();
} else {
nsCOMPtr<nsIThread> main_thread;
NS_GetMainThread(getter_AddRefs(main_thread));
sock = new NrSocketIpc(main_thread.get());
}
int r, _status;
r = sock->create(addr);
@ -492,7 +978,7 @@ static int nr_socket_local_destroy(void **objp) {
if(!objp || !*objp)
return 0;
NrSocket *sock = static_cast<NrSocket *>(*objp);
NrSocketBase *sock = static_cast<NrSocketBase *>(*objp);
*objp=0;
sock->close(); // Signal STS that we want not to listen
@ -503,7 +989,7 @@ static int nr_socket_local_destroy(void **objp) {
static int nr_socket_local_sendto(void *obj,const void *msg, size_t len,
int flags, nr_transport_addr *addr) {
NrSocket *sock = static_cast<NrSocket *>(obj);
NrSocketBase *sock = static_cast<NrSocketBase *>(obj);
return sock->sendto(msg, len, flags, addr);
}
@ -511,13 +997,13 @@ static int nr_socket_local_sendto(void *obj,const void *msg, size_t len,
static int nr_socket_local_recvfrom(void *obj,void * restrict buf,
size_t maxlen, size_t *len, int flags,
nr_transport_addr *addr) {
NrSocket *sock = static_cast<NrSocket *>(obj);
NrSocketBase *sock = static_cast<NrSocketBase *>(obj);
return sock->recvfrom(buf, maxlen, len, flags, addr);
}
static int nr_socket_local_getfd(void *obj, NR_SOCKET *fd) {
NrSocket *sock = static_cast<NrSocket *>(obj);
NrSocketBase *sock = static_cast<NrSocketBase *>(obj);
*fd = sock;
@ -525,14 +1011,14 @@ static int nr_socket_local_getfd(void *obj, NR_SOCKET *fd) {
}
static int nr_socket_local_getaddr(void *obj, nr_transport_addr *addrp) {
NrSocket *sock = static_cast<NrSocket *>(obj);
NrSocketBase *sock = static_cast<NrSocketBase *>(obj);
return sock->getaddr(addrp);
}
static int nr_socket_local_close(void *obj) {
NrSocket *sock = static_cast<NrSocket *>(obj);
NrSocketBase *sock = static_cast<NrSocketBase *>(obj);
sock->close();
@ -542,13 +1028,13 @@ static int nr_socket_local_close(void *obj) {
// Implement async api
int NR_async_wait(NR_SOCKET sock, int how, NR_async_cb cb,void *cb_arg,
char *function,int line) {
NrSocket *s = static_cast<NrSocket *>(sock);
NrSocketBase *s = static_cast<NrSocketBase *>(sock);
return s->async_wait(how, cb, cb_arg, function, line);
}
int NR_async_cancel(NR_SOCKET sock,int how) {
NrSocket *s = static_cast<NrSocket *>(sock);
NrSocketBase *s = static_cast<NrSocketBase *>(sock);
return s->cancel(how);
}

Просмотреть файл

@ -46,18 +46,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef nr_socket_prsock__
#define nr_socket_prsock__
#include <vector>
#include <queue>
#include "nspr.h"
#include "prio.h"
#include "nsAutoPtr.h"
#include "nsCOMPtr.h"
#include "nsASocketHandler.h"
#include "nsISocketTransportService.h"
#include "nsXPCOM.h"
#include "nsIEventTarget.h"
#include "nsIUDPSocketChild.h"
#include "databuffer.h"
#include "m_cpp_utils.h"
#include "mozilla/ReentrantMonitor.h"
#include "mozilla/RefPtr.h"
namespace mozilla {
@ -65,13 +70,52 @@ namespace net {
union NetAddr;
}
class NrSocket : public nsASocketHandler {
class NrSocketBase {
public:
NrSocket() : fd_(nullptr) {
memset(&my_addr_, 0, sizeof(my_addr_));
NrSocketBase() : poll_flags_(0) {
memset(cbs_, 0, sizeof(cbs_));
memset(cb_args_, 0, sizeof(cb_args_));
memset(&my_addr_, 0, sizeof(my_addr_));
}
virtual ~NrSocketBase() {}
// the nr_socket APIs
virtual int create(nr_transport_addr *addr) = 0;
virtual int sendto(const void *msg, size_t len,
int flags, nr_transport_addr *to) = 0;
virtual int recvfrom(void * buf, size_t maxlen,
size_t *len, int flags,
nr_transport_addr *from) = 0;
virtual int getaddr(nr_transport_addr *addrp) = 0;
virtual void close() = 0;
// Implementations of the async_event APIs
virtual int async_wait(int how, NR_async_cb cb, void *cb_arg,
char *function, int line);
virtual int cancel(int how);
// nsISupport reference counted interface
NS_IMETHOD_(nsrefcnt) AddRef(void) = 0;
NS_IMETHOD_(nsrefcnt) Release(void) = 0;
uint32_t poll_flags() {
return poll_flags_;
}
protected:
void fire_callback(int how);
nr_transport_addr my_addr_;
private:
NR_async_cb cbs_[NR_ASYNC_WAIT_WRITE + 1];
void *cb_args_[NR_ASYNC_WAIT_WRITE + 1];
uint32_t poll_flags_;
};
class NrSocket : public NrSocketBase,
public nsASocketHandler {
public:
NrSocket() : fd_(nullptr) {}
virtual ~NrSocket() {
PR_Close(fd_);
}
@ -87,36 +131,95 @@ public:
NS_DECL_THREADSAFE_ISUPPORTS
// Implementations of the async_event APIs
int async_wait(int how, NR_async_cb cb, void *cb_arg,
char *function, int line);
int cancel(int how);
virtual int async_wait(int how, NR_async_cb cb, void *cb_arg,
char *function, int line);
virtual int cancel(int how);
// Implementations of the nr_socket APIs
int create(nr_transport_addr *addr); // (really init, but it's called create)
int sendto(const void *msg, size_t len,
int flags, nr_transport_addr *to);
int recvfrom(void * buf, size_t maxlen,
size_t *len, int flags,
nr_transport_addr *from);
int getaddr(nr_transport_addr *addrp);
void close();
virtual int create(nr_transport_addr *addr); // (really init, but it's called create)
virtual int sendto(const void *msg, size_t len,
int flags, nr_transport_addr *to);
virtual int recvfrom(void * buf, size_t maxlen,
size_t *len, int flags,
nr_transport_addr *from);
virtual int getaddr(nr_transport_addr *addrp);
virtual void close();
private:
DISALLOW_COPY_ASSIGN(NrSocket);
void fire_callback(int how);
PRFileDesc *fd_;
nr_transport_addr my_addr_;
NR_async_cb cbs_[NR_ASYNC_WAIT_WRITE + 1];
void *cb_args_[NR_ASYNC_WAIT_WRITE + 1];
nsCOMPtr<nsIEventTarget> ststhread_;
};
struct nr_udp_message {
nr_udp_message(const PRNetAddr &from, nsAutoPtr<DataBuffer> &data)
: from(from), data(data) {
}
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nr_udp_message);
PRNetAddr from;
nsAutoPtr<DataBuffer> data;
private:
DISALLOW_COPY_ASSIGN(nr_udp_message);
};
class NrSocketIpc : public NrSocketBase,
public nsIUDPSocketInternal {
public:
enum NrSocketIpcState {
NR_INIT,
NR_CONNECTING,
NR_CONNECTED,
NR_CLOSING,
NR_CLOSED,
};
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSOCKETINTERNAL
NrSocketIpc(const nsCOMPtr<nsIEventTarget> &main_thread);
virtual ~NrSocketIpc() {};
// Implementations of the NrSocketBase APIs
virtual int create(nr_transport_addr *addr);
virtual int sendto(const void *msg, size_t len,
int flags, nr_transport_addr *to);
virtual int recvfrom(void * buf, size_t maxlen,
size_t *len, int flags,
nr_transport_addr *from);
virtual int getaddr(nr_transport_addr *addrp);
virtual void close();
private:
DISALLOW_COPY_ASSIGN(NrSocketIpc);
// Main thread executors of the NrSocketBase APIs
void create_m(const nsACString &host, const uint16_t port);
void sendto_m(const net::NetAddr &addr, nsAutoPtr<DataBuffer> buf);
void close_m();
// STS thread executor
void recv_callback_s(RefPtr<nr_udp_message> msg);
bool err_;
NrSocketIpcState state_;
std::queue<RefPtr<nr_udp_message> > received_msgs_;
nsCOMPtr<nsIUDPSocketChild> socket_child_;
nsCOMPtr<nsIEventTarget> sts_thread_;
const nsCOMPtr<nsIEventTarget> main_thread_;
ReentrantMonitor monitor_;
};
int nr_netaddr_to_transport_addr(const net::NetAddr *netaddr,
nr_transport_addr *addr);
int nr_praddr_to_transport_addr(const PRNetAddr *praddr,
nr_transport_addr *addr, int keep);
int nr_transport_addr_get_addrstring_and_port(nr_transport_addr *addr,
nsACString *host, int32_t *port);
} // close namespace
#endif

Просмотреть файл

@ -712,7 +712,7 @@ abstract public class BrowserApp extends GeckoApp
if (itemId == R.id.subscribe) {
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab != null && tab.getFeedsEnabled()) {
if (tab != null && tab.hasFeeds()) {
JSONObject args = new JSONObject();
try {
args.put("tabId", tab.getId());
@ -724,6 +724,21 @@ abstract public class BrowserApp extends GeckoApp
return true;
}
if (itemId == R.id.add_search_engine) {
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab != null && tab.hasOpenSearch()) {
JSONObject args = new JSONObject();
try {
args.put("tabId", tab.getId());
} catch (JSONException e) {
Log.e(LOGTAG, "error building json arguments");
return true;
}
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("SearchEngines:Add", args.toString()));
}
return true;
}
if (itemId == R.id.copyurl) {
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab != null) {

Просмотреть файл

@ -377,15 +377,19 @@ public class BrowserToolbar extends GeckoRelativeLayout
menu.findItem(R.id.share).setVisible(false);
menu.findItem(R.id.add_to_launcher).setVisible(false);
}
if (!tab.getFeedsEnabled()) {
if (!tab.hasFeeds()) {
menu.findItem(R.id.subscribe).setVisible(false);
}
menu.findItem(R.id.add_search_engine).setVisible(tab.hasOpenSearch());
} else {
// if there is no tab, remove anything tab dependent
menu.findItem(R.id.copyurl).setVisible(false);
menu.findItem(R.id.share).setVisible(false);
menu.findItem(R.id.add_to_launcher).setVisible(false);
menu.findItem(R.id.subscribe).setVisible(false);
menu.findItem(R.id.add_search_engine).setVisible(false);
}
menu.findItem(R.id.share).setVisible(!GeckoProfile.get(getContext()).inGuestMode());

Просмотреть файл

@ -13,6 +13,7 @@ import org.mozilla.gecko.util.HardwareUtils;
import org.mozilla.gecko.util.GeckoEventListener;
import org.mozilla.gecko.util.ThreadUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
@ -29,11 +30,18 @@ import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GeckoView extends LayerView
implements GeckoEventListener, ContextGetter {
private static final String LOGTAG = "GeckoView";
private ChromeDelegate mChromeDelegate;
private ContentDelegate mContentDelegate;
public GeckoView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GeckoView);
@ -76,7 +84,15 @@ public class GeckoView extends LayerView
Tabs tabs = Tabs.getInstance();
tabs.attachToContext(context);
}
GeckoAppShell.registerEventListener("Gecko:Ready", this);
GeckoAppShell.registerEventListener("Content:StateChange", this);
GeckoAppShell.registerEventListener("Content:LoadError", this);
GeckoAppShell.registerEventListener("Content:PageShow", this);
GeckoAppShell.registerEventListener("DOMTitleChanged", this);
GeckoAppShell.registerEventListener("Link:Favicon", this);
GeckoAppShell.registerEventListener("Prompt:Show", this);
GeckoAppShell.registerEventListener("Prompt:ShowTop", this);
ThreadUtils.setUiThread(Thread.currentThread(), new Handler());
initializeView(GeckoAppShell.getEventDispatcher());
@ -90,28 +106,193 @@ public class GeckoView extends LayerView
}
}
public void loadUrl(String uri) {
Tabs.getInstance().loadUrl(uri);
/**
* Add a Browser to the GeckoView container.
* @param url The URL resource to load into the new Browser.
*/
public Browser addBrowser(String url) {
Tab tab = Tabs.getInstance().loadUrl(url, Tabs.LOADURL_NEW_TAB);
if (tab != null) {
return new Browser(tab.getId());
}
return null;
}
public void loadUrlInNewTab(String uri) {
Tabs.getInstance().loadUrl(uri, Tabs.LOADURL_NEW_TAB);
}
public void handleMessage(String event, JSONObject message) {
if (event.equals("Gecko:Ready")) {
GeckoThread.setLaunchState(GeckoThread.LaunchState.GeckoRunning);
Tab selectedTab = Tabs.getInstance().getSelectedTab();
if (selectedTab != null)
Tabs.getInstance().notifyListeners(selectedTab, Tabs.TabEvents.SELECTED);
geckoConnected();
GeckoAppShell.setLayerClient(getLayerClient());
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Viewport:Flush", null));
show();
requestRender();
/**
* Remove a Browser from the GeckoView container.
* @param browser The Browser to remove.
*/
public void removeBrowser(Browser browser) {
Tab tab = Tabs.getInstance().getTab(browser.getId());
if (tab != null) {
Tabs.getInstance().closeTab(tab);
}
}
/**
* Set the active/visible Browser.
* @param browser The Browser to make selected.
*/
public void setCurrentBrowser(Browser browser) {
Tab tab = Tabs.getInstance().getTab(browser.getId());
if (tab != null) {
Tabs.getInstance().selectTab(tab.getId());
}
}
/**
* Get the active/visible Browser.
* @return The current selected Browser.
*/
public Browser getCurrentBrowser() {
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab != null) {
return new Browser(tab.getId());
}
return null;
}
/**
* Get the list of current Browsers in the GeckoView container.
* @return An unmodifiable List of Browser objects.
*/
public List<Browser> getBrowsers() {
ArrayList<Browser> browsers = new ArrayList<Browser>();
Iterable<Tab> tabs = Tabs.getInstance().getTabsInOrder();
for (Tab tab : tabs) {
browsers.add(new Browser(tab.getId()));
}
return Collections.unmodifiableList(browsers);
}
/**
* Not part of the public API. Ignore.
*/
public void handleMessage(final String event, final JSONObject message) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
try {
if (event.equals("Gecko:Ready")) {
GeckoView.this.handleReady(message);
} else if (event.equals("Content:StateChange")) {
GeckoView.this.handleStateChange(message);
} else if (event.equals("Content:LoadError")) {
GeckoView.this.handleLoadError(message);
} else if (event.equals("Content:PageShow")) {
GeckoView.this.handlePageShow(message);
} else if (event.equals("DOMTitleChanged")) {
GeckoView.this.handleTitleChanged(message);
} else if (event.equals("Link:Favicon")) {
GeckoView.this.handleLinkFavicon(message);
} else if (event.equals("Prompt:Show") || event.equals("Prompt:ShowTop")) {
GeckoView.this.handlePrompt(message);
}
} catch (Exception e) {
Log.w(LOGTAG, "handleMessage threw for " + event, e);
}
}
});
}
private void handleReady(final JSONObject message) {
GeckoThread.setLaunchState(GeckoThread.LaunchState.GeckoRunning);
Tab selectedTab = Tabs.getInstance().getSelectedTab();
if (selectedTab != null)
Tabs.getInstance().notifyListeners(selectedTab, Tabs.TabEvents.SELECTED);
geckoConnected();
GeckoAppShell.setLayerClient(getLayerClient());
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Viewport:Flush", null));
show();
requestRender();
if (mChromeDelegate != null) {
mChromeDelegate.onReady(this);
}
}
private void handleStateChange(final JSONObject message) throws JSONException {
int state = message.getInt("state");
if ((state & GeckoAppShell.WPL_STATE_IS_NETWORK) != 0) {
if ((state & GeckoAppShell.WPL_STATE_START) != 0) {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onPageStart(this, new Browser(id), message.getString("uri"));
}
} else if ((state & GeckoAppShell.WPL_STATE_STOP) != 0) {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onPageStop(this, new Browser(id), message.getBoolean("success"));
}
}
}
}
private void handleLoadError(final JSONObject message) throws JSONException {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onPageStop(GeckoView.this, new Browser(id), false);
}
}
private void handlePageShow(final JSONObject message) throws JSONException {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onPageShow(GeckoView.this, new Browser(id));
}
}
private void handleTitleChanged(final JSONObject message) throws JSONException {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onReceivedTitle(GeckoView.this, new Browser(id), message.getString("title"));
}
}
private void handleLinkFavicon(final JSONObject message) throws JSONException {
if (mContentDelegate != null) {
int id = message.getInt("tabID");
mContentDelegate.onReceivedFavicon(GeckoView.this, new Browser(id), message.getString("href"), message.getInt("size"));
}
}
private void handlePrompt(final JSONObject message) throws JSONException {
if (mChromeDelegate != null) {
String hint = message.optString("hint");
if ("alert".equals(hint)) {
String text = message.optString("text");
mChromeDelegate.onAlert(GeckoView.this, null, text, new PromptResult(message.optString("guid")));
} else if ("confirm".equals(hint)) {
String text = message.optString("text");
mChromeDelegate.onConfirm(GeckoView.this, null, text, new PromptResult(message.optString("guid")));
} else if ("prompt".equals(hint)) {
String text = message.optString("text");
String defaultValue = message.optString("textbox0");
mChromeDelegate.onPrompt(GeckoView.this, null, text, defaultValue, new PromptResult(message.optString("guid")));
} else if ("remotedebug".equals(hint)) {
mChromeDelegate.onDebugRequest(GeckoView.this, new PromptResult(message.optString("guid")));
}
}
}
/**
* Set the chrome callback handler.
* This will replace the current handler.
* @param chrome An implementation of GeckoViewChrome.
*/
public void setChromeDelegate(ChromeDelegate chrome) {
mChromeDelegate = chrome;
}
/**
* Set the content callback handler.
* This will replace the current handler.
* @param content An implementation of ContentDelegate.
*/
public void setContentDelegate(ContentDelegate content) {
mContentDelegate = content;
}
public static void setGeckoInterface(final BaseGeckoInterface geckoInterface) {
GeckoAppShell.setGeckoInterface(geckoInterface);
}
@ -119,4 +300,255 @@ public class GeckoView extends LayerView
public static GeckoAppShell.GeckoInterface getGeckoInterface() {
return GeckoAppShell.getGeckoInterface();
}
/**
* Wrapper for a browser in the GeckoView container. Associated with a browser
* element in the Gecko system.
*/
public class Browser {
private final int mId;
private Browser(int Id) {
mId = Id;
}
/**
* Get the ID of the Browser. This is the same ID used by Gecko for it's underlying
* browser element.
* @return The integer ID of the Browser.
*/
private int getId() {
return mId;
}
/**
* Load a URL resource into the Browser.
* @param url The URL string.
*/
public void loadUrl(String url) {
JSONObject args = new JSONObject();
try {
args.put("url", url);
args.put("parentId", -1);
args.put("newTab", false);
args.put("tabID", mId);
} catch (Exception e) {
Log.w(LOGTAG, "Error building JSON arguments for loadUrl.", e);
}
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Tab:Load", args.toString()));
}
/**
* Reload the current URL resource into the Browser. The URL is force loaded from the
* network and is not pulled from cache.
*/
public void reload() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
tab.doReload();
}
}
/**
* Stop the current loading operation.
*/
public void stop() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
tab.doStop();
}
}
/**
* Check to see if the Browser has session history and can go back to a
* previous page.
* @return A boolean flag indicating if previous session exists.
* This method will likely be removed and replaced by a callback in GeckoViewContent
*/
public boolean canGoBack() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
return tab.canDoBack();
}
return false;
}
/**
* Move backward in the session history, if that's possible.
*/
public void goBack() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
tab.doBack();
}
}
/**
* Check to see if the Browser has session history and can go forward to a
* new page.
* @return A boolean flag indicating if forward session exists.
* This method will likely be removed and replaced by a callback in GeckoViewContent
*/
public boolean canGoForward() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
return tab.canDoForward();
}
return false;
}
/**
* Move forward in the session history, if that's possible.
*/
public void goForward() {
Tab tab = Tabs.getInstance().getTab(mId);
if (tab != null) {
tab.doForward();
}
}
}
/* Provides a means for the client to indicate whether a JavaScript
* dialog request should proceed. An instance of this class is passed to
* various GeckoViewChrome callback actions.
*/
public class PromptResult {
private final int RESULT_OK = 0;
private final int RESULT_CANCEL = 1;
private final String mGUID;
public PromptResult(String guid) {
mGUID = guid;
}
private JSONObject makeResult(int resultCode) {
JSONObject result = new JSONObject();
try {
result.put("guid", mGUID);
result.put("button", resultCode);
} catch(JSONException ex) { }
return result;
}
/**
* Handle a confirmation response from the user.
*/
public void confirm() {
JSONObject result = makeResult(RESULT_OK);
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Prompt:Reply", result.toString()));
}
/**
* Handle a confirmation response from the user.
* @param value String value to return to the browser context.
*/
public void confirmWithValue(String value) {
JSONObject result = makeResult(RESULT_OK);
try {
result.put("textbox0", value);
} catch(JSONException ex) { }
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Prompt:Reply", result.toString()));
}
/**
* Handle a cancellation response from the user.
*/
public void cancel() {
JSONObject result = makeResult(RESULT_CANCEL);
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Prompt:Reply", result.toString()));
}
}
public interface ChromeDelegate {
/**
* Tell the host application that Gecko is ready to handle requests.
* @param view The GeckoView that initiated the callback.
*/
public void onReady(GeckoView view);
/**
* Tell the host application to display an alert dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onAlert(GeckoView view, GeckoView.Browser browser, String message, GeckoView.PromptResult result);
/**
* Tell the host application to display a confirmation dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onConfirm(GeckoView view, GeckoView.Browser browser, String message, GeckoView.PromptResult result);
/**
* Tell the host application to display an input prompt dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param defaultValue The string to use as default input.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onPrompt(GeckoView view, GeckoView.Browser browser, String message, String defaultValue, GeckoView.PromptResult result);
/**
* Tell the host application to display a remote debugging request dialog.
* @param view The GeckoView that initiated the callback.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onDebugRequest(GeckoView view, GeckoView.PromptResult result);
}
public interface ContentDelegate {
/**
* A Browser has started loading content from the network.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param url The resource being loaded.
*/
public void onPageStart(GeckoView view, GeckoView.Browser browser, String url);
/**
* A Browser has finished loading content from the network.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that was loading the content.
* @param success Whether the page loaded successfully or an error occured.
*/
public void onPageStop(GeckoView view, GeckoView.Browser browser, boolean success);
/**
* A Browser is displaying content. This page could have been loaded via
* network or from the session history.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
*/
public void onPageShow(GeckoView view, GeckoView.Browser browser);
/**
* A page title was discovered in the content or updated after the content
* loaded.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
* @param title The title sent from the content.
*/
public void onReceivedTitle(GeckoView view, GeckoView.Browser browser, String title);
/**
* A link element was discovered in the content or updated after the content
* loaded that specifies a favicon.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
* @param url The href of the link element specifying the favicon.
* @param size The maximum size specified for the favicon, or -1 for any size.
*/
public void onReceivedFavicon(GeckoView view, GeckoView.Browser browser, String url, int size);
}
}

Просмотреть файл

@ -0,0 +1,61 @@
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* 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/. */
package org.mozilla.gecko;
public class GeckoViewChrome implements GeckoView.ChromeDelegate {
/**
* Tell the host application that Gecko is ready to handle requests.
* @param view The GeckoView that initiated the callback.
*/
public void onReady(GeckoView view) {}
/**
* Tell the host application to display an alert dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onAlert(GeckoView view, GeckoView.Browser browser, String message, GeckoView.PromptResult result) {
result.cancel();
}
/**
* Tell the host application to display a confirmation dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onConfirm(GeckoView view, GeckoView.Browser browser, String message, GeckoView.PromptResult result) {
result.cancel();
}
/**
* Tell the host application to display an input prompt dialog.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param message The string to display in the dialog.
* @param defaultValue The string to use as default input.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onPrompt(GeckoView view, GeckoView.Browser browser, String message, String defaultValue, GeckoView.PromptResult result) {
result.cancel();
}
/**
* Tell the host application to display a remote debugging request dialog.
* @param view The GeckoView that initiated the callback.
* @param result A PromptResult used to send back the result without blocking.
* Defaults to cancel requests.
*/
public void onDebugRequest(GeckoView view, GeckoView.PromptResult result) {
result.cancel();
}
}

Просмотреть файл

@ -0,0 +1,51 @@
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* 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/. */
package org.mozilla.gecko;
public class GeckoViewContent implements GeckoView.ContentDelegate {
/**
* A Browser has started loading content from the network.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is loading the content.
* @param url The resource being loaded.
*/
public void onPageStart(GeckoView view, GeckoView.Browser browser, String url) {}
/**
* A Browser has finished loading content from the network.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that was loading the content.
* @param success Whether the page loaded successfully or an error occured.
*/
public void onPageStop(GeckoView view, GeckoView.Browser browser, boolean success) {}
/**
* A Browser is displaying content. This page could have been loaded via
* network or from the session history.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
*/
public void onPageShow(GeckoView view, GeckoView.Browser browser) {}
/**
* A page title was discovered in the content or updated after the content
* loaded.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
* @param title The title sent from the content.
*/
public void onReceivedTitle(GeckoView view, GeckoView.Browser browser, String title) {}
/**
* A link element was discovered in the content or updated after the content
* loaded that specifies a favicon.
* @param view The GeckoView that initiated the callback.
* @param browser The Browser that is showing the content.
* @param url The href of the link element specifying the favicon.
* @param size The maximum size specified for the favicon, or -1 for any size.
*/
public void onReceivedFavicon(GeckoView view, GeckoView.Browser browser, String url, int size) {}
}

Просмотреть файл

@ -43,7 +43,8 @@ public class Tab {
private Bitmap mFavicon;
private String mFaviconUrl;
private int mFaviconSize;
private boolean mFeedsEnabled;
private boolean mHasFeeds;
private boolean mHasOpenSearch;
private JSONObject mIdentityData;
private boolean mReaderEnabled;
private BitmapDrawable mThumbnail;
@ -98,7 +99,8 @@ public class Tab {
mFavicon = null;
mFaviconUrl = null;
mFaviconSize = 0;
mFeedsEnabled = false;
mHasFeeds = false;
mHasOpenSearch = false;
mIdentityData = null;
mReaderEnabled = false;
mEnteringReaderMode = false;
@ -236,8 +238,12 @@ public class Tab {
return mFaviconUrl;
}
public boolean getFeedsEnabled() {
return mFeedsEnabled;
public boolean hasFeeds() {
return mHasFeeds;
}
public boolean hasOpenSearch() {
return mHasOpenSearch;
}
public String getSecurityMode() {
@ -393,8 +399,12 @@ public class Tab {
mFaviconSize = 0;
}
public void setFeedsEnabled(boolean feedsEnabled) {
mFeedsEnabled = feedsEnabled;
public void setHasFeeds(boolean hasFeeds) {
mHasFeeds = hasFeeds;
}
public void setHasOpenSearch(boolean hasOpenSearch) {
mHasOpenSearch = hasOpenSearch;
}
public void updateIdentityData(JSONObject identityData) {
@ -622,7 +632,7 @@ public class Tab {
setContentType(message.getString("contentType"));
clearFavicon();
setFeedsEnabled(false);
setHasFeeds(false);
updateTitle(null);
updateIdentityData(null);
setReaderEnabled(false);

Просмотреть файл

@ -102,6 +102,7 @@ public class Tabs implements GeckoEventListener {
registerEventListener("DOMTitleChanged");
registerEventListener("Link:Favicon");
registerEventListener("Link:Feed");
registerEventListener("Link:OpenSearch");
registerEventListener("DesktopMode:Changed");
registerEventListener("Tab:ViewportMetadata");
}
@ -467,8 +468,11 @@ public class Tabs implements GeckoEventListener {
tab.updateFaviconURL(message.getString("href"), message.getInt("size"));
notifyListeners(tab, TabEvents.LINK_FAVICON);
} else if (event.equals("Link:Feed")) {
tab.setFeedsEnabled(true);
tab.setHasFeeds(true);
notifyListeners(tab, TabEvents.LINK_FEED);
} else if (event.equals("Link:OpenSearch")) {
boolean visible = message.getBoolean("visible");
tab.setHasOpenSearch(visible);
} else if (event.equals("DesktopMode:Changed")) {
tab.setDesktopMode(message.getBoolean("desktopMode"));
notifyListeners(tab, TabEvents.DESKTOP_MODE_CHANGE);

Просмотреть файл

@ -228,6 +228,7 @@ size. -->
<!ENTITY contextmenu_top_sites_edit "Edit">
<!ENTITY contextmenu_top_sites_pin "Pin Site">
<!ENTITY contextmenu_top_sites_unpin "Unpin Site">
<!ENTITY contextmenu_add_search_engine "Add a Search Engine">
<!ENTITY pref_titlebar_mode "Title bar">
<!ENTITY pref_titlebar_mode_title "Show page title">

Просмотреть файл

@ -148,6 +148,8 @@ gbjar.sources += [
'GeckoJavaSampler.java',
'GlobalHistory.java',
'GeckoView.java',
'GeckoViewChrome.java',
'GeckoViewContent.java',
'health/BrowserHealthRecorder.java',
'health/BrowserHealthReporter.java',
'InputMethods.java',

Просмотреть файл

@ -17,6 +17,10 @@
<item android:id="@+id/subscribe"
android:title="@string/contextmenu_subscribe"/>
<item android:id="@+id/add_search_engine"
android:title="@string/contextmenu_add_search_engine"
android:visible="false"/>
<item android:id="@+id/copyurl"
android:title="@string/contextmenu_copyurl"/>

Просмотреть файл

@ -228,6 +228,7 @@
<string name="contextmenu_top_sites_edit">&contextmenu_top_sites_edit;</string>
<string name="contextmenu_top_sites_pin">&contextmenu_top_sites_pin;</string>
<string name="contextmenu_top_sites_unpin">&contextmenu_top_sites_unpin;</string>
<string name="contextmenu_add_search_engine">&contextmenu_add_search_engine;</string>
<string name="pref_titlebar_mode">&pref_titlebar_mode;</string>
<string name="pref_titlebar_mode_title">&pref_titlebar_mode_title;</string>

Просмотреть файл

@ -1397,10 +1397,17 @@ var BrowserApp = {
if (!shouldShowProgress(url))
params.showProgress = false;
if (data.newTab)
if (data.newTab) {
this.addTab(url, params);
else
} else {
if (data.tabId) {
// Use a specific browser instead of the selected browser, if it exists
let specificBrowser = this.getTabForId(data.tabId).browser;
if (specificBrowser)
browser = specificBrowser;
}
this.loadURI(url, browser, params);
}
break;
}
@ -3487,6 +3494,60 @@ Tab.prototype = {
};
sendMessageToJava(json);
} catch (e) {}
} else if (list.indexOf("[search]" != -1)) {
let type = target.type && target.type.toLowerCase();
// Replace all starting or trailing spaces or spaces before "*;" globally w/ "".
type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
// Check that type matches opensearch.
let isOpenSearch = (type == "application/opensearchdescription+xml");
if (isOpenSearch && target.title && /^(?:https?|ftp):/i.test(target.href)) {
let visibleEngines = Services.search.getVisibleEngines();
// NOTE: Engines are currently identified by name, but this can be changed
// when Engines are identified by URL (see bug 335102).
if (visibleEngines.some(function(e) {
return e.name == target.title;
})) {
// This engine is already present, do nothing.
return;
}
if (this.browser.engines) {
// This engine has already been handled, do nothing.
if (this.browser.engines.some(function(e) {
return e.url == target.href;
})) {
return;
}
} else {
this.browser.engines = [];
}
// Get favicon.
let iconURL = target.ownerDocument.documentURIObject.prePath + "/favicon.ico";
let newEngine = {
title: target.title,
url: target.href,
iconURL: iconURL
};
this.browser.engines.push(newEngine);
// Don't send a message to display engines if we've already handled an engine.
if (this.browser.engines.length > 1)
return;
// Broadcast message that this tab contains search engines that should be visible.
let newEngineMessage = {
type: "Link:OpenSearch",
tabID: this.id,
visible: true
};
sendMessageToJava(newEngineMessage);
}
}
break;
}
@ -3641,6 +3702,22 @@ Tab.prototype = {
return;
}
// Clear page-specific opensearch engines and feeds for a new request.
if (aStateFlags & Ci.nsIWebProgressListener.STATE_START && aRequest && aWebProgress.isTopLevel) {
this.browser.engines = null;
// Send message to clear search engine option in context menu.
let newEngineMessage = {
type: "Link:OpenSearch",
tabID: this.id,
visible: false
};
sendMessageToJava(newEngineMessage);
this.browser.feeds = null;
}
// Check to see if we restoring the content from a previous presentation (session)
// since there should be no real network activity
let restoring = aStateFlags & Ci.nsIWebProgressListener.STATE_RESTORING;
@ -6556,6 +6633,7 @@ var SearchEngines = {
PREF_SUGGEST_PROMPTED: "browser.search.suggest.prompted",
init: function init() {
Services.obs.addObserver(this, "SearchEngines:Add", false);
Services.obs.addObserver(this, "SearchEngines:Get", false);
Services.obs.addObserver(this, "SearchEngines:GetVisible", false);
Services.obs.addObserver(this, "SearchEngines:SetDefault", false);
@ -6570,6 +6648,7 @@ var SearchEngines = {
},
uninit: function uninit() {
Services.obs.removeObserver(this, "SearchEngines:Add");
Services.obs.removeObserver(this, "SearchEngines:Get");
Services.obs.removeObserver(this, "SearchEngines:GetVisible");
Services.obs.removeObserver(this, "SearchEngines:SetDefault");
@ -6651,6 +6730,9 @@ var SearchEngines = {
observe: function observe(aSubject, aTopic, aData) {
let engine;
switch(aTopic) {
case "SearchEngines:Add":
this.displaySearchEnginesList(aData);
break;
case "SearchEngines:GetVisible":
Services.search.init(this._handleSearchEnginesGetVisible.bind(this));
break;
@ -6677,6 +6759,50 @@ var SearchEngines = {
}
},
// Display context menu listing names of the search engines available to be added.
displaySearchEnginesList: function displaySearchEnginesList(aData) {
let data = JSON.parse(aData);
let tab = BrowserApp.getTabForId(data.tabId);
if (!tab)
return;
let browser = tab.browser;
let engines = browser.engines;
let p = new Prompt({
window: browser.contentWindow
}).setSingleChoiceItems(engines.map(function(e) {
return { label: e.title };
})).show((function(data) {
if (data.button == -1)
return;
this.addOpenSearchEngine(engines[data.button]);
engines.splice(data.button, 1);
if (engines.length < 1) {
// Broadcast message that there are no more add-able search engines.
let newEngineMessage = {
type: "Link:OpenSearch",
tabID: tab.id,
visible: false
};
sendMessageToJava(newEngineMessage);
}
}).bind(this));
},
addOpenSearchEngine: function addOpenSearchEngine(engine) {
Services.search.addEngine(engine.url, Ci.nsISearchEngine.DATA_XML, engine.iconURL, false, {
onSuccess: function() {
// Display a toast confirming addition of new search engine.
NativeWindow.toast.show(Strings.browser.formatStringFromName("alertSearchEngineAddedToast", [engine.title], 1), "long");
}
});
},
addEngine: function addEngine(aElement) {
let form = aElement.form;
let charset = aElement.ownerDocument.characterSet;
@ -7118,6 +7244,7 @@ var RemoteDebugger = {
// Make prompt. Note: button order is in reverse.
let prompt = new Prompt({
window: null,
hint: "remotedebug",
title: title,
message: msg,
buttons: [ agree, cancel, disable ],

Просмотреть файл

@ -218,6 +218,7 @@ InternalPrompt.prototype = {
alert: function alert(aTitle, aText) {
let p = this._getPrompt(aTitle, aText, [ PromptUtils.getLocaleString("OK") ]);
p.setHint("alert");
this.showPrompt(p);
},
@ -230,6 +231,7 @@ InternalPrompt.prototype = {
confirm: function confirm(aTitle, aText) {
let p = this._getPrompt(aTitle, aText);
p.setHint("confirm");
let data = this.showPrompt(p);
return (data.button == 0);
},
@ -291,6 +293,7 @@ InternalPrompt.prototype = {
nsIPrompt_prompt: function nsIPrompt_prompt(aTitle, aText, aValue, aCheckMsg, aCheckState) {
let p = this._getPrompt(aTitle, aText, null, aCheckMsg, aCheckState);
p.setHint("prompt");
p.addTextbox({
value: aValue.value,
autofocus: true

Просмотреть файл

@ -22,6 +22,11 @@ alertDownloadsCancel=Cancel
alertFullScreenToast=Press BACK to leave full-screen mode
# LOCALIZATION NOTE (alertSearchEngineAddedToast)
# %S will be replaced by the name of the search engine (exposed by the current page)
# that has been added; for example, 'Google'.
alertSearchEngineAddedToast='%S' has been added as a search engine
downloadCancelPromptTitle=Cancel Download
downloadCancelPromptMessage=Do you want to cancel this download?

Просмотреть файл

@ -32,12 +32,23 @@ function Prompt(aOptions) {
if ("buttons" in aOptions && aOptions.buttons != null)
this.msg.buttons = aOptions.buttons;
if ("hint" in aOptions && aOptions.hint != null)
this.msg.hint = aOptions.hint;
let idService = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
this.guid = idService.generateUUID().toString();
this.msg.guid = this.guid;
}
Prompt.prototype = {
setHint: function(aHint) {
if (!aHint)
delete this.msg.hint;
else
this.msg.hint = aHint;
return this;
},
addButton: function(aOptions) {
if (!this.msg.buttons)
this.msg.buttons = [];

Просмотреть файл

@ -106,7 +106,7 @@ XPIDL_SOURCES += [
'nsITimedChannel.idl',
'nsITraceableChannel.idl',
'nsITransport.idl',
'nsIUDPServerSocket.idl',
'nsIUDPSocket.idl',
'nsIUnicharStreamLoader.idl',
'nsIUploadChannel.idl',
'nsIUploadChannel2.idl',

Просмотреть файл

@ -22,7 +22,7 @@ interface nsISearchSubmission : nsISupports
readonly attribute nsIURI uri;
};
[scriptable, uuid(ccf6aa20-10a9-4a0c-a81d-31b10ea846de)]
[scriptable, uuid(7914c4b8-f05b-40c9-a982-38a058cd1769)]
interface nsISearchEngine : nsISupports
{
/**
@ -83,6 +83,25 @@ interface nsISearchEngine : nsISupports
*/
boolean supportsResponseType(in AString responseType);
/**
* Returns a string with the URL to an engine's icon matching both width and
* height. Returns null if icon with specified dimensions is not found.
*
* @param width
* Width of the requested icon.
* @param height
* Height of the requested icon.
*/
AString getIconURLBySize(in long width, in long height);
/**
* Gets an array of all available icons. Each entry is an object with
* width, height and url properties. width and height are numeric and
* represent the icon's dimensions. url is a string with the URL for
* the icon.
*/
jsval getIcons();
/**
* Supported search engine types.
*/

Просмотреть файл

@ -6,13 +6,18 @@
#include "nsISupports.idl"
%{ C++
#include "mozilla/net/DNS.h"
%}
native NetAddr(mozilla::net::NetAddr);
/**
* nsINetAddr
*
* This interface represents a native NetAddr struct in a readonly
* interface.
*/
[scriptable, uuid(4f7c40b0-fc7d-42a4-a642-1b2a703c10f6)]
[scriptable, uuid(652B9EC5-D159-45D7-9127-50BB559486CD)]
interface nsINetAddr : nsISupports
{
/**
@ -71,4 +76,9 @@ interface nsINetAddr : nsISupports
const unsigned long FAMILY_INET = 1;
const unsigned long FAMILY_INET6 = 2;
const unsigned long FAMILY_LOCAL = 3;
/**
* @return the underlying NetAddr struct.
*/
[noscript] NetAddr getNetAddr();
};

Просмотреть файл

@ -6,7 +6,7 @@
#include "nsISupports.idl"
interface nsINetAddr;
interface nsIUDPServerSocketListener;
interface nsIUDPSocketListener;
interface nsIUDPMessage;
interface nsISocketTransport;
interface nsIOutputStream;
@ -22,23 +22,23 @@ native NetAddr(mozilla::net::NetAddr);
[ptr] native NetAddrPtr(mozilla::net::NetAddr);
/**
* nsIUDPServerSocket
* nsIUDPSocket
*
* An interface to a server socket that can accept incoming connections.
* An interface to a UDP socket that can accept incoming connections.
*/
[scriptable, uuid(c2a38bd0-024b-4ae8-bcb2-20d766b54389)]
interface nsIUDPServerSocket : nsISupports
[scriptable, uuid(6EFE692D-F0B0-4A9E-9E63-837C7452446D)]
interface nsIUDPSocket : nsISupports
{
/**
* init
*
* This method initializes a server socket.
* This method initializes a UDP socket.
*
* @param aPort
* The port of the server socket. Pass -1 to indicate no preference,
* The port of the UDP socket. Pass -1 to indicate no preference,
* and a port will be selected automatically.
* @param aLoopbackOnly
* If true, the server socket will only respond to connections on the
* If true, the UDP socket will only respond to connections on the
* local loopback interface. Otherwise, it will accept connections
* from any interface. To specify a particular network interface,
* use initWithAddress.
@ -48,20 +48,20 @@ interface nsIUDPServerSocket : nsISupports
/**
* initWithAddress
*
* This method initializes a server socket, and binds it to a particular
* This method initializes a UDP socket, and binds it to a particular
* local address (and hence a particular local network interface).
*
* @param aAddr
* The address to which this server socket should be bound.
* The address to which this UDP socket should be bound.
*/
[noscript] void initWithAddress([const] in NetAddrPtr aAddr);
/**
* close
*
* This method closes a server socket. This does not affect already
* This method closes a UDP socket. This does not affect already
* connected client sockets (i.e., the nsISocketTransport instances
* created from this server socket). This will cause the onStopListening
* created from this UDP socket). This will cause the onStopListening
* event to asynchronously fire with a status of NS_BINDING_ABORTED.
*/
void close();
@ -69,7 +69,7 @@ interface nsIUDPServerSocket : nsISupports
/**
* asyncListen
*
* This method puts the server socket in the listening state. It will
* This method puts the UDP socket in the listening state. It will
* asynchronously listen for and accept client connections. The listener
* will be notified once for each client connection that is accepted. The
* listener's onSocketAccepted method will be called on the same thread
@ -81,65 +81,109 @@ interface nsIUDPServerSocket : nsISupports
* @param aListener
* The listener to be notified when client connections are accepted.
*/
void asyncListen(in nsIUDPServerSocketListener aListener);
void asyncListen(in nsIUDPSocketListener aListener);
/**
* Returns the port of this server socket.
* Returns the port of this UDP socket.
*/
readonly attribute long port;
/**
* Returns the address to which this server socket is bound. Since a
* server socket may be bound to multiple network devices, this address
* Returns the address to which this UDP socket is bound. Since a
* UDP socket may be bound to multiple network devices, this address
* may not necessarily be specific to a single network device. In the
* case of an IP socket, the IP address field would be zerod out to
* indicate a server socket bound to all network devices. Therefore,
* indicate a UDP socket bound to all network devices. Therefore,
* this method cannot be used to determine the IP address of the local
* system. See nsIDNSService::myHostName if this is what you need.
*/
[noscript] NetAddr getAddress();
/**
* send
*
* Send out the datagram to specified remote host and port.
* DNS lookup will be triggered.
*
* @param host The remote host name.
* @param port The remote port.
* @param data The buffer containing the data to be written.
* @param dataLength The maximum number of bytes to be written.
* @return number of bytes written. (0 or dataLength)
*/
unsigned long send(in AUTF8String host, in unsigned short port,
[const, array, size_is(dataLength)]in uint8_t data,
in unsigned long dataLength);
/**
* sendWithAddr
*
* Send out the datagram to specified remote host and port.
*
* @param addr The remote host address.
* @param data The buffer containing the data to be written.
* @param dataLength The maximum number of bytes to be written.
* @return number of bytes written. (0 or dataLength)
*/
unsigned long sendWithAddr(in nsINetAddr addr,
[const, array, size_is(dataLength)]in uint8_t data,
in unsigned long dataLength);
/**
* sendWithAddress
*
* Send out the datagram to specified remote address and port.
*
* @param addr The remote host address.
* @param data The buffer containing the data to be written.
* @param dataLength The maximum number of bytes to be written.
* @return number of bytes written. (0 or dataLength)
*/
[noscript] unsigned long sendWithAddress([const] in NetAddrPtr addr,
[const, array, size_is(dataLength)]in uint8_t data,
in unsigned long dataLength);
};
/**
* nsIUDPServerSocketListener
* nsIUDPSocketListener
*
* This interface is notified whenever a server socket accepts a new connection.
* This interface is notified whenever a UDP socket accepts a new connection.
* The transport is in the connected state, and read/write streams can be opened
* using the normal nsITransport API. The address of the client can be found by
* calling the nsISocketTransport::GetAddress method or by inspecting
* nsISocketTransport::GetHost, which returns a string representation of the
* client's IP address (NOTE: this may be an IPv4 or IPv6 string literal).
*/
[scriptable, uuid(0500a336-29b2-4df1-9103-911f8ee0a569)]
interface nsIUDPServerSocketListener : nsISupports
[scriptable, uuid(2E4B5DD3-7358-4281-B81F-10C62EF39CB5)]
interface nsIUDPSocketListener : nsISupports
{
/**
* onPacketReceived
*
* This method is called when a client sends an UDP packet.
*
* @param aServ
* The server socket.
* @param aSocket
* The UDP socket.
* @param aMessage
* The message.
*/
void onPacketReceived(in nsIUDPServerSocket aServ,
void onPacketReceived(in nsIUDPSocket aSocket,
in nsIUDPMessage aMessage);
/**
* onStopListening
*
* This method is called when the listening socket stops for some reason.
* The server socket is effectively dead after this notification.
* The UDP socket is effectively dead after this notification.
*
* @param aServ
* The server socket.
* @param aSocket
* The UDP socket.
* @param aStatus
* The reason why the server socket stopped listening. If the
* server socket was manually closed, then this value will be
* The reason why the UDP socket stopped listening. If the
* UDP socket was manually closed, then this value will be
* NS_BINDING_ABORTED.
*/
void onStopListening(in nsIUDPServerSocket aServ, in nsresult aStatus);
void onStopListening(in nsIUDPSocket aSocket, in nsresult aStatus);
};
/**
@ -147,7 +191,7 @@ interface nsIUDPServerSocketListener : nsISupports
*
* This interface is used to encapsulate an incomming UDP message
*/
[scriptable, uuid(1587698a-60b6-4a8d-9df9-708cd793e24b)]
[scriptable, uuid(333D5D69-8117-4AA6-9E16-2DD4FD6AEBA6)]
interface nsIUDPMessage : nsISupports
{
/**

Просмотреть файл

@ -66,7 +66,7 @@ SOURCES += [
'nsSyncStreamListener.cpp',
'nsTemporaryFileInputStream.cpp',
'nsTransportUtils.cpp',
'nsUDPServerSocket.cpp',
'nsUDPSocket.cpp',
'nsUnicharStreamLoader.cpp',
'nsURIChecker.cpp',
'nsURLHelper.cpp',

Просмотреть файл

@ -151,3 +151,8 @@ NS_IMETHODIMP nsNetAddr::GetIsV4Mapped(bool *aIsV4Mapped)
return NS_OK;
}
NS_IMETHODIMP nsNetAddr::GetNetAddr(NetAddr *aResult) {
memcpy(aResult, &mAddr, sizeof(mAddr));
return NS_OK;
}

Просмотреть файл

@ -4,7 +4,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsSocketTransport2.h"
#include "nsUDPServerSocket.h"
#include "nsUDPSocket.h"
#include "nsProxyRelease.h"
#include "nsAutoPtr.h"
#include "nsError.h"
@ -19,6 +19,9 @@
#include "nsIPipe.h"
#include "prerror.h"
#include "nsThreadUtils.h"
#include "nsIDNSRecord.h"
#include "nsIDNSService.h"
#include "nsICancelable.h"
using namespace mozilla::net;
using namespace mozilla;
@ -27,10 +30,10 @@ static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
//-----------------------------------------------------------------------------
typedef void (nsUDPServerSocket:: *nsUDPServerSocketFunc)(void);
typedef void (nsUDPSocket:: *nsUDPSocketFunc)(void);
static nsresult
PostEvent(nsUDPServerSocket *s, nsUDPServerSocketFunc func)
PostEvent(nsUDPSocket *s, nsUDPSocketFunc func)
{
nsCOMPtr<nsIRunnable> ev = NS_NewRunnableMethod(s, func);
@ -40,15 +43,32 @@ PostEvent(nsUDPServerSocket *s, nsUDPServerSocketFunc func)
return gSocketTransportService->Dispatch(ev, NS_DISPATCH_NORMAL);
}
static nsresult
ResolveHost(const nsACString &host, nsIDNSListener *listener)
{
nsresult rv;
nsCOMPtr<nsIDNSService> dns =
do_GetService("@mozilla.org/network/dns-service;1", &rv);
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsICancelable> tmpOutstanding;
return dns->AsyncResolve(host, 0, listener, nullptr,
getter_AddRefs(tmpOutstanding));
}
//-----------------------------------------------------------------------------
// nsUPDOutputStream impl
// nsUDPOutputStream impl
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS1(nsUDPOutputStream, nsIOutputStream)
nsUDPOutputStream::nsUDPOutputStream(nsUDPServerSocket* aServer,
nsUDPOutputStream::nsUDPOutputStream(nsUDPSocket* aSocket,
PRFileDesc* aFD,
PRNetAddr& aPrClientAddr)
: mServer(aServer)
: mSocket(aSocket)
, mFD(aFD)
, mPrClientAddr(aPrClientAddr)
, mIsClosed(false)
@ -90,7 +110,7 @@ NS_IMETHODIMP nsUDPOutputStream::Write(const char * aBuf, uint32_t aCount, uint3
*_retval = count;
mServer->AddOutputBytes(count);
mSocket->AddOutputBytes(count);
return NS_OK;
}
@ -115,7 +135,7 @@ NS_IMETHODIMP nsUDPOutputStream::IsNonBlocking(bool *_retval)
}
//-----------------------------------------------------------------------------
// nsUPDMessage impl
// nsUDPMessage impl
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS1(nsUDPMessage, nsIUDPMessage)
@ -162,11 +182,11 @@ NS_IMETHODIMP nsUDPMessage::GetOutputStream(nsIOutputStream * *aOutputStream)
}
//-----------------------------------------------------------------------------
// nsServerSocket
// nsUDPSocket
//-----------------------------------------------------------------------------
nsUDPServerSocket::nsUDPServerSocket()
: mLock("nsUDPServerSocket.mLock")
nsUDPSocket::nsUDPSocket()
: mLock("nsUDPSocket.mLock")
, mFD(nullptr)
, mAttached(false)
, mByteReadCount(0)
@ -183,26 +203,26 @@ nsUDPServerSocket::nsUDPServerSocket()
}
mSts = gSocketTransportService;
MOZ_COUNT_CTOR(nsUDPServerSocket);
MOZ_COUNT_CTOR(nsUDPSocket);
}
nsUDPServerSocket::~nsUDPServerSocket()
nsUDPSocket::~nsUDPSocket()
{
Close(); // just in case :)
MOZ_COUNT_DTOR(nsUDPServerSocket);
MOZ_COUNT_DTOR(nsUDPSocket);
}
void
nsUDPServerSocket::AddOutputBytes(uint64_t aBytes)
nsUDPSocket::AddOutputBytes(uint64_t aBytes)
{
mByteWriteCount += aBytes;
}
void
nsUDPServerSocket::OnMsgClose()
nsUDPSocket::OnMsgClose()
{
SOCKET_LOG(("nsServerSocket::OnMsgClose [this=%p]\n", this));
SOCKET_LOG(("nsUDPSocket::OnMsgClose [this=%p]\n", this));
if (NS_FAILED(mCondition))
return;
@ -218,9 +238,9 @@ nsUDPServerSocket::OnMsgClose()
}
void
nsUDPServerSocket::OnMsgAttach()
nsUDPSocket::OnMsgAttach()
{
SOCKET_LOG(("nsServerSocket::OnMsgAttach [this=%p]\n", this));
SOCKET_LOG(("nsUDPSocket::OnMsgAttach [this=%p]\n", this));
if (NS_FAILED(mCondition))
return;
@ -236,7 +256,7 @@ nsUDPServerSocket::OnMsgAttach()
}
nsresult
nsUDPServerSocket::TryAttach()
nsUDPSocket::TryAttach()
{
nsresult rv;
@ -258,7 +278,7 @@ nsUDPServerSocket::TryAttach()
if (!gSocketTransportService->CanAttachSocket())
{
nsCOMPtr<nsIRunnable> event =
NS_NewRunnableMethod(this, &nsUDPServerSocket::OnMsgAttach);
NS_NewRunnableMethod(this, &nsUDPSocket::OnMsgAttach);
nsresult rv = gSocketTransportService->NotifyWhenCanAttachSocket(event);
if (NS_FAILED(rv))
@ -282,11 +302,11 @@ nsUDPServerSocket::TryAttach()
}
//-----------------------------------------------------------------------------
// nsServerSocket::nsASocketHandler
// nsUDPSocket::nsASocketHandler
//-----------------------------------------------------------------------------
void
nsUDPServerSocket::OnSocketReady(PRFileDesc *fd, int16_t outFlags)
nsUDPSocket::OnSocketReady(PRFileDesc *fd, int16_t outFlags)
{
NS_ASSERTION(NS_SUCCEEDED(mCondition), "oops");
NS_ASSERTION(mFD == fd, "wrong file descriptor");
@ -343,7 +363,7 @@ nsUDPServerSocket::OnSocketReady(PRFileDesc *fd, int16_t outFlags)
}
void
nsUDPServerSocket::OnSocketDetached(PRFileDesc *fd)
nsUDPSocket::OnSocketDetached(PRFileDesc *fd)
{
// force a failure condition if none set; maybe the STS is shutting down :-/
if (NS_SUCCEEDED(mCondition))
@ -359,7 +379,7 @@ nsUDPServerSocket::OnSocketDetached(PRFileDesc *fd)
if (mListener)
{
// need to atomically clear mListener. see our Close() method.
nsCOMPtr<nsIUDPServerSocketListener> listener;
nsCOMPtr<nsIUDPSocketListener> listener;
{
MutexAutoLock lock(mLock);
mListener.swap(listener);
@ -373,25 +393,25 @@ nsUDPServerSocket::OnSocketDetached(PRFileDesc *fd)
}
void
nsUDPServerSocket::IsLocal(bool *aIsLocal)
nsUDPSocket::IsLocal(bool *aIsLocal)
{
// If bound to loopback, this server socket only accepts local connections.
// If bound to loopback, this UDP socket only accepts local connections.
*aIsLocal = mAddr.raw.family == nsINetAddr::FAMILY_LOCAL;
}
//-----------------------------------------------------------------------------
// nsServerSocket::nsISupports
// nsSocket::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS1(nsUDPServerSocket, nsIUDPServerSocket)
NS_IMPL_ISUPPORTS1(nsUDPSocket, nsIUDPSocket)
//-----------------------------------------------------------------------------
// nsServerSocket::nsIServerSocket
// nsSocket::nsISocket
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsUDPServerSocket::Init(int32_t aPort, bool aLoopbackOnly)
nsUDPSocket::Init(int32_t aPort, bool aLoopbackOnly)
{
NetAddr addr;
@ -410,7 +430,7 @@ nsUDPServerSocket::Init(int32_t aPort, bool aLoopbackOnly)
}
NS_IMETHODIMP
nsUDPServerSocket::InitWithAddress(const NetAddr *aAddr)
nsUDPSocket::InitWithAddress(const NetAddr *aAddr)
{
NS_ENSURE_TRUE(mFD == nullptr, NS_ERROR_ALREADY_INITIALIZED);
@ -421,7 +441,7 @@ nsUDPServerSocket::InitWithAddress(const NetAddr *aAddr)
mFD = PR_OpenUDPSocket(aAddr->raw.family);
if (!mFD)
{
NS_WARNING("unable to create server socket");
NS_WARNING("unable to create UDP socket");
return NS_ERROR_FAILURE;
}
@ -436,6 +456,7 @@ nsUDPServerSocket::InitWithAddress(const NetAddr *aAddr)
PR_SetSocketOption(mFD, &opt);
PRNetAddr addr;
PR_InitializeNetAddr(PR_IpAddrAny, 0, &addr);
NetAddrToPRNetAddr(aAddr, &addr);
if (PR_Bind(mFD, &addr) != PR_SUCCESS)
@ -467,7 +488,7 @@ fail:
}
NS_IMETHODIMP
nsUDPServerSocket::Close()
nsUDPSocket::Close()
{
{
MutexAutoLock lock(mLock);
@ -483,11 +504,11 @@ nsUDPServerSocket::Close()
return NS_OK;
}
}
return PostEvent(this, &nsUDPServerSocket::OnMsgClose);
return PostEvent(this, &nsUDPSocket::OnMsgClose);
}
NS_IMETHODIMP
nsUDPServerSocket::GetPort(int32_t *aResult)
nsUDPSocket::GetPort(int32_t *aResult)
{
// no need to enter the lock here
uint16_t port;
@ -503,7 +524,7 @@ nsUDPServerSocket::GetPort(int32_t *aResult)
}
NS_IMETHODIMP
nsUDPServerSocket::GetAddress(NetAddr *aResult)
nsUDPSocket::GetAddress(NetAddr *aResult)
{
// no need to enter the lock here
memcpy(aResult, &mAddr, sizeof(mAddr));
@ -512,107 +533,260 @@ nsUDPServerSocket::GetAddress(NetAddr *aResult)
namespace {
class ServerSocketListenerProxy MOZ_FINAL : public nsIUDPServerSocketListener
class SocketListenerProxy MOZ_FINAL : public nsIUDPSocketListener
{
public:
ServerSocketListenerProxy(nsIUDPServerSocketListener* aListener)
: mListener(new nsMainThreadPtrHolder<nsIUDPServerSocketListener>(aListener))
SocketListenerProxy(nsIUDPSocketListener* aListener)
: mListener(new nsMainThreadPtrHolder<nsIUDPSocketListener>(aListener))
, mTargetThread(do_GetCurrentThread())
{ }
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSERVERSOCKETLISTENER
NS_DECL_NSIUDPSOCKETLISTENER
class OnPacketReceivedRunnable : public nsRunnable
{
public:
OnPacketReceivedRunnable(const nsMainThreadPtrHandle<nsIUDPServerSocketListener>& aListener,
nsIUDPServerSocket* aServ,
nsIUDPMessage* aMessage)
OnPacketReceivedRunnable(const nsMainThreadPtrHandle<nsIUDPSocketListener>& aListener,
nsIUDPSocket* aSocket,
nsIUDPMessage* aMessage)
: mListener(aListener)
, mServ(aServ)
, mSocket(aSocket)
, mMessage(aMessage)
{ }
NS_DECL_NSIRUNNABLE
private:
nsMainThreadPtrHandle<nsIUDPServerSocketListener> mListener;
nsCOMPtr<nsIUDPServerSocket> mServ;
nsMainThreadPtrHandle<nsIUDPSocketListener> mListener;
nsCOMPtr<nsIUDPSocket> mSocket;
nsCOMPtr<nsIUDPMessage> mMessage;
};
class OnStopListeningRunnable : public nsRunnable
{
public:
OnStopListeningRunnable(const nsMainThreadPtrHandle<nsIUDPServerSocketListener>& aListener,
nsIUDPServerSocket* aServ,
OnStopListeningRunnable(const nsMainThreadPtrHandle<nsIUDPSocketListener>& aListener,
nsIUDPSocket* aSocket,
nsresult aStatus)
: mListener(aListener)
, mServ(aServ)
, mSocket(aSocket)
, mStatus(aStatus)
{ }
NS_DECL_NSIRUNNABLE
private:
nsMainThreadPtrHandle<nsIUDPServerSocketListener> mListener;
nsCOMPtr<nsIUDPServerSocket> mServ;
nsMainThreadPtrHandle<nsIUDPSocketListener> mListener;
nsCOMPtr<nsIUDPSocket> mSocket;
nsresult mStatus;
};
private:
nsMainThreadPtrHandle<nsIUDPServerSocketListener> mListener;
nsMainThreadPtrHandle<nsIUDPSocketListener> mListener;
nsCOMPtr<nsIEventTarget> mTargetThread;
};
NS_IMPL_ISUPPORTS1(ServerSocketListenerProxy,
nsIUDPServerSocketListener)
NS_IMPL_ISUPPORTS1(SocketListenerProxy,
nsIUDPSocketListener)
NS_IMETHODIMP
ServerSocketListenerProxy::OnPacketReceived(nsIUDPServerSocket* aServ,
nsIUDPMessage* aMessage)
SocketListenerProxy::OnPacketReceived(nsIUDPSocket* aSocket,
nsIUDPMessage* aMessage)
{
nsRefPtr<OnPacketReceivedRunnable> r =
new OnPacketReceivedRunnable(mListener, aServ, aMessage);
new OnPacketReceivedRunnable(mListener, aSocket, aMessage);
return mTargetThread->Dispatch(r, NS_DISPATCH_NORMAL);
}
NS_IMETHODIMP
ServerSocketListenerProxy::OnStopListening(nsIUDPServerSocket* aServ,
nsresult aStatus)
SocketListenerProxy::OnStopListening(nsIUDPSocket* aSocket,
nsresult aStatus)
{
nsRefPtr<OnStopListeningRunnable> r =
new OnStopListeningRunnable(mListener, aServ, aStatus);
new OnStopListeningRunnable(mListener, aSocket, aStatus);
return mTargetThread->Dispatch(r, NS_DISPATCH_NORMAL);
}
NS_IMETHODIMP
ServerSocketListenerProxy::OnPacketReceivedRunnable::Run()
SocketListenerProxy::OnPacketReceivedRunnable::Run()
{
mListener->OnPacketReceived(mServ, mMessage);
mListener->OnPacketReceived(mSocket, mMessage);
return NS_OK;
}
NS_IMETHODIMP
ServerSocketListenerProxy::OnStopListeningRunnable::Run()
SocketListenerProxy::OnStopListeningRunnable::Run()
{
mListener->OnStopListening(mServ, mStatus);
mListener->OnStopListening(mSocket, mStatus);
return NS_OK;
}
class PendingSend : public nsIDNSListener
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIDNSLISTENER
PendingSend(nsUDPSocket *aSocket, uint16_t aPort,
FallibleTArray<uint8_t> &aData)
: mSocket(aSocket)
, mPort(aPort)
{
mData.SwapElements(aData);
}
virtual ~PendingSend() {}
private:
nsRefPtr<nsUDPSocket> mSocket;
uint16_t mPort;
FallibleTArray<uint8_t> mData;
};
NS_IMPL_ISUPPORTS1(PendingSend, nsIDNSListener)
NS_IMETHODIMP
PendingSend::OnLookupComplete(nsICancelable *request,
nsIDNSRecord *rec,
nsresult status)
{
if (NS_FAILED(status)) {
NS_WARNING("Failed to send UDP packet due to DNS lookup failure");
return NS_OK;
}
NetAddr addr;
if (NS_SUCCEEDED(rec->GetNextAddr(mPort, &addr))) {
uint32_t count;
nsresult rv = mSocket->SendWithAddress(&addr, mData.Elements(),
mData.Length(), &count);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
class SendRequestRunnable: public nsRunnable {
public:
SendRequestRunnable(nsUDPSocket *aSocket,
const NetAddr &aAddr,
FallibleTArray<uint8_t> &aData)
: mSocket(aSocket)
, mAddr(aAddr)
, mData(aData)
{ }
NS_DECL_NSIRUNNABLE
private:
nsRefPtr<nsUDPSocket> mSocket;
const NetAddr mAddr;
FallibleTArray<uint8_t> mData;
};
NS_IMETHODIMP
SendRequestRunnable::Run()
{
uint32_t count;
mSocket->SendWithAddress(&mAddr, mData.Elements(),
mData.Length(), &count);
return NS_OK;
}
} // anonymous namespace
NS_IMETHODIMP
nsUDPServerSocket::AsyncListen(nsIUDPServerSocketListener *aListener)
nsUDPSocket::AsyncListen(nsIUDPSocketListener *aListener)
{
// ensuring mFD implies ensuring mLock
NS_ENSURE_TRUE(mFD, NS_ERROR_NOT_INITIALIZED);
NS_ENSURE_TRUE(mListener == nullptr, NS_ERROR_IN_PROGRESS);
{
MutexAutoLock lock(mLock);
mListener = new ServerSocketListenerProxy(aListener);
mListener = new SocketListenerProxy(aListener);
mListenerTarget = NS_GetCurrentThread();
}
return PostEvent(this, &nsUDPServerSocket::OnMsgAttach);
return PostEvent(this, &nsUDPSocket::OnMsgAttach);
}
NS_IMETHODIMP
nsUDPSocket::Send(const nsACString &aHost, uint16_t aPort,
const uint8_t *aData, uint32_t aDataLength,
uint32_t *_retval)
{
NS_ENSURE_ARG(aData);
NS_ENSURE_ARG_POINTER(_retval);
*_retval = 0;
FallibleTArray<uint8_t> fallibleArray;
if (!fallibleArray.InsertElementsAt(0, aData, aDataLength)) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsCOMPtr<nsIDNSListener> listener = new PendingSend(this, aPort, fallibleArray);
nsresult rv = ResolveHost(aHost, listener);
NS_ENSURE_SUCCESS(rv, rv);
*_retval = aDataLength;
return NS_OK;
}
NS_IMETHODIMP
nsUDPSocket::SendWithAddr(nsINetAddr *aAddr, const uint8_t *aData,
uint32_t aDataLength, uint32_t *_retval)
{
NS_ENSURE_ARG(aAddr);
NS_ENSURE_ARG(aData);
NS_ENSURE_ARG_POINTER(_retval);
NetAddr netAddr;
aAddr->GetNetAddr(&netAddr);
return SendWithAddress(&netAddr, aData, aDataLength, _retval);
}
NS_IMETHODIMP
nsUDPSocket::SendWithAddress(const NetAddr *aAddr, const uint8_t *aData,
uint32_t aDataLength, uint32_t *_retval)
{
NS_ENSURE_ARG(aAddr);
NS_ENSURE_ARG(aData);
NS_ENSURE_ARG_POINTER(_retval);
*_retval = 0;
PRNetAddr prAddr;
NetAddrToPRNetAddr(aAddr, &prAddr);
bool onSTSThread = false;
mSts->IsOnCurrentThread(&onSTSThread);
if (onSTSThread) {
MutexAutoLock lock(mLock);
if (!mFD) {
// socket is not initialized or has been closed
return NS_ERROR_FAILURE;
}
int32_t count = PR_SendTo(mFD, aData, sizeof(uint8_t) *aDataLength,
0, &prAddr, PR_INTERVAL_NO_WAIT);
if (count < 0) {
PRErrorCode code = PR_GetError();
return ErrorAccordingToNSPR(code);
}
this->AddOutputBytes(count);
*_retval = count;
} else {
FallibleTArray<uint8_t> fallibleArray;
if (!fallibleArray.InsertElementsAt(0, aData, aDataLength)) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv = mSts->Dispatch(new SendRequestRunnable(this, *aAddr, fallibleArray),
NS_DISPATCH_NORMAL);
NS_ENSURE_SUCCESS(rv, rv);
*_retval = aDataLength;
}
return NS_OK;
}

Просмотреть файл

@ -3,22 +3,22 @@
* 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 nsUDPServerSocket_h__
#define nsUDPServerSocket_h__
#ifndef nsUDPSocket_h__
#define nsUDPSocket_h__
#include "nsIUDPServerSocket.h"
#include "nsIUDPSocket.h"
#include "mozilla/Mutex.h"
#include "nsIOutputStream.h"
#include "nsAutoPtr.h"
//-----------------------------------------------------------------------------
class nsUDPServerSocket : public nsASocketHandler
, public nsIUDPServerSocket
class nsUDPSocket : public nsASocketHandler
, public nsIUDPSocket
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSERVERSOCKET
NS_DECL_NSIUDPSOCKET
// nsASocketHandler methods:
virtual void OnSocketReady(PRFileDesc* fd, int16_t outFlags);
@ -30,10 +30,10 @@ public:
void AddOutputBytes(uint64_t aBytes);
nsUDPServerSocket();
nsUDPSocket();
// This must be public to support older compilers (xlC_r on AIX)
virtual ~nsUDPServerSocket();
virtual ~nsUDPSocket();
private:
void OnMsgClose();
@ -47,7 +47,7 @@ private:
mozilla::Mutex mLock;
PRFileDesc *mFD;
mozilla::net::NetAddr mAddr;
nsCOMPtr<nsIUDPServerSocketListener> mListener;
nsCOMPtr<nsIUDPSocketListener> mListener;
nsCOMPtr<nsIEventTarget> mListenerTarget;
bool mAttached;
nsRefPtr<nsSocketTransportService> mSts;
@ -85,16 +85,16 @@ public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIOUTPUTSTREAM
nsUDPOutputStream(nsUDPServerSocket* aServer,
nsUDPOutputStream(nsUDPSocket* aSocket,
PRFileDesc* aFD,
PRNetAddr& aPrClientAddr);
virtual ~nsUDPOutputStream();
private:
nsRefPtr<nsUDPServerSocket> mServer;
nsRefPtr<nsUDPSocket> mSocket;
PRFileDesc *mFD;
PRNetAddr mPrClientAddr;
bool mIsClosed;
};
#endif // nsUDPServerSocket_h__
#endif // nsUDPSocket_h__

Просмотреть файл

@ -335,10 +335,10 @@
{0xab, 0x1d, 0x5e, 0x68, 0xa9, 0xf4, 0x5f, 0x08} \
}
// component implementing nsIUDPServerSocket
#define NS_UDPSERVERSOCKET_CONTRACTID \
"@mozilla.org/network/server-socket-udp;1"
#define NS_UDPSERVERSOCKET_CID \
// component implementing nsIUDPSocket
#define NS_UDPSOCKET_CONTRACTID \
"@mozilla.org/network/udp-socket;1"
#define NS_UDPSOCKET_CID \
{ /* c9f74572-7b8e-4fec-bb4a-03c0d3021bd6 */ \
0xc9f74572, \
0x7b8e, \

Просмотреть файл

@ -73,8 +73,8 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsSocketTransportService, Init)
#include "nsServerSocket.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsServerSocket)
#include "nsUDPServerSocket.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsUDPServerSocket)
#include "nsUDPSocket.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsUDPSocket)
#include "nsUDPSocketProvider.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsUDPSocketProvider)
@ -682,7 +682,7 @@ NS_DEFINE_NAMED_CID(NS_IOSERVICE_CID);
NS_DEFINE_NAMED_CID(NS_STREAMTRANSPORTSERVICE_CID);
NS_DEFINE_NAMED_CID(NS_SOCKETTRANSPORTSERVICE_CID);
NS_DEFINE_NAMED_CID(NS_SERVERSOCKET_CID);
NS_DEFINE_NAMED_CID(NS_UDPSERVERSOCKET_CID);
NS_DEFINE_NAMED_CID(NS_UDPSOCKET_CID);
NS_DEFINE_NAMED_CID(NS_SOCKETPROVIDERSERVICE_CID);
NS_DEFINE_NAMED_CID(NS_DNSSERVICE_CID);
NS_DEFINE_NAMED_CID(NS_IDNSERVICE_CID);
@ -820,7 +820,7 @@ static const mozilla::Module::CIDEntry kNeckoCIDs[] = {
{ &kNS_STREAMTRANSPORTSERVICE_CID, false, nullptr, nsStreamTransportServiceConstructor },
{ &kNS_SOCKETTRANSPORTSERVICE_CID, false, nullptr, nsSocketTransportServiceConstructor },
{ &kNS_SERVERSOCKET_CID, false, nullptr, nsServerSocketConstructor },
{ &kNS_UDPSERVERSOCKET_CID, false, nullptr, nsUDPServerSocketConstructor },
{ &kNS_UDPSOCKET_CID, false, nullptr, nsUDPSocketConstructor },
{ &kNS_SOCKETPROVIDERSERVICE_CID, false, nullptr, nsSocketProviderService::Create },
{ &kNS_DNSSERVICE_CID, false, nullptr, nsDNSServiceConstructor },
{ &kNS_IDNSERVICE_CID, false, nullptr, nsIDNServiceConstructor },
@ -965,7 +965,7 @@ static const mozilla::Module::ContractIDEntry kNeckoContracts[] = {
{ NS_STREAMTRANSPORTSERVICE_CONTRACTID, &kNS_STREAMTRANSPORTSERVICE_CID },
{ NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &kNS_SOCKETTRANSPORTSERVICE_CID },
{ NS_SERVERSOCKET_CONTRACTID, &kNS_SERVERSOCKET_CID },
{ NS_UDPSERVERSOCKET_CONTRACTID, &kNS_UDPSERVERSOCKET_CID },
{ NS_UDPSOCKET_CONTRACTID, &kNS_UDPSOCKET_CID },
{ NS_SOCKETPROVIDERSERVICE_CONTRACTID, &kNS_SOCKETPROVIDERSERVICE_CID },
{ NS_DNSSERVICE_CONTRACTID, &kNS_DNSSERVICE_CID },
{ NS_IDNSERVICE_CONTRACTID, &kNS_IDNSERVICE_CID },

Просмотреть файл

@ -1,4 +1,4 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* This Source Code Form is subject to the terms of the Mozilla Public
@ -16,6 +16,7 @@
#include "mozilla/net/RemoteOpenFileChild.h"
#include "mozilla/dom/network/TCPSocketChild.h"
#include "mozilla/dom/network/TCPServerSocketChild.h"
#include "mozilla/dom/network/UDPSocketChild.h"
#ifdef MOZ_RTSP
#include "mozilla/net/RtspControllerChild.h"
#endif
@ -23,6 +24,7 @@
using mozilla::dom::TCPSocketChild;
using mozilla::dom::TCPServerSocketChild;
using mozilla::dom::UDPSocketChild;
namespace mozilla {
namespace net {
@ -209,6 +211,23 @@ NeckoChild::DeallocPTCPServerSocketChild(PTCPServerSocketChild* child)
return true;
}
PUDPSocketChild*
NeckoChild::AllocPUDPSocketChild(const nsCString& aHost,
const uint16_t& aPort)
{
NS_NOTREACHED("AllocPUDPSocket should not be called");
return nullptr;
}
bool
NeckoChild::DeallocPUDPSocketChild(PUDPSocketChild* child)
{
UDPSocketChild* p = static_cast<UDPSocketChild*>(child);
p->ReleaseIPDLReference();
return true;
}
PRemoteOpenFileChild*
NeckoChild::AllocPRemoteOpenFileChild(const URIParams&, const OptionalURIParams&)
{

Просмотреть файл

@ -47,6 +47,9 @@ protected:
const uint16_t& aBacklog,
const nsString& aBinaryType);
virtual bool DeallocPTCPServerSocketChild(PTCPServerSocketChild*);
virtual PUDPSocketChild* AllocPUDPSocketChild(const nsCString& aHost,
const uint16_t& aPort);
virtual bool DeallocPUDPSocketChild(PUDPSocketChild*);
virtual PRemoteOpenFileChild* AllocPRemoteOpenFileChild(const URIParams&,
const OptionalURIParams&);
virtual bool DeallocPRemoteOpenFileChild(PRemoteOpenFileChild*);

Просмотреть файл

@ -20,6 +20,7 @@
#include "mozilla/dom/TabParent.h"
#include "mozilla/dom/network/TCPSocketParent.h"
#include "mozilla/dom/network/TCPServerSocketParent.h"
#include "mozilla/dom/network/UDPSocketParent.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/LoadContext.h"
#include "mozilla/AppProcessChecker.h"
@ -36,6 +37,8 @@ using mozilla::net::PTCPSocketParent;
using mozilla::dom::TCPSocketParent;
using mozilla::net::PTCPServerSocketParent;
using mozilla::dom::TCPServerSocketParent;
using mozilla::net::PUDPSocketParent;
using mozilla::dom::UDPSocketParent;
using IPC::SerializedLoadContext;
namespace mozilla {
@ -373,6 +376,37 @@ NeckoParent::DeallocPTCPServerSocketParent(PTCPServerSocketParent* actor)
return true;
}
PUDPSocketParent*
NeckoParent::AllocPUDPSocketParent(const nsCString& aHost,
const uint16_t& aPort)
{
bool enabled = Preferences::GetBool("media.peerconnection.ipc.enabled", false);
if (!enabled) {
NS_WARNING("Not support UDP socket in content process, aborting subprocess");
return nullptr;
}
UDPSocketParent* p = new UDPSocketParent();
p->AddRef();
return p;
}
bool
NeckoParent::RecvPUDPSocketConstructor(PUDPSocketParent* aActor,
const nsCString& aHost,
const uint16_t& aPort)
{
return static_cast<UDPSocketParent*>(aActor)->Init(aHost, aPort);
}
bool
NeckoParent::DeallocPUDPSocketParent(PUDPSocketParent* actor)
{
UDPSocketParent* p = static_cast<UDPSocketParent*>(actor);
p->Release();
return true;
}
PRemoteOpenFileParent*
NeckoParent::AllocPRemoteOpenFileParent(const URIParams& aURI,
const OptionalURIParams& aAppURI)

Просмотреть файл

@ -116,6 +116,12 @@ protected:
const uint16_t& aBacklog,
const nsString& aBinaryType);
virtual bool DeallocPTCPServerSocketParent(PTCPServerSocketParent*);
virtual PUDPSocketParent* AllocPUDPSocketParent(const nsCString& aHost,
const uint16_t& aPort);
virtual bool RecvPUDPSocketConstructor(PUDPSocketParent*,
const nsCString& aHost,
const uint16_t& aPort);
virtual bool DeallocPUDPSocketParent(PUDPSocketParent*);
virtual bool RecvHTMLDNSPrefetch(const nsString& hostname,
const uint16_t& flags);
virtual bool RecvCancelHTMLDNSPrefetch(const nsString& hostname,

Просмотреть файл

@ -14,6 +14,7 @@ include protocol PFTPChannel;
include protocol PWebSocket;
include protocol PTCPSocket;
include protocol PTCPServerSocket;
include protocol PUDPSocket;
include protocol PRemoteOpenFile;
include protocol PBlob; //FIXME: bug #792908
@ -39,6 +40,7 @@ sync protocol PNecko
manages PWebSocket;
manages PTCPSocket;
manages PTCPServerSocket;
manages PUDPSocket;
manages PRemoteOpenFile;
manages PRtspController;
@ -55,6 +57,8 @@ parent:
PWebSocket(PBrowser browser, SerializedLoadContext loadContext);
PTCPServerSocket(uint16_t localPort, uint16_t backlog, nsString binaryType);
PUDPSocket(nsCString host, uint16_t port);
PRemoteOpenFile(URIParams fileuri, OptionalURIParams appuri);
HTMLDNSPrefetch(nsString hostname, uint16_t flags);

Просмотреть файл

@ -0,0 +1,268 @@
/* 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 "TestCommon.h"
#include "TestHarness.h"
#include "nsIUDPSocket.h"
#include "nsISocketTransportService.h"
#include "nsISocketTransport.h"
#include "nsIOutputStream.h"
#include "nsIInputStream.h"
#include "nsINetAddr.h"
#include "mozilla/net/DNS.h"
#include "prerror.h"
#define REQUEST 0x68656c6f
#define RESPONSE 0x6f6c6568
#define EXPECT_SUCCESS(rv, ...) \
PR_BEGIN_MACRO \
if (NS_FAILED(rv)) { \
fail(__VA_ARGS__); \
return false; \
} \
PR_END_MACRO
#define EXPECT_FAILURE(rv, ...) \
PR_BEGIN_MACRO \
if (NS_SUCCEEDED(rv)) { \
fail(__VA_ARGS__); \
return false; \
} \
PR_END_MACRO
#define REQUIRE_EQUAL(a, b, ...) \
PR_BEGIN_MACRO \
if (a != b) { \
fail(__VA_ARGS__); \
return false; \
} \
PR_END_MACRO
enum TestPhase {
TEST_OUTPUT_STREAM,
TEST_SEND_API,
TEST_NONE
};
static TestPhase phase = TEST_NONE;
static bool CheckMessageContent(nsIUDPMessage *aMessage, uint32_t aExpectedContent)
{
nsCString data;
aMessage->GetData(data);
const char* buffer = data.get();
uint32_t len = data.Length();
uint32_t input = 0;
for (uint32_t i = 0; i < len; i++) {
input += buffer[i] << (8 * i);
}
if (len != sizeof(uint32_t) || input != aExpectedContent)
{
fail("Request 0x%x received, expected 0x%x", input, aExpectedContent);
return false;
} else {
passed("Request 0x%x received as expected", input);
return true;
}
}
/*
* UDPClientListener: listens for incomming UDP packets
*/
class UDPClientListener : public nsIUDPSocketListener
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSOCKETLISTENER
virtual ~UDPClientListener();
nsresult mResult;
};
NS_IMPL_ISUPPORTS1(UDPClientListener, nsIUDPSocketListener)
UDPClientListener::~UDPClientListener()
{
}
NS_IMETHODIMP
UDPClientListener::OnPacketReceived(nsIUDPSocket* socket, nsIUDPMessage* message)
{
mResult = NS_OK;
uint16_t port;
nsCString ip;
nsCOMPtr<nsINetAddr> fromAddr;
message->GetFromAddr(getter_AddRefs(fromAddr));
fromAddr->GetPort(&port);
fromAddr->GetAddress(ip);
passed("Packet received on client from %s:%d", ip.get(), port);
if (TEST_SEND_API == phase && CheckMessageContent(message, REQUEST)) {
uint32_t count;
const uint32_t data = RESPONSE;
printf("*** Attempting to write response 0x%x to server by SendWithAddr...\n", RESPONSE);
mResult = socket->SendWithAddr(fromAddr, (const uint8_t*)&data,
sizeof(uint32_t), &count);
if (mResult == NS_OK && count == sizeof(uint32_t)) {
passed("Response written");
} else {
fail("Response written");
}
} else if (TEST_OUTPUT_STREAM != phase || !CheckMessageContent(message, RESPONSE)) {
mResult = NS_ERROR_FAILURE;
}
// Notify thread
QuitPumpingEvents();
return NS_OK;
}
NS_IMETHODIMP
UDPClientListener::OnStopListening(nsIUDPSocket*, nsresult)
{
QuitPumpingEvents();
return NS_OK;
}
/*
* UDPServerListener: listens for incomming UDP packets
*/
class UDPServerListener : public nsIUDPSocketListener
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIUDPSOCKETLISTENER
virtual ~UDPServerListener();
nsresult mResult;
};
NS_IMPL_ISUPPORTS1(UDPServerListener, nsIUDPSocketListener)
UDPServerListener::~UDPServerListener()
{
}
NS_IMETHODIMP
UDPServerListener::OnPacketReceived(nsIUDPSocket* socket, nsIUDPMessage* message)
{
mResult = NS_OK;
uint16_t port;
nsCString ip;
nsCOMPtr<nsINetAddr> fromAddr;
message->GetFromAddr(getter_AddRefs(fromAddr));
fromAddr->GetPort(&port);
fromAddr->GetAddress(ip);
passed("Packet received on server from %s:%d", ip.get(), port);
if (TEST_OUTPUT_STREAM == phase && CheckMessageContent(message, REQUEST))
{
nsCOMPtr<nsIOutputStream> outstream;
message->GetOutputStream(getter_AddRefs(outstream));
uint32_t count;
const uint32_t data = RESPONSE;
printf("*** Attempting to write response 0x%x to client by OutputStream...\n", RESPONSE);
mResult = outstream->Write((const char*)&data, sizeof(uint32_t), &count);
if (mResult == NS_OK && count == sizeof(uint32_t)) {
passed("Response written");
} else {
fail("Response written");
}
} else if (TEST_SEND_API != phase || !CheckMessageContent(message, RESPONSE)) {
mResult = NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
UDPServerListener::OnStopListening(nsIUDPSocket*, nsresult)
{
QuitPumpingEvents();
return NS_OK;
}
/**** Main ****/
int
main(int32_t argc, char *argv[])
{
nsresult rv;
ScopedXPCOM xpcom("UDP ServerSocket");
if (xpcom.failed())
return -1;
// Create UDPSocket
nsCOMPtr<nsIUDPSocket> server, client;
server = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv);
NS_ENSURE_SUCCESS(rv, -1);
client = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv);
NS_ENSURE_SUCCESS(rv, -1);
// Create UDPServerListener to process UDP packets
nsCOMPtr<UDPServerListener> serverListener = new UDPServerListener();
// Bind server socket to 127.0.0.1
rv = server->Init(0, true);
NS_ENSURE_SUCCESS(rv, -1);
int32_t serverPort;
server->GetPort(&serverPort);
server->AsyncListen(serverListener);
// Bind clinet on arbitrary port
nsCOMPtr<UDPClientListener> clientListener = new UDPClientListener();
client->Init(0, true);
client->AsyncListen(clientListener);
// Write data to server
uint32_t count;
const uint32_t data = REQUEST;
phase = TEST_OUTPUT_STREAM;
rv = client->Send(NS_LITERAL_CSTRING("127.0.0.1"), serverPort, (uint8_t*)&data, sizeof(uint32_t), &count);
NS_ENSURE_SUCCESS(rv, -1);
REQUIRE_EQUAL(count, sizeof(uint32_t), "Error");
passed("Request written by Send");
// Wait for server
PumpEvents();
NS_ENSURE_SUCCESS(serverListener->mResult, -1);
// Read response from server
NS_ENSURE_SUCCESS(clientListener->mResult, -1);
mozilla::net::NetAddr clientAddr;
rv = client->GetAddress(&clientAddr);
NS_ENSURE_SUCCESS(rv, -1);
phase = TEST_SEND_API;
rv = server->SendWithAddress(&clientAddr, (uint8_t*)&data, sizeof(uint32_t), &count);
NS_ENSURE_SUCCESS(rv, -1);
REQUIRE_EQUAL(count, sizeof(uint32_t), "Error");
passed("Request written by SendWithAddress");
// Wait for server
PumpEvents();
NS_ENSURE_SUCCESS(serverListener->mResult, -1);
// Read response from server
NS_ENSURE_SUCCESS(clientListener->mResult, -1);
// Close server
printf("*** Attempting to close server ...\n");
server->Close();
client->Close();
PumpEvents();
passed("Server closed");
return 0; // failure is a non-zero return
}

Просмотреть файл

@ -53,6 +53,6 @@ SOURCES += [
CPP_UNIT_TESTS += [
'TestSTSParser.cpp',
'TestUDPServerSocket.cpp',
'TestUDPSocket.cpp',
]

Просмотреть файл

@ -149,6 +149,7 @@
"dom/network/tests/test_network_basics.html": "",
"dom/permission/tests/test_permission_basics.html": "",
"dom/mobilemessage/tests/test_sms_basics.html": "Bug 909036",
"dom/media/tests/ipc/test_ipc.html":"bug 910661",
"dom/tests/mochitest/ajax/jquery/test_jQuery.html": "bug 775227",
"dom/tests/mochitest/ajax/offline/test_simpleManifest.html": "TIMED_OUT",
"dom/tests/mochitest/ajax/offline/test_updatingManifest.html": "TIMED_OUT",

Просмотреть файл

@ -320,6 +320,7 @@
"dom/media/tests/mochitest/test_peerConnection_setRemoteAnswerInStable.html":"",
"dom/media/tests/mochitest/test_peerConnection_setRemoteOfferInHaveLocalOffer.html":"",
"dom/media/tests/mochitest/test_peerConnection_throwInCallbacks.html":"",
"dom/media/tests/ipc/test_ipc.html":"nested ipc not working",
"dom/network/tests/test_networkstats_basics.html":"Will be fixed in bug 858005",
"dom/permission/tests/test_permission_basics.html":"Bug 907770",

Просмотреть файл

@ -325,6 +325,7 @@
"dom/media/tests/mochitest/test_peerConnection_setRemoteAnswerInStable.html":"",
"dom/media/tests/mochitest/test_peerConnection_setRemoteOfferInHaveLocalOffer.html":"",
"dom/media/tests/mochitest/test_peerConnection_throwInCallbacks.html":"",
"dom/media/tests/ipc/test_ipc.html":"nested ipc not working",
"dom/network/tests/test_networkstats_basics.html":"Will be fixed in bug 858005",
"dom/permission/tests/test_permission_basics.html":"https not working, bug 907770",

Просмотреть файл

@ -1556,7 +1556,45 @@ Engine.prototype = {
},
/**
* Sets the .iconURI property of the engine.
* Creates a key by serializing an object that contains the icon's width
* and height.
*
* @param aWidth
* Width of the icon.
* @param aHeight
* Height of the icon.
* @returns key string
*/
_getIconKey: function SRCH_ENG_getIconKey(aWidth, aHeight) {
let keyObj = {
width: aWidth,
height: aHeight
};
return JSON.stringify(keyObj);
},
/**
* Add an icon to the icon map used by getIconURIBySize() and getIcons().
*
* @param aWidth
* Width of the icon.
* @param aHeight
* Height of the icon.
* @param aURISpec
* String with the icon's URI.
*/
_addIconToMap: function SRCH_ENG_addIconToMap(aWidth, aHeight, aURISpec) {
// Use an object instead of a Map() because it needs to be serializable.
this._iconMapObj = this._iconMapObj || {};
let key = this._getIconKey(aWidth, aHeight);
this._iconMapObj[key] = aURISpec;
},
/**
* Sets the .iconURI property of the engine. If both aWidth and aHeight are
* provided an entry will be added to _iconMapObj that will enable accessing
* icon's data through getIcons() and getIconURIBySize() APIs.
*
* @param aIconURL
* A URI string pointing to the engine's icon. Must have a http[s],
@ -1566,13 +1604,12 @@ Engine.prototype = {
* @param aIsPreferred
* Whether or not this icon is to be preferred. Preferred icons can
* override non-preferred icons.
* @param aWidth (optional)
* Width of the icon.
* @param aHeight (optional)
* Height of the icon.
*/
_setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred) {
// If we already have a preferred icon, and this isn't a preferred icon,
// just ignore it.
if (this._hasPreferredIcon && !aIsPreferred)
return;
_setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred, aWidth, aHeight) {
var uri = makeURI(aIconURL);
// Ignore bad URIs
@ -1584,9 +1621,15 @@ Engine.prototype = {
// Only accept remote icons from http[s] or ftp
switch (uri.scheme) {
case "data":
this._iconURI = uri;
notifyAction(this, SEARCH_ENGINE_CHANGED);
this._hasPreferredIcon = aIsPreferred;
if (!this._hasPreferredIcon || aIsPreferred) {
this._iconURI = uri;
notifyAction(this, SEARCH_ENGINE_CHANGED);
this._hasPreferredIcon = aIsPreferred;
}
if (aWidth && aHeight) {
this._addIconToMap(aWidth, aHeight, aIconURL)
}
break;
case "http":
case "https":
@ -1610,7 +1653,12 @@ Engine.prototype = {
}
var str = btoa(String.fromCharCode.apply(null, aByteArray));
aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
let dataURL = ICON_DATAURL_PREFIX + str;
aEngine._iconURI = makeURI(dataURL);
if (aWidth && aHeight) {
aEngine._addIconToMap(aWidth, aHeight, dataURL)
}
// The engine might not have a file yet, if it's being downloaded,
// because the request for the engine file itself (_onLoad) may not
@ -1804,14 +1852,17 @@ Engine.prototype = {
*/
_parseImage: function SRCH_ENG_parseImage(aElement) {
LOG("_parseImage: Image textContent: \"" + limitURILength(aElement.textContent) + "\"");
if (aElement.getAttribute("width") == "16" &&
aElement.getAttribute("height") == "16") {
this._setIcon(aElement.textContent, true);
}
else {
LOG("OpenSearch image must have explicit width=16 height=16: " +
aElement.textContent);
let width = parseInt(aElement.getAttribute("width"), 10);
let height = parseInt(aElement.getAttribute("height"), 10);
let isPrefered = width == 16 && height == 16;
if (isNaN(width) || isNaN(height) || width <= 0 || height <=0) {
LOG("OpenSearch image element must have positive width and height.");
return;
}
this._setIcon(aElement.textContent, isPrefered, width, height);
},
_parseAsMozSearch: function SRCH_ENG_parseAsMoz() {
@ -2209,6 +2260,7 @@ Engine.prototype = {
else
this._readOnly = false;
this._iconURI = makeURI(aJson._iconURL);
this._iconMapObj = aJson._iconMapObj;
for (let i = 0; i < aJson._urls.length; ++i) {
let url = aJson._urls[i];
let engineURL = new EngineURL(url.type || URLTYPE_SEARCH_HTML,
@ -2233,7 +2285,8 @@ Engine.prototype = {
description: this.description,
__searchForm: this.__searchForm,
_iconURL: this._iconURL,
_urls: [url._serializeToJSON() for each(url in this._urls)]
_iconMapObj: this._iconMapObj,
_urls: [url._serializeToJSON() for each(url in this._urls)]
};
if (this._file instanceof Ci.nsILocalFile)
@ -2679,8 +2732,51 @@ Engine.prototype = {
get wrappedJSObject() {
return this;
}
},
/**
* Returns a string with the URL to an engine's icon matching both width and
* height. Returns null if icon with specified dimensions is not found.
*
* @param width
* Width of the requested icon.
* @param height
* Height of the requested icon.
*/
getIconURLBySize: function SRCH_ENG_getIconURLBySize(aWidth, aHeight) {
if (!this._iconMapObj)
return null;
let key = this._getIconKey(aWidth, aHeight);
if (key in this._iconMapObj) {
return this._iconMapObj[key];
}
return null;
},
/**
* Gets an array of all available icons. Each entry is an object with
* width, height and url properties. width and height are numeric and
* represent the icon's dimensions. url is a string with the URL for
* the icon.
*/
getIcons: function SRCH_ENG_getIcons() {
let result = [];
if (!this._iconMapObj)
return result;
for (let key of Object.keys(this._iconMapObj)) {
let iconSize = JSON.parse(key);
result.push({
width: iconSize.width,
height: iconSize.height,
url: this._iconMapObj[key]
});
}
return result;
}
};
// nsISearchSubmission

Просмотреть файл

@ -0,0 +1,22 @@
<!-- 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/. -->
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>IconsTest</ShortName>
<Description>IconsTest. Search by Test.</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/x-icon;base64,ico16</Image>
<Image width="32" height="32">data:image/x-icon;base64,ico32</Image>
<Image width="74" height="74">data:image/png;base64,ico74</Image>
<Url type="application/x-suggestions+json" template="http://api.bing.com/osjson.aspx">
<Param name="query" value="{searchTerms}"/>
<Param name="form" value="MOZW"/>
</Url>
<Url type="text/html" method="GET" template="http://www.bing.com/search">
<Param name="q" value="{searchTerms}"/>
<MozParam name="pc" condition="pref" pref="ms-pc"/>
<Param name="form" value="MOZW"/>
</Url>
<SearchForm>http://www.bing.com/search</SearchForm>
</SearchPlugin>

Просмотреть файл

@ -0,0 +1,78 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Tests getIcons() and getIconURLBySize() on engine with multiple icons.
*/
"use strict";
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://testing-common/httpd.js");
function test_multiIcon() {
let engine = Services.search.getEngineByName("IconsTest");
do_check_neq(engine, null);
do_print("Running tests on IconsTest engine");
do_print("The default should be the 16x16 icon");
do_check_true(engine.iconURI.spec.contains("ico16"));
do_check_true(engine.getIconURLBySize(32,32).contains("ico32"));
do_check_true(engine.getIconURLBySize(74,74).contains("ico74"));
do_print("Invalid dimensions should return null.");
do_check_null(engine.getIconURLBySize(50,50));
let allIcons = engine.getIcons();
do_print("Check that allIcons contains expected icon sizes");
do_check_eq(allIcons.length, 3);
let expectedWidths = [16, 32, 74];
do_check_true(allIcons.every((item) => {
let width = item.width;
do_check_neq(expectedWidths.indexOf(width), -1);
do_check_eq(width, item.height);
let icon = item.url.split(",").pop();
do_check_eq(icon, "ico" + width);
return true;
}));
do_test_finished();
}
function run_test() {
removeMetadata();
updateAppInfo();
let httpServer = new HttpServer();
httpServer.start(4444);
httpServer.registerDirectory("/", do_get_cwd());
do_register_cleanup(function cleanup() {
httpServer.stop(function() {});
});
do_test_pending();
let observer = function(aSubject, aTopic, aData) {
if (aData == "engine-loaded") {
test_multiIcon();
}
};
Services.obs.addObserver(observer, "browser-search-engine-modified", false);
do_print("Adding engine with multiple images");
Services.search.addEngine("http://localhost:4444/data/engineImages.xml",
Ci.nsISearchEngine.DATA_XML, null, false);
do_timeout(12000, function() {
do_throw("Timeout");
});
}

Просмотреть файл

@ -7,6 +7,7 @@ support-files =
data/engine.src
data/engine.xml
data/engine2.xml
data/engineImages.xml
data/ico-size-16x16-png.ico
data/search-metadata.json
data/search.json
@ -27,6 +28,7 @@ support-files =
[test_prefSync.js]
[test_notifications.js]
[test_addEngine_callback.js]
[test_multipleIcons.js]
[test_async.js]
[test_sync.js]
[test_sync_fallback.js]

Просмотреть файл

@ -338,7 +338,15 @@
firstFrameShown : false,
timeUpdateCount : 0,
maxCurrentTimeSeen : 0,
isAudioOnly : false,
_isAudioOnly : false,
get isAudioOnly() { return this._isAudioOnly; },
set isAudioOnly(val) {
this._isAudioOnly = val;
if (!this.isTopLevelSyntheticDocument)
return;
this.video.style.height = this._controlBarHeight + "px";
this.video.style.width = "66%";
},
suppressError : false,
setupStatusFader : function(immediate) {
@ -842,7 +850,10 @@
},
onVolumeMouseInOut : function (event) {
if (this.isVideoWithoutAudioTrack()) {
let doc = this.video.ownerDocument;
let win = doc.defaultView;
if (this.isVideoWithoutAudioTrack() ||
(this.isAudioOnly && this.isTopLevelSyntheticDocument)) {
return;
}
// Ignore events caused by transitions between mute button and volumeStack,
@ -1335,6 +1346,12 @@
dump("videoctl: " + msg + "\n");
},
get isTopLevelSyntheticDocument() {
let doc = this.video.ownerDocument;
let win = doc.defaultView;
return doc.mozSyntheticDocument && win === win.top;
},
_playButtonWidth : 0,
_durationLabelWidth : 0,
_muteButtonWidth : 0,
@ -1343,15 +1360,11 @@
_overlayPlayButtonHeight : 64,
_overlayPlayButtonWidth : 64,
adjustControlSize : function adjustControlSize() {
if (this.isAudioOnly)
let doc = this.video.ownerDocument;
let isAudioOnly = this.isAudioOnly;
if (isAudioOnly && !this.isTopLevelSyntheticDocument)
return;
let videoHeight = this.video.clientHeight;
let videoWidth = this.video.clientWidth;
if (this._overlayPlayButtonHeight > videoHeight || this._overlayPlayButtonWidth > videoWidth)
this.clickToPlay.hidden = true;
// The scrubber has |flex=1|, therefore |minScrubberWidth|
// was generated by empirical testing.
let minScrubberWidth = 25;
@ -1363,6 +1376,12 @@
let minHeightForControlBar = this._controlBarHeight;
let minWidthOnlyPlayPause = this._playButtonWidth + this._muteButtonWidth;
let videoHeight = isAudioOnly ? minHeightForControlBar : this.video.clientHeight;
let videoWidth = isAudioOnly ? minWidthAllControls : this.video.clientWidth;
if (this._overlayPlayButtonHeight > videoHeight || this._overlayPlayButtonWidth > videoWidth)
this.clickToPlay.hidden = true;
let size = "normal";
if (videoHeight < minHeightForControlBar)
size = "hidden";

Просмотреть файл

@ -8,6 +8,7 @@ const {Cc, Ci, Cu} = require("chrome");
const {colorUtils} = require("devtools/css-color");
const {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
const MAX_ITERATIONS = 100;
const REGEX_QUOTES = /^".*?"|^".*/;
const REGEX_URL = /^url\(["']?(.+?)(?::(\d+))?["']?\)/;
const REGEX_WHITESPACE = /^\s+/;
@ -135,6 +136,7 @@ OutputParser.prototype = {
let dirty = false;
let matched = null;
let nameValueSupported = false;
let i = 0;
let trimMatchFromStart = function(match) {
text = text.substr(match.length);
@ -207,6 +209,14 @@ OutputParser.prototype = {
}
dirty = false;
// Prevent this loop from slowing down the browser with too
// many nodes being appended into output.
i++;
if (i > MAX_ITERATIONS) {
trimMatchFromStart(text);
this._appendTextNode(text);
}
}
return this._toDOM();
@ -312,14 +322,10 @@ OutputParser.prototype = {
*/
_appendTextNode: function(text) {
let lastItem = this.parsed[this.parsed.length - 1];
if (typeof lastItem !== "undefined" && lastItem.nodeName === "#text") {
lastItem.nodeValue += text;
if (typeof lastItem === "string") {
this.parsed[this.parsed.length - 1] = lastItem + text
} else {
let win = Services.appShell.hiddenDOMWindow;
let doc = win.document;
let textNode = doc.createTextNode(text);
this.parsed.push(textNode);
this.parsed.push(text);
}
},
@ -335,7 +341,11 @@ OutputParser.prototype = {
let frag = doc.createDocumentFragment();
for (let item of this.parsed) {
frag.appendChild(item);
if (typeof item === "string") {
frag.appendChild(doc.createTextNode(item));
} else {
frag.appendChild(item);
}
}
this.parsed.length = 0;

Просмотреть файл

@ -109,6 +109,18 @@ RemoteWebProgressManager.prototype = {
return [deserialized, aState];
},
_callProgressListeners: function(methodName, ...args) {
for (let p of this._progressListeners) {
if (p[methodName]) {
try {
p[methodName].apply(p, args);
} catch (ex) {
Cu.reportError("RemoteWebProgress failed to call " + methodName + ": " + ex + "\n");
}
}
}
},
receiveMessage: function (aMessage) {
let json = aMessage.json;
let objects = aMessage.objects;
@ -133,9 +145,7 @@ RemoteWebProgressManager.prototype = {
switch (aMessage.name) {
case "Content:StateChange":
for (let p of this._progressListeners) {
p.onStateChange(webProgress, request, json.stateFlags, json.status);
}
this._callProgressListeners("onStateChange", webProgress, request, json.stateFlags, json.status);
break;
case "Content:LocationChange":
@ -150,9 +160,7 @@ RemoteWebProgressManager.prototype = {
this._browser._imageDocument = null;
}
for (let p of this._progressListeners) {
p.onLocationChange(webProgress, request, location);
}
this._callProgressListeners("onLocationChange", webProgress, request, location);
break;
case "Content:SecurityChange":
@ -166,15 +174,11 @@ RemoteWebProgressManager.prototype = {
this._browser._securityUI._update(status, state);
}
for (let p of this._progressListeners) {
p.onSecurityChange(webProgress, request, state);
}
this._callProgressListeners("onSecurityChange", webProgress, request, state);
break;
case "Content:StatusChange":
for (let p of this._progressListeners) {
p.onStatusChange(webProgress, request, json.status, json.message);
}
this._callProgressListeners("onStatusChange", webProgress, request, json.status, json.message);
break;
}
}