Merge mozilla-central and inbound

This commit is contained in:
Ed Morley 2013-06-13 11:33:19 +01:00
commit 0949a9435f
71 changed files with 966 additions and 249 deletions

View File

@ -352,6 +352,7 @@ MenuPopup.prototype = {
window.addEventListener("keypress", this, true); window.addEventListener("keypress", this, true);
window.addEventListener("mousedown", this, true); window.addEventListener("mousedown", this, true);
Elements.stack.addEventListener("PopupChanged", this, false); Elements.stack.addEventListener("PopupChanged", this, false);
Elements.browsers.addEventListener("PanBegin", this, false);
this._panel.hidden = false; this._panel.hidden = false;
this._position(aPositionOptions || {}); this._position(aPositionOptions || {});
@ -382,6 +383,7 @@ MenuPopup.prototype = {
window.removeEventListener("keypress", this, true); window.removeEventListener("keypress", this, true);
window.removeEventListener("mousedown", this, true); window.removeEventListener("mousedown", this, true);
Elements.stack.removeEventListener("PopupChanged", this, false); Elements.stack.removeEventListener("PopupChanged", this, false);
Elements.browsers.removeEventListener("PanBegin", this, false);
let self = this; let self = this;
this._panel.addEventListener("transitionend", function () { this._panel.addEventListener("transitionend", function () {
@ -497,6 +499,9 @@ MenuPopup.prototype = {
this.hide(); this.hide();
} }
break; break;
case "PanBegin":
this.hide();
break;
} }
} }
}; };

View File

@ -1128,3 +1128,5 @@ sys/thr.h
sys/user.h sys/user.h
kvm.h kvm.h
spawn.h spawn.h
err.h
xlocale.h

View File

@ -21,7 +21,7 @@ interface nsIDOMBlob;
#include "jsapi.h" #include "jsapi.h"
%} %}
[scriptable, builtinclass, uuid(5bc978f2-41e5-4349-a12d-b018092271f7)] [scriptable, builtinclass, uuid(ac97e161-9f1d-4163-adc9-e9a59e18682c)]
interface nsIXMLHttpRequestEventTarget : nsIDOMEventTarget { interface nsIXMLHttpRequestEventTarget : nsIDOMEventTarget {
// event handler attributes // event handler attributes
[implicit_jscontext] attribute jsval onabort; [implicit_jscontext] attribute jsval onabort;
@ -133,7 +133,7 @@ interface nsIXMLHttpRequest : nsISupports
* The string representing the status of the response for * The string representing the status of the response for
* HTTP requests. * HTTP requests.
*/ */
readonly attribute DOMString statusText; readonly attribute ACString statusText;
/** /**
* If the request has been sent already, this method will * If the request has been sent already, this method will
@ -148,7 +148,7 @@ interface nsIXMLHttpRequest : nsISupports
* @returns A string containing all of the response headers. * @returns A string containing all of the response headers.
* The empty string if the response has not yet been received. * The empty string if the response has not yet been received.
*/ */
DOMString getAllResponseHeaders(); ACString getAllResponseHeaders();
/** /**
* Returns the text of the header with the specified name for * Returns the text of the header with the specified name for
@ -159,7 +159,7 @@ interface nsIXMLHttpRequest : nsISupports
* NULL if the response has not yet been received or the * NULL if the response has not yet been received or the
* header does not exist in the response. * header does not exist in the response.
*/ */
ACString getResponseHeader(in AUTF8String header); ACString getResponseHeader(in ACString header);
%{C++ %{C++
// note this is NOT virtual so this won't muck with the vtable! // note this is NOT virtual so this won't muck with the vtable!
@ -189,7 +189,7 @@ interface nsIXMLHttpRequest : nsISupports
* @param password (optional) A password for authentication if necessary. * @param password (optional) A password for authentication if necessary.
* The default value is the empty string * The default value is the empty string
*/ */
[optional_argc] void open(in AUTF8String method, in AUTF8String url, [optional_argc] void open(in ACString method, in AUTF8String url,
[optional] in boolean async, [optional] in boolean async,
[optional,Undefined(Empty)] in DOMString user, [optional,Undefined(Empty)] in DOMString user,
[optional,Undefined(Empty)] in DOMString password); [optional,Undefined(Empty)] in DOMString password);
@ -237,7 +237,7 @@ interface nsIXMLHttpRequest : nsISupports
* @param header The name of the header to set in the request. * @param header The name of the header to set in the request.
* @param value The body of the header. * @param value The body of the header.
*/ */
void setRequestHeader(in AUTF8String header, in AUTF8String value); void setRequestHeader(in ACString header, in ACString value);
/** /**
* The amount of milliseconds a request can take before being terminated. * The amount of milliseconds a request can take before being terminated.

View File

@ -139,11 +139,11 @@ using namespace mozilla::dom;
#define NS_PROGRESS_EVENT_INTERVAL 50 #define NS_PROGRESS_EVENT_INTERVAL 50
#define IMPL_STRING_GETTER(_name) \ #define IMPL_CSTRING_GETTER(_name) \
NS_IMETHODIMP \ NS_IMETHODIMP \
nsXMLHttpRequest::_name(nsAString& aOut) \ nsXMLHttpRequest::_name(nsACString& aOut) \
{ \ { \
nsString tmp; \ nsCString tmp; \
_name(tmp); \ _name(tmp); \
aOut = tmp; \ aOut = tmp; \
return NS_OK; \ return NS_OK; \
@ -1128,9 +1128,9 @@ nsXMLHttpRequest::Status()
return status; return status;
} }
IMPL_STRING_GETTER(GetStatusText) IMPL_CSTRING_GETTER(GetStatusText)
void void
nsXMLHttpRequest::GetStatusText(nsString& aStatusText) nsXMLHttpRequest::GetStatusText(nsCString& aStatusText)
{ {
nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel(); nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel();
@ -1152,17 +1152,8 @@ nsXMLHttpRequest::GetStatusText(nsString& aStatusText)
} }
} }
nsCString statusText; httpChannel->GetResponseStatusText(aStatusText);
httpChannel->GetResponseStatusText(statusText);
if (statusText.IsVoid()) {
aStatusText.SetIsVoid(true);
} else {
// We use UTF8ToNewUnicode here because it truncates after invalid UTF-8
// characters, CopyUTF8toUTF16 just doesn't copy in that case.
uint32_t length;
PRUnichar* chars = UTF8ToNewUnicode(statusText, &length);
aStatusText.Adopt(chars, length);
}
} }
void void
@ -1286,10 +1277,10 @@ nsXMLHttpRequest::IsSafeHeader(const nsACString& header, nsIHttpChannel* httpCha
return isSafe; return isSafe;
} }
/* DOMString getAllResponseHeaders(); */ /* ByteString getAllResponseHeaders(); */
IMPL_STRING_GETTER(GetAllResponseHeaders) IMPL_CSTRING_GETTER(GetAllResponseHeaders)
void void
nsXMLHttpRequest::GetAllResponseHeaders(nsString& aResponseHeaders) nsXMLHttpRequest::GetAllResponseHeaders(nsCString& aResponseHeaders)
{ {
aResponseHeaders.Truncate(); aResponseHeaders.Truncate();
@ -1303,7 +1294,7 @@ nsXMLHttpRequest::GetAllResponseHeaders(nsString& aResponseHeaders)
if (nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel()) { if (nsCOMPtr<nsIHttpChannel> httpChannel = GetCurrentHttpChannel()) {
nsRefPtr<nsHeaderVisitor> visitor = new nsHeaderVisitor(this, httpChannel); nsRefPtr<nsHeaderVisitor> visitor = new nsHeaderVisitor(this, httpChannel);
if (NS_SUCCEEDED(httpChannel->VisitResponseHeaders(visitor))) { if (NS_SUCCEEDED(httpChannel->VisitResponseHeaders(visitor))) {
CopyASCIItoUTF16(visitor->Headers(), aResponseHeaders); aResponseHeaders = visitor->Headers();
} }
return; return;
} }
@ -1316,10 +1307,10 @@ nsXMLHttpRequest::GetAllResponseHeaders(nsString& aResponseHeaders)
nsAutoCString value; nsAutoCString value;
if (NS_SUCCEEDED(mChannel->GetContentType(value))) { if (NS_SUCCEEDED(mChannel->GetContentType(value))) {
aResponseHeaders.AppendLiteral("Content-Type: "); aResponseHeaders.AppendLiteral("Content-Type: ");
AppendASCIItoUTF16(value, aResponseHeaders); aResponseHeaders.Append(value);
if (NS_SUCCEEDED(mChannel->GetContentCharset(value)) && !value.IsEmpty()) { if (NS_SUCCEEDED(mChannel->GetContentCharset(value)) && !value.IsEmpty()) {
aResponseHeaders.AppendLiteral(";charset="); aResponseHeaders.AppendLiteral(";charset=");
AppendASCIItoUTF16(value, aResponseHeaders); aResponseHeaders.Append(value);
} }
aResponseHeaders.AppendLiteral("\r\n"); aResponseHeaders.AppendLiteral("\r\n");
} }
@ -2950,7 +2941,7 @@ nsXMLHttpRequest::Send(nsIVariant* aVariant, const Nullable<RequestBody>& aBody)
return rv; return rv;
} }
/* void setRequestHeader (in AUTF8String header, in AUTF8String value); */ /* void setRequestHeader (in ByteString header, in ByteString value); */
// http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader // http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader
NS_IMETHODIMP NS_IMETHODIMP
nsXMLHttpRequest::SetRequestHeader(const nsACString& header, nsXMLHttpRequest::SetRequestHeader(const nsACString& header,

View File

@ -242,19 +242,18 @@ public:
uint16_t ReadyState(); uint16_t ReadyState();
// request // request
void Open(const nsAString& aMethod, const nsAString& aUrl, bool aAsync, void Open(const nsACString& aMethod, const nsAString& aUrl, bool aAsync,
const mozilla::dom::Optional<nsAString>& aUser, const mozilla::dom::Optional<nsAString>& aUser,
const mozilla::dom::Optional<nsAString>& aPassword, const mozilla::dom::Optional<nsAString>& aPassword,
ErrorResult& aRv) ErrorResult& aRv)
{ {
aRv = Open(NS_ConvertUTF16toUTF8(aMethod), NS_ConvertUTF16toUTF8(aUrl), aRv = Open(aMethod, NS_ConvertUTF16toUTF8(aUrl),
aAsync, aUser, aPassword); aAsync, aUser, aPassword);
} }
void SetRequestHeader(const nsAString& aHeader, const nsAString& aValue, void SetRequestHeader(const nsACString& aHeader, const nsACString& aValue,
ErrorResult& aRv) ErrorResult& aRv)
{ {
aRv = SetRequestHeader(NS_ConvertUTF16toUTF8(aHeader), aRv = SetRequestHeader(aHeader, aValue);
NS_ConvertUTF16toUTF8(aValue));
} }
uint32_t Timeout() uint32_t Timeout()
{ {
@ -400,7 +399,7 @@ public:
// response // response
uint32_t Status(); uint32_t Status();
void GetStatusText(nsString& aStatusText); void GetStatusText(nsCString& aStatusText);
void GetResponseHeader(const nsACString& aHeader, nsACString& aResult, void GetResponseHeader(const nsACString& aHeader, nsACString& aResult,
ErrorResult& aRv); ErrorResult& aRv);
void GetResponseHeader(const nsAString& aHeader, nsString& aResult, void GetResponseHeader(const nsAString& aHeader, nsString& aResult,
@ -416,7 +415,7 @@ public:
CopyASCIItoUTF16(result, aResult); CopyASCIItoUTF16(result, aResult);
} }
} }
void GetAllResponseHeaders(nsString& aResponseHeaders); void GetAllResponseHeaders(nsCString& aResponseHeaders);
bool IsSafeHeader(const nsACString& aHeaderName, nsIHttpChannel* aHttpChannel); bool IsSafeHeader(const nsACString& aHeaderName, nsIHttpChannel* aHttpChannel);
void OverrideMimeType(const nsAString& aMimeType) void OverrideMimeType(const nsAString& aMimeType)
{ {

View File

@ -2,6 +2,7 @@
<html> <html>
<!-- <!--
https://bugzilla.mozilla.org/show_bug.cgi?id=638112 https://bugzilla.mozilla.org/show_bug.cgi?id=638112
https://bugzilla.mozilla.org/show_bug.cgi?id=796850
--> -->
<head> <head>
<title>Test for Bug 638112</title> <title>Test for Bug 638112</title>
@ -10,15 +11,18 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=638112
</head> </head>
<body> <body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=638112">Mozilla Bug 638112</a> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=638112">Mozilla Bug 638112</a>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=796850">Mozilla Bug 796850</a>
<p id="display"></p> <p id="display"></p>
<div id="content" style="display: none"> <div id="content" style="display: none">
</div> </div>
<pre id="test"> <pre id="test">
<script type="text/javascript"> <script type="text/javascript">
SimpleTest.expectAssertions(1); /** Test for Bug 638112, revised for Bug 796850 **/
/** Test for Bug 638112 **/ /* Bug 796850 changed the type of statusText to ByteString. As a result it is
* now considered to be raw 8 bit encoded rather than UTF8.
*/
function run_test() { function run_test() {
var req = new XMLHttpRequest(); var req = new XMLHttpRequest();
@ -26,7 +30,7 @@ function run_test() {
req.send(null); req.send(null);
var statusText = req.statusText; var statusText = req.statusText;
is(statusText, "Information Sans-Autorit", ""); is(statusText, "Information Sans-Autorit\u00E9", "");
SimpleTest.finish(); SimpleTest.finish();
} }

View File

@ -114,7 +114,8 @@ HTMLTrackElement::WrapNode(JSContext* aCx, JS::Handle<JSObject*> aScope)
bool bool
HTMLTrackElement::IsWebVTTEnabled() HTMLTrackElement::IsWebVTTEnabled()
{ {
return HTMLTrackElementBinding::PrefEnabled(); // Our callee does not use its arguments.
return HTMLTrackElementBinding::ConstructorEnabled(nullptr, JS::NullPtr());
} }
TextTrack* TextTrack*

View File

@ -3934,7 +3934,8 @@ ResolvePrototype(nsIXPConnect *aXPConnect, nsGlobalWindow *aWin, JSContext *cx,
} }
static bool static bool
ConstructorEnabled(const nsGlobalNameStruct *aStruct, nsGlobalWindow *aWin) OldBindingConstructorEnabled(const nsGlobalNameStruct *aStruct,
nsGlobalWindow *aWin)
{ {
MOZ_ASSERT(aStruct->mType == nsGlobalNameStruct::eTypeClassConstructor || MOZ_ASSERT(aStruct->mType == nsGlobalNameStruct::eTypeClassConstructor ||
aStruct->mType == nsGlobalNameStruct::eTypeExternalClassInfo); aStruct->mType == nsGlobalNameStruct::eTypeExternalClassInfo);
@ -3998,11 +3999,7 @@ nsWindowSH::GlobalResolve(nsGlobalWindow *aWin, JSContext *cx,
name_struct->mDefineDOMInterface; name_struct->mDefineDOMInterface;
if (define) { if (define) {
if (name_struct->mType == nsGlobalNameStruct::eTypeClassConstructor && if (name_struct->mType == nsGlobalNameStruct::eTypeClassConstructor &&
!ConstructorEnabled(name_struct, aWin)) { !OldBindingConstructorEnabled(name_struct, aWin)) {
return NS_OK;
}
if (name_struct->mPrefEnabled && !(*name_struct->mPrefEnabled)()) {
return NS_OK; return NS_OK;
} }
@ -4019,6 +4016,14 @@ nsWindowSH::GlobalResolve(nsGlobalWindow *aWin, JSContext *cx,
global = obj; global = obj;
} }
// Check whether our constructor is enabled after we unwrap Xrays, since
// we don't want to define an interface on the Xray if it's disabled in
// the target global, even if it's enabled in the Xray's global.
if (name_struct->mConstructorEnabled &&
!(*name_struct->mConstructorEnabled)(cx, global)) {
return NS_OK;
}
bool enabled; bool enabled;
JS::Rooted<JSObject*> interfaceObject(cx, define(cx, global, id, &enabled)); JS::Rooted<JSObject*> interfaceObject(cx, define(cx, global, id, &enabled));
if (enabled) { if (enabled) {
@ -4081,7 +4086,7 @@ nsWindowSH::GlobalResolve(nsGlobalWindow *aWin, JSContext *cx,
if (name_struct->mType == nsGlobalNameStruct::eTypeClassConstructor || if (name_struct->mType == nsGlobalNameStruct::eTypeClassConstructor ||
name_struct->mType == nsGlobalNameStruct::eTypeExternalClassInfo) { name_struct->mType == nsGlobalNameStruct::eTypeExternalClassInfo) {
if (!ConstructorEnabled(name_struct, aWin)) { if (!OldBindingConstructorEnabled(name_struct, aWin)) {
return NS_OK; return NS_OK;
} }
@ -4888,16 +4893,21 @@ nsNavigatorSH::NewResolve(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
mozilla::dom::ConstructNavigatorProperty construct = name_struct->mConstructNavigatorProperty; mozilla::dom::ConstructNavigatorProperty construct = name_struct->mConstructNavigatorProperty;
MOZ_ASSERT(construct); MOZ_ASSERT(construct);
if (name_struct->mPrefEnabled && !(*name_struct->mPrefEnabled)()) {
return NS_OK;
}
JS::Rooted<JSObject*> naviObj(cx, js::CheckedUnwrap(obj, /* stopAtOuter = */ false)); JS::Rooted<JSObject*> naviObj(cx, js::CheckedUnwrap(obj, /* stopAtOuter = */ false));
NS_ENSURE_TRUE(naviObj, NS_ERROR_DOM_SECURITY_ERR); NS_ENSURE_TRUE(naviObj, NS_ERROR_DOM_SECURITY_ERR);
JS::Rooted<JSObject*> domObject(cx); JS::Rooted<JSObject*> domObject(cx);
{ {
JSAutoCompartment ac(cx, naviObj); JSAutoCompartment ac(cx, naviObj);
// Check whether our constructor is enabled after we unwrap Xrays, since
// we don't want to define an interface on the Xray if it's disabled in
// the target global, even if it's enabled in the Xray's global.
if (name_struct->mConstructorEnabled &&
!(*name_struct->mConstructorEnabled)(cx, naviObj)) {
return NS_OK;
}
domObject = construct(cx, naviObj); domObject = construct(cx, naviObj);
if (!domObject) { if (!domObject) {
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;

View File

@ -825,7 +825,7 @@ nsScriptNameSpaceManager::Observe(nsISupports* aSubject, const char* aTopic,
void void
nsScriptNameSpaceManager::RegisterDefineDOMInterface(const nsAFlatString& aName, nsScriptNameSpaceManager::RegisterDefineDOMInterface(const nsAFlatString& aName,
mozilla::dom::DefineInterface aDefineDOMInterface, mozilla::dom::DefineInterface aDefineDOMInterface,
mozilla::dom::PrefEnabled aPrefEnabled) mozilla::dom::ConstructorEnabled* aConstructorEnabled)
{ {
nsGlobalNameStruct *s = AddToHash(&mGlobalNames, &aName); nsGlobalNameStruct *s = AddToHash(&mGlobalNames, &aName);
if (s) { if (s) {
@ -833,7 +833,7 @@ nsScriptNameSpaceManager::RegisterDefineDOMInterface(const nsAFlatString& aName,
s->mType = nsGlobalNameStruct::eTypeNewDOMBinding; s->mType = nsGlobalNameStruct::eTypeNewDOMBinding;
} }
s->mDefineDOMInterface = aDefineDOMInterface; s->mDefineDOMInterface = aDefineDOMInterface;
s->mPrefEnabled = aPrefEnabled; s->mConstructorEnabled = aConstructorEnabled;
} }
} }
@ -841,7 +841,7 @@ void
nsScriptNameSpaceManager::RegisterNavigatorDOMConstructor( nsScriptNameSpaceManager::RegisterNavigatorDOMConstructor(
const nsAFlatString& aName, const nsAFlatString& aName,
mozilla::dom::ConstructNavigatorProperty aNavConstructor, mozilla::dom::ConstructNavigatorProperty aNavConstructor,
mozilla::dom::PrefEnabled aPrefEnabled) mozilla::dom::ConstructorEnabled* aConstructorEnabled)
{ {
nsGlobalNameStruct *s = AddToHash(&mNavigatorNames, &aName); nsGlobalNameStruct *s = AddToHash(&mNavigatorNames, &aName);
if (s) { if (s) {
@ -849,7 +849,7 @@ nsScriptNameSpaceManager::RegisterNavigatorDOMConstructor(
s->mType = nsGlobalNameStruct::eTypeNewDOMBinding; s->mType = nsGlobalNameStruct::eTypeNewDOMBinding;
} }
s->mConstructNavigatorProperty = aNavConstructor; s->mConstructNavigatorProperty = aNavConstructor;
s->mPrefEnabled = aPrefEnabled; s->mConstructorEnabled = aConstructorEnabled;
} }
} }

View File

@ -55,6 +55,9 @@ struct nsGlobalNameStruct
eTypeExternalConstructorAlias eTypeExternalConstructorAlias
} mType; } mType;
// mChromeOnly is only used for structs that define non-WebIDL things
// (possibly in addition to WebIDL ones). In particular, it's not even
// initialized for eTypeNewDOMBinding structs.
bool mChromeOnly; bool mChromeOnly;
bool mDisabled; bool mDisabled;
@ -71,7 +74,8 @@ struct nsGlobalNameStruct
mozilla::dom::DefineInterface mDefineDOMInterface; // for window mozilla::dom::DefineInterface mDefineDOMInterface; // for window
mozilla::dom::ConstructNavigatorProperty mConstructNavigatorProperty; // for navigator mozilla::dom::ConstructNavigatorProperty mConstructNavigatorProperty; // for navigator
}; };
mozilla::dom::PrefEnabled mPrefEnabled; // May be null if not pref controlled // May be null if enabled unconditionally
mozilla::dom::ConstructorEnabled* mConstructorEnabled;
}; };
@ -140,11 +144,11 @@ public:
void RegisterDefineDOMInterface(const nsAFlatString& aName, void RegisterDefineDOMInterface(const nsAFlatString& aName,
mozilla::dom::DefineInterface aDefineDOMInterface, mozilla::dom::DefineInterface aDefineDOMInterface,
mozilla::dom::PrefEnabled aPrefEnabled); mozilla::dom::ConstructorEnabled* aConstructorEnabled);
void RegisterNavigatorDOMConstructor(const nsAFlatString& aName, void RegisterNavigatorDOMConstructor(const nsAFlatString& aName,
mozilla::dom::ConstructNavigatorProperty aNavConstructor, mozilla::dom::ConstructNavigatorProperty aNavConstructor,
mozilla::dom::PrefEnabled aPrefEnabled); mozilla::dom::ConstructorEnabled* aConstructorEnabled);
typedef PLDHashOperator typedef PLDHashOperator
(* GlobalNameEnumerator)(const nsAString& aGlobalName, void* aClosure); (* GlobalNameEnumerator)(const nsAString& aGlobalName, void* aClosure);

View File

@ -7,8 +7,10 @@
#include <algorithm> #include <algorithm>
#include <stdarg.h> #include <stdarg.h>
#include "prprf.h"
#include "mozilla/DebugOnly.h" #include "mozilla/DebugOnly.h"
#include "mozilla/FloatingPoint.h" #include "mozilla/FloatingPoint.h"
#include "mozilla/Assertions.h"
#include "BindingUtils.h" #include "BindingUtils.h"
@ -1899,5 +1901,83 @@ ConstructJSImplementation(JSContext* aCx, const char* aContractId,
return window.forget(); return window.forget();
} }
bool
NonVoidByteStringToJsval(JSContext *cx, const nsACString &str,
JS::MutableHandle<JS::Value> rval)
{
if (str.IsEmpty()) {
rval.set(JS_GetEmptyStringValue(cx));
return true;
}
// ByteStrings are not UTF-8 encoded.
JSString* jsStr = JS_NewStringCopyN(cx, str.Data(), str.Length());
if (!jsStr)
return false;
rval.setString(jsStr);
return true;
}
bool
ConvertJSValueToByteString(JSContext* cx, JS::Handle<JS::Value> v,
JS::MutableHandle<JS::Value> pval, bool nullable,
nsACString& result)
{
JSString *s;
if (v.isString()) {
s = v.toString();
} else {
if (nullable && v.isNullOrUndefined()) {
result.SetIsVoid(true);
return true;
}
s = JS_ValueToString(cx, v);
if (!s) {
return false;
}
pval.set(JS::StringValue(s)); // Root the new string.
}
size_t length;
const jschar *chars = JS_GetStringCharsZAndLength(cx, s, &length);
if (!chars) {
return false;
}
// Conversion from Javascript string to ByteString is only valid if all
// characters < 256.
for (size_t i = 0; i < length; i++) {
if (chars[i] > 255) {
// The largest unsigned 64 bit number (18,446,744,073,709,551,615) has
// 20 digits, plus one more for the null terminator.
char index[21];
MOZ_STATIC_ASSERT(sizeof(size_t) <= 8, "index array too small");
PR_snprintf(index, sizeof(index), "%d", i);
// A jschar is 16 bits long. The biggest unsigned 16 bit
// number (65,535) has 5 digits, plus one more for the null
// terminator.
char badChar[6];
MOZ_STATIC_ASSERT(sizeof(jschar) <= 2, "badChar array too small");
PR_snprintf(badChar, sizeof(badChar), "%d", chars[i]);
ThrowErrorMessage(cx, MSG_INVALID_BYTESTRING, index, badChar);
return false;
}
}
if (length >= UINT32_MAX) {
return false;
}
result.SetCapacity(length+1);
JS_EncodeStringToBuffer(cx, s, result.BeginWriting(), length);
result.BeginWriting()[length] = '\0';
result.SetLength(length);
return true;
}
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla

View File

@ -1582,6 +1582,11 @@ ConvertJSValueToString(JSContext* cx, JS::Handle<JS::Value> v,
return true; return true;
} }
bool
ConvertJSValueToByteString(JSContext* cx, JS::Handle<JS::Value> v,
JS::MutableHandle<JS::Value> pval, bool nullable,
nsACString& result);
// Class for holding the type of members of a union. The union type has an enum // Class for holding the type of members of a union. The union type has an enum
// to keep track of which of its UnionMembers has been constructed. // to keep track of which of its UnionMembers has been constructed.
template<class T> template<class T>
@ -2057,6 +2062,24 @@ bool
RegisterForDeferredFinalization(DeferredFinalizeStartFunction start, RegisterForDeferredFinalization(DeferredFinalizeStartFunction start,
DeferredFinalizeFunction run); DeferredFinalizeFunction run);
/**
* Convert an nsCString to jsval, returning true on success.
* These functions are intended for ByteString implementations.
* As such, the string is not UTF-8 encoded. Any UTF8 strings passed to these
* methods will be mangled.
*/
bool NonVoidByteStringToJsval(JSContext *cx, const nsACString &str,
JS::MutableHandle<JS::Value> rval);
inline bool ByteStringToJsval(JSContext *cx, const nsACString &str,
JS::MutableHandle<JS::Value> rval)
{
if (str.IsVoid()) {
rval.setNull();
return true;
}
return NonVoidByteStringToJsval(cx, str, rval);
}
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla

View File

@ -1978,7 +1978,11 @@ class CGPrefEnabledNative(CGAbstractMethod):
if the method returns true. if the method returns true.
""" """
def __init__(self, descriptor): def __init__(self, descriptor):
CGAbstractMethod.__init__(self, descriptor, 'PrefEnabled', 'bool', []) CGAbstractMethod.__init__(self, descriptor,
'ConstructorEnabled', 'bool',
[Argument("JSContext*", "/* unused */"),
Argument("JS::Handle<JSObject*>",
"/* unused */")])
def definition_body(self): def definition_body(self):
return " return %s::PrefEnabled();" % self.descriptor.nativeType return " return %s::PrefEnabled();" % self.descriptor.nativeType
@ -1991,13 +1995,33 @@ class CGPrefEnabled(CGAbstractMethod):
on the global if the pref is true. on the global if the pref is true.
""" """
def __init__(self, descriptor): def __init__(self, descriptor):
CGAbstractMethod.__init__(self, descriptor, 'PrefEnabled', 'bool', []) CGAbstractMethod.__init__(self, descriptor,
'ConstructorEnabled', 'bool',
[Argument("JSContext*", "/* unused */"),
Argument("JS::Handle<JSObject*>",
"/* unused */")])
def definition_body(self): def definition_body(self):
pref = self.descriptor.interface.getExtendedAttribute("Pref") pref = self.descriptor.interface.getExtendedAttribute("Pref")
assert isinstance(pref, list) and len(pref) == 1 assert isinstance(pref, list) and len(pref) == 1
return " return Preferences::GetBool(\"%s\");" % pref[0] return " return Preferences::GetBool(\"%s\");" % pref[0]
class CGConstructorEnabledChromeOnly(CGAbstractMethod):
"""
A method for testing whether the object we're going to be defined
on is chrome so we can decide whether our constructor should be
enabled.
"""
def __init__(self, descriptor):
assert descriptor.interface.getExtendedAttribute("ChromeOnly")
CGAbstractMethod.__init__(self, descriptor,
'ConstructorEnabled', 'bool',
[Argument("JSContext*", "aCx"),
Argument("JS::Handle<JSObject*>", "aObj")])
def definition_body(self):
return " return %s;" % GetAccessCheck(self.descriptor, "aObj")
class CGIsMethod(CGAbstractMethod): class CGIsMethod(CGAbstractMethod):
def __init__(self, descriptor): def __init__(self, descriptor):
args = [Argument('JSObject*', 'obj')] args = [Argument('JSObject*', 'obj')]
@ -3189,7 +3213,7 @@ for (uint32_t i = 0; i < length; ++i) {
declType=CGGeneric(declType), declType=CGGeneric(declType),
holderType=holderType) holderType=holderType)
if type.isString(): if type.isDOMString():
assert not isEnforceRange and not isClamp assert not isEnforceRange and not isClamp
treatAs = { treatAs = {
@ -3255,6 +3279,24 @@ for (uint32_t i = 0; i < length; ++i) {
declType=CGGeneric(declType), declType=CGGeneric(declType),
holderType=CGGeneric("FakeDependentString")) holderType=CGGeneric("FakeDependentString"))
if type.isByteString():
assert not isEnforceRange and not isClamp
nullable = toStringBool(type.nullable())
conversionCode = (
"if (!ConvertJSValueToByteString(cx, ${val}, ${mutableVal},"
" %s, ${declName})) {\n"
"%s\n"
"}" % (nullable, exceptionCodeIndented.define()))
# ByteString arguments cannot have a default value.
assert defaultValue is None
return JSToNativeConversionInfo(
conversionCode,
declType=CGGeneric("nsCString"),
dealWithOptional=isOptional)
if type.isEnum(): if type.isEnum():
assert not isEnforceRange and not isClamp assert not isEnforceRange and not isClamp
@ -3958,12 +4000,18 @@ if (!returnArray) {
wrappingCode += wrapAndSetPtr(wrap, failed) wrappingCode += wrapAndSetPtr(wrap, failed)
return (wrappingCode, False) return (wrappingCode, False)
if type.isString(): if type.isDOMString():
if type.nullable(): if type.nullable():
return (wrapAndSetPtr("xpc::StringToJsval(cx, %s, ${jsvalRef}.address())" % result), False) return (wrapAndSetPtr("xpc::StringToJsval(cx, %s, ${jsvalRef}.address())" % result), False)
else: else:
return (wrapAndSetPtr("xpc::NonVoidStringToJsval(cx, %s, ${jsvalRef}.address())" % result), False) return (wrapAndSetPtr("xpc::NonVoidStringToJsval(cx, %s, ${jsvalRef}.address())" % result), False)
if type.isByteString():
if type.nullable():
return (wrapAndSetPtr("ByteStringToJsval(cx, %s, ${jsvalHandle})" % result), False)
else:
return (wrapAndSetPtr("NonVoidByteStringToJsval(cx, %s, ${jsvalHandle})" % result), False)
if type.isEnum(): if type.isEnum():
if type.nullable(): if type.nullable():
resultLoc = "%s.Value()" % result resultLoc = "%s.Value()" % result
@ -4179,10 +4227,12 @@ def getRetvalDeclarationForType(returnType, descriptorProvider,
if returnType.nullable(): if returnType.nullable():
result = CGTemplatedType("Nullable", result) result = CGTemplatedType("Nullable", result)
return result, False, None, None return result, False, None, None
if returnType.isString(): if returnType.isDOMString():
if isMember: if isMember:
return CGGeneric("nsString"), True, None, None return CGGeneric("nsString"), True, None, None
return CGGeneric("DOMString"), True, None, None return CGGeneric("DOMString"), True, None, None
if returnType.isByteString():
return CGGeneric("nsCString"), True, None, None
if returnType.isEnum(): if returnType.isEnum():
result = CGGeneric(returnType.unroll().inner.identifier.name) result = CGGeneric(returnType.unroll().inner.identifier.name)
if returnType.nullable(): if returnType.nullable():
@ -5655,9 +5705,12 @@ def getUnionAccessorSignatureType(type, descriptorProvider):
typeName = CGWrapper(typeName, post="&") typeName = CGWrapper(typeName, post="&")
return typeName return typeName
if type.isString(): if type.isDOMString():
return CGGeneric("const nsAString&") return CGGeneric("const nsAString&")
if type.isByteString():
return CGGeneric("const nsCString&")
if type.isEnum(): if type.isEnum():
if type.nullable(): if type.nullable():
raise TypeError("We don't support nullable enumerated arguments or " raise TypeError("We don't support nullable enumerated arguments or "
@ -7510,10 +7563,20 @@ class CGDescriptor(CGThing):
not descriptor.interface.isExternal() and not descriptor.interface.isExternal() and
# Workers stuff is never pref-controlled # Workers stuff is never pref-controlled
not descriptor.workers): not descriptor.workers):
if descriptor.interface.getExtendedAttribute("PrefControlled") is not None: prefControlled = descriptor.interface.getExtendedAttribute("PrefControlled")
havePref = descriptor.interface.getExtendedAttribute("Pref")
haveChromeOnly = descriptor.interface.getExtendedAttribute("ChromeOnly")
# Make sure at most one of those is set
if bool(prefControlled) + bool(havePref) + bool(haveChromeOnly) > 1:
raise TypeError("Interface %s has more than one of "
"'PrefControlled', 'Pref', and 'ChomeOnly' "
"specified", descriptor.name)
if prefControlled is not None:
cgThings.append(CGPrefEnabledNative(descriptor)) cgThings.append(CGPrefEnabledNative(descriptor))
elif descriptor.interface.getExtendedAttribute("Pref") is not None: elif havePref is not None:
cgThings.append(CGPrefEnabled(descriptor)) cgThings.append(CGPrefEnabled(descriptor))
elif haveChromeOnly is not None:
cgThings.append(CGConstructorEnabledChromeOnly(descriptor))
if descriptor.concrete: if descriptor.concrete:
if descriptor.proxy: if descriptor.proxy:
@ -8027,12 +8090,12 @@ class CGRegisterProtos(CGAbstractMethod):
def _defineMacro(self): def _defineMacro(self):
return """ return """
#define REGISTER_PROTO(_dom_class, _pref_check) \\ #define REGISTER_PROTO(_dom_class, _ctor_check) \\
aNameSpaceManager->RegisterDefineDOMInterface(NS_LITERAL_STRING(#_dom_class), _dom_class##Binding::DefineDOMInterface, _pref_check); aNameSpaceManager->RegisterDefineDOMInterface(NS_LITERAL_STRING(#_dom_class), _dom_class##Binding::DefineDOMInterface, _ctor_check);
#define REGISTER_CONSTRUCTOR(_dom_constructor, _dom_class, _pref_check) \\ #define REGISTER_CONSTRUCTOR(_dom_constructor, _dom_class, _ctor_check) \\
aNameSpaceManager->RegisterDefineDOMInterface(NS_LITERAL_STRING(#_dom_constructor), _dom_class##Binding::DefineDOMInterface, _pref_check); aNameSpaceManager->RegisterDefineDOMInterface(NS_LITERAL_STRING(#_dom_constructor), _dom_class##Binding::DefineDOMInterface, _ctor_check);
#define REGISTER_NAVIGATOR_CONSTRUCTOR(_prop, _dom_class, _pref_check) \\ #define REGISTER_NAVIGATOR_CONSTRUCTOR(_prop, _dom_class, _ctor_check) \\
aNameSpaceManager->RegisterNavigatorDOMConstructor(NS_LITERAL_STRING(_prop), _dom_class##Binding::ConstructNavigatorObject, _pref_check); aNameSpaceManager->RegisterNavigatorDOMConstructor(NS_LITERAL_STRING(_prop), _dom_class##Binding::ConstructNavigatorObject, _ctor_check);
""" """
def _undefineMacro(self): def _undefineMacro(self):
@ -8041,23 +8104,24 @@ class CGRegisterProtos(CGAbstractMethod):
#undef REGISTER_PROTO #undef REGISTER_PROTO
#undef REGISTER_NAVIGATOR_CONSTRUCTOR""" #undef REGISTER_NAVIGATOR_CONSTRUCTOR"""
def _registerProtos(self): def _registerProtos(self):
def getPrefCheck(desc): def getCheck(desc):
if (desc.interface.getExtendedAttribute("PrefControlled") is None and if (desc.interface.getExtendedAttribute("PrefControlled") is None and
desc.interface.getExtendedAttribute("Pref") is None): desc.interface.getExtendedAttribute("Pref") is None and
desc.interface.getExtendedAttribute("ChromeOnly") is None):
return "nullptr" return "nullptr"
return "%sBinding::PrefEnabled" % desc.name return "%sBinding::ConstructorEnabled" % desc.name
lines = [] lines = []
for desc in self.config.getDescriptors(hasInterfaceObject=True, for desc in self.config.getDescriptors(hasInterfaceObject=True,
isExternal=False, isExternal=False,
workers=False, workers=False,
register=True): register=True):
lines.append("REGISTER_PROTO(%s, %s);" % (desc.name, getPrefCheck(desc))) lines.append("REGISTER_PROTO(%s, %s);" % (desc.name, getCheck(desc)))
lines.extend("REGISTER_CONSTRUCTOR(%s, %s, %s);" % (n.identifier.name, desc.name, getPrefCheck(desc)) lines.extend("REGISTER_CONSTRUCTOR(%s, %s, %s);" % (n.identifier.name, desc.name, getCheck(desc))
for n in desc.interface.namedConstructors) for n in desc.interface.namedConstructors)
for desc in self.config.getDescriptors(isNavigatorProperty=True, register=True): for desc in self.config.getDescriptors(isNavigatorProperty=True, register=True):
propName = desc.interface.getNavigatorProperty() propName = desc.interface.getNavigatorProperty()
assert propName assert propName
lines.append('REGISTER_NAVIGATOR_CONSTRUCTOR("%s", %s, %s);' % (propName, desc.name, getPrefCheck(desc))) lines.append('REGISTER_NAVIGATOR_CONSTRUCTOR("%s", %s, %s);' % (propName, desc.name, getCheck(desc)))
return '\n'.join(lines) + '\n' return '\n'.join(lines) + '\n'
def definition_body(self): def definition_body(self):
return self._defineMacro() + self._registerProtos() + self._undefineMacro() return self._defineMacro() + self._registerProtos() + self._undefineMacro()
@ -8448,12 +8512,18 @@ class CGNativeMember(ClassMethod):
return (result.define(), return (result.define(),
"%s(%s)" % (result.define(), defaultReturnArg), "%s(%s)" % (result.define(), defaultReturnArg),
"return ${declName};") "return ${declName};")
if type.isString(): if type.isDOMString():
if isMember: if isMember:
# No need for a third element in the isMember case # No need for a third element in the isMember case
return "nsString", None, None return "nsString", None, None
# Outparam # Outparam
return "void", "", "retval = ${declName};" return "void", "", "retval = ${declName};"
if type.isByteString():
if isMember:
# No need for a third element in the isMember case
return "nsCString", None, None
# Outparam
return "void", "", "retval = ${declName};"
if type.isEnum(): if type.isEnum():
enumName = type.unroll().inner.identifier.name enumName = type.unroll().inner.identifier.name
if type.nullable(): if type.nullable():
@ -8532,8 +8602,10 @@ class CGNativeMember(ClassMethod):
def getArgs(self, returnType, argList): def getArgs(self, returnType, argList):
args = [self.getArg(arg) for arg in argList] args = [self.getArg(arg) for arg in argList]
# Now the outparams # Now the outparams
if returnType.isString(): if returnType.isDOMString():
args.append(Argument("nsString&", "retval")) args.append(Argument("nsString&", "retval"))
if returnType.isByteString():
args.append(Argument("nsCString&", "retval"))
elif returnType.isSequence(): elif returnType.isSequence():
nullable = returnType.nullable() nullable = returnType.nullable()
if nullable: if nullable:
@ -8627,13 +8699,17 @@ class CGNativeMember(ClassMethod):
typeDecl = typeDecl % type.name typeDecl = typeDecl % type.name
return typeDecl, False, False return typeDecl, False, False
if type.isString(): if type.isDOMString():
if isMember: if isMember:
declType = "nsString" declType = "nsString"
else: else:
declType = "nsAString" declType = "nsAString"
return declType, True, False return declType, True, False
if type.isByteString():
declType = "nsCString"
return declType, True, False
if type.isEnum(): if type.isEnum():
return type.unroll().inner.identifier.name, False, True return type.unroll().inner.identifier.name, False, True
@ -9500,7 +9576,7 @@ class CallbackMember(CGNativeMember):
jsvalIndex = "%d" % i jsvalIndex = "%d" % i
if arg.optional and not arg.defaultValue: if arg.optional and not arg.defaultValue:
argval += ".Value()" argval += ".Value()"
if arg.type.isString(): if arg.type.isDOMString():
# XPConnect string-to-JS conversion wants to mutate the string. So # XPConnect string-to-JS conversion wants to mutate the string. So
# let's give it a string it can mutate # let's give it a string it can mutate
# XXXbz if we try to do a sequence of strings, this will kinda fail. # XXXbz if we try to do a sequence of strings, this will kinda fail.

View File

@ -37,4 +37,6 @@ MSG_DEF(MSG_ENCODING_NOT_SUPPORTED, 1, "The given encoding '{0}' is not supporte
MSG_DEF(MSG_DOM_ENCODING_NOT_UTF, 0, "The encoding must be utf-8, utf-16, or utf-16be.") MSG_DEF(MSG_DOM_ENCODING_NOT_UTF, 0, "The encoding must be utf-8, utf-16, or utf-16be.")
MSG_DEF(MSG_NOT_FINITE, 0, "Floating-point value is not finite.") MSG_DEF(MSG_NOT_FINITE, 0, "Floating-point value is not finite.")
MSG_DEF(MSG_INVALID_VERSION, 0, "0 (Zero) is not a valid database version.") MSG_DEF(MSG_INVALID_VERSION, 0, "0 (Zero) is not a valid database version.")
MSG_DEF(MSG_INVALID_BYTESTRING, 2, "Cannot convert string to ByteString because the character"
" at index {0} has value {1} which is greater than 255.")
MSG_DEF(MSG_NOT_DATE, 0, "Value is not a date.") MSG_DEF(MSG_NOT_DATE, 0, "Value is not a date.")

View File

@ -384,7 +384,7 @@ class IDLObjectWithIdentifier(IDLObject):
identifier = attr.identifier() identifier = attr.identifier()
value = attr.value() value = attr.value()
if identifier == "TreatNullAs": if identifier == "TreatNullAs":
if not self.type.isString() or self.type.nullable(): if not self.type.isDOMString() or self.type.nullable():
raise WebIDLError("[TreatNullAs] is only allowed on " raise WebIDLError("[TreatNullAs] is only allowed on "
"arguments or attributes whose type is " "arguments or attributes whose type is "
"DOMString", "DOMString",
@ -407,7 +407,7 @@ class IDLObjectWithIdentifier(IDLObject):
"allowed on optional arguments", "allowed on optional arguments",
[self.location]) [self.location])
elif value == 'Null': elif value == 'Null':
if not self.type.isString(): if not self.type.isDOMString():
raise WebIDLError("[TreatUndefinedAs=Null] is only " raise WebIDLError("[TreatUndefinedAs=Null] is only "
"allowed on arguments or " "allowed on arguments or "
"attributes whose type is " "attributes whose type is "
@ -418,7 +418,7 @@ class IDLObjectWithIdentifier(IDLObject):
"allowed on arguments whose type " "allowed on arguments whose type "
"is DOMString?", [self.location]) "is DOMString?", [self.location])
elif value == 'EmptyString': elif value == 'EmptyString':
if not self.type.isString(): if not self.type.isDOMString():
raise WebIDLError("[TreatUndefinedAs=EmptyString] " raise WebIDLError("[TreatUndefinedAs=EmptyString] "
"is only allowed on arguments or " "is only allowed on arguments or "
"attributes whose type is " "attributes whose type is "
@ -508,7 +508,10 @@ class IDLInterface(IDLObjectWithScope):
self._callback = False self._callback = False
self._finished = False self._finished = False
self.members = [] self.members = []
self.namedConstructors = set() # namedConstructors needs deterministic ordering because bindings code
# outputs the constructs in the order that namedConstructors enumerates
# them.
self.namedConstructors = list()
self.implementedInterfaces = set() self.implementedInterfaces = set()
self._consequential = False self._consequential = False
self._isPartial = True self._isPartial = True
@ -903,7 +906,7 @@ class IDLInterface(IDLObjectWithScope):
# NamedConstructors. # NamedConstructors.
newMethod = self.parentScope.lookupIdentifier(method.identifier) newMethod = self.parentScope.lookupIdentifier(method.identifier)
if newMethod == method: if newMethod == method:
self.namedConstructors.add(method) self.namedConstructors.append(method)
elif not newMethod in self.namedConstructors: elif not newMethod in self.namedConstructors:
raise WebIDLError("NamedConstructor conflicts with a NamedConstructor of a different interface", raise WebIDLError("NamedConstructor conflicts with a NamedConstructor of a different interface",
[method.location, newMethod.location]) [method.location, newMethod.location])
@ -913,7 +916,8 @@ class IDLInterface(IDLObjectWithScope):
identifier == "JSImplementation" or identifier == "JSImplementation" or
identifier == "HeaderFile" or identifier == "HeaderFile" or
identifier == "NavigatorProperty" or identifier == "NavigatorProperty" or
identifier == "OverrideBuiltins"): identifier == "OverrideBuiltins" or
identifier == "ChromeOnly"):
# Known attributes that we don't need to do anything with here # Known attributes that we don't need to do anything with here
pass pass
else: else:
@ -1213,6 +1217,7 @@ class IDLType(IDLObject):
# Other types # Other types
'any', 'any',
'domstring', 'domstring',
'bytestring',
'object', 'object',
'date', 'date',
'void', 'void',
@ -1252,6 +1257,12 @@ class IDLType(IDLObject):
def isString(self): def isString(self):
return False return False
def isByteString(self):
return False
def isDOMString(self):
return False
def isVoid(self): def isVoid(self):
return self.name == "Void" return self.name == "Void"
@ -1400,6 +1411,12 @@ class IDLNullableType(IDLType):
def isString(self): def isString(self):
return self.inner.isString() return self.inner.isString()
def isByteString(self):
return self.inner.isByteString()
def isDOMString(self):
return self.inner.isDOMString()
def isFloat(self): def isFloat(self):
return self.inner.isFloat() return self.inner.isFloat()
@ -1509,6 +1526,12 @@ class IDLSequenceType(IDLType):
def isString(self): def isString(self):
return False; return False;
def isByteString(self):
return False
def isDOMString(self):
return False
def isVoid(self): def isVoid(self):
return False return False
@ -1693,6 +1716,12 @@ class IDLArrayType(IDLType):
def isString(self): def isString(self):
return False return False
def isByteString(self):
return False
def isDOMString(self):
return False
def isVoid(self): def isVoid(self):
return False return False
@ -1776,6 +1805,12 @@ class IDLTypedefType(IDLType, IDLObjectWithIdentifier):
def isString(self): def isString(self):
return self.inner.isString() return self.inner.isString()
def isByteString(self):
return self.inner.isByteString()
def isDOMString(self):
return self.inner.isDOMString()
def isVoid(self): def isVoid(self):
return self.inner.isVoid() return self.inner.isVoid()
@ -1863,6 +1898,12 @@ class IDLWrapperType(IDLType):
def isString(self): def isString(self):
return False return False
def isByteString(self):
return False
def isDOMString(self):
return False
def isVoid(self): def isVoid(self):
return False return False
@ -1981,6 +2022,7 @@ class IDLBuiltinType(IDLType):
# Other types # Other types
'any', 'any',
'domstring', 'domstring',
'bytestring',
'object', 'object',
'date', 'date',
'void', 'void',
@ -2014,6 +2056,7 @@ class IDLBuiltinType(IDLType):
Types.double: IDLType.Tags.double, Types.double: IDLType.Tags.double,
Types.any: IDLType.Tags.any, Types.any: IDLType.Tags.any,
Types.domstring: IDLType.Tags.domstring, Types.domstring: IDLType.Tags.domstring,
Types.bytestring: IDLType.Tags.bytestring,
Types.object: IDLType.Tags.object, Types.object: IDLType.Tags.object,
Types.date: IDLType.Tags.date, Types.date: IDLType.Tags.date,
Types.void: IDLType.Tags.void, Types.void: IDLType.Tags.void,
@ -2039,6 +2082,13 @@ class IDLBuiltinType(IDLType):
return self._typeTag <= IDLBuiltinType.Types.double return self._typeTag <= IDLBuiltinType.Types.double
def isString(self): def isString(self):
return self._typeTag == IDLBuiltinType.Types.domstring or \
self._typeTag == IDLBuiltinType.Types.bytestring
def isByteString(self):
return self._typeTag == IDLBuiltinType.Types.bytestring
def isDOMString(self):
return self._typeTag == IDLBuiltinType.Types.domstring return self._typeTag == IDLBuiltinType.Types.domstring
def isInteger(self): def isInteger(self):
@ -2173,6 +2223,9 @@ BuiltinTypes = {
IDLBuiltinType.Types.domstring: IDLBuiltinType.Types.domstring:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "String", IDLBuiltinType(BuiltinLocation("<builtin type>"), "String",
IDLBuiltinType.Types.domstring), IDLBuiltinType.Types.domstring),
IDLBuiltinType.Types.bytestring:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "ByteString",
IDLBuiltinType.Types.bytestring),
IDLBuiltinType.Types.object: IDLBuiltinType.Types.object:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Object", IDLBuiltinType(BuiltinLocation("<builtin type>"), "Object",
IDLBuiltinType.Types.object), IDLBuiltinType.Types.object),
@ -3256,6 +3309,7 @@ class Tokenizer(object):
"::": "SCOPE", "::": "SCOPE",
"Date": "DATE", "Date": "DATE",
"DOMString": "DOMSTRING", "DOMString": "DOMSTRING",
"ByteString": "BYTESTRING",
"any": "ANY", "any": "ANY",
"boolean": "BOOLEAN", "boolean": "BOOLEAN",
"byte": "BYTE", "byte": "BYTE",
@ -3813,8 +3867,8 @@ class Parser(Tokenizer):
if len(arguments) != 0: if len(arguments) != 0:
raise WebIDLError("stringifier has wrong number of arguments", raise WebIDLError("stringifier has wrong number of arguments",
[self.getLocation(p, 2)]) [self.getLocation(p, 2)])
if not returnType.isString(): if not returnType.isDOMString():
raise WebIDLError("stringifier must have string return type", raise WebIDLError("stringifier must have DOMString return type",
[self.getLocation(p, 2)]) [self.getLocation(p, 2)])
inOptionalArguments = False inOptionalArguments = False
@ -4123,6 +4177,7 @@ class Parser(Tokenizer):
| QUESTIONMARK | QUESTIONMARK
| DATE | DATE
| DOMSTRING | DOMSTRING
| BYTESTRING
| ANY | ANY
| ATTRIBUTE | ATTRIBUTE
| BOOLEAN | BOOLEAN
@ -4358,6 +4413,12 @@ class Parser(Tokenizer):
""" """
p[0] = IDLBuiltinType.Types.domstring p[0] = IDLBuiltinType.Types.domstring
def p_PrimitiveOrStringTypeBytestring(self, p):
"""
PrimitiveOrStringType : BYTESTRING
"""
p[0] = IDLBuiltinType.Types.bytestring
def p_UnsignedIntegerTypeUnsigned(self, p): def p_UnsignedIntegerTypeUnsigned(self, p):
""" """
UnsignedIntegerType : UNSIGNED IntegerType UnsignedIntegerType : UNSIGNED IntegerType

View File

@ -0,0 +1,72 @@
# -*- coding: UTF-8 -*-
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface TestByteString {
attribute ByteString bs;
attribute DOMString ds;
};
""")
results = parser.finish();
harness.ok(True, "TestByteString interface parsed without error.")
harness.check(len(results), 1, "Should be one production")
harness.ok(isinstance(results[0], WebIDL.IDLInterface),
"Should be an IDLInterface")
iface = results[0]
harness.check(iface.identifier.QName(), "::TestByteString", "Interface has the right QName")
harness.check(iface.identifier.name, "TestByteString", "Interface has the right name")
harness.check(iface.parent, None, "Interface has no parent")
members = iface.members
harness.check(len(members), 2, "Should be two productions")
attr = members[0]
harness.ok(isinstance(attr, WebIDL.IDLAttribute), "Should be an IDLAttribute")
harness.check(attr.identifier.QName(), "::TestByteString::bs", "Attr has correct QName")
harness.check(attr.identifier.name, "bs", "Attr has correct name")
harness.check(str(attr.type), "ByteString", "Attr type is the correct name")
harness.ok(attr.type.isByteString(), "Should be ByteString type")
harness.ok(attr.type.isString(), "Should be String collective type")
harness.ok(not attr.type.isDOMString(), "Should be not be DOMString type")
# now check we haven't broken DOMStrings in the process.
attr = members[1]
harness.ok(isinstance(attr, WebIDL.IDLAttribute), "Should be an IDLAttribute")
harness.check(attr.identifier.QName(), "::TestByteString::ds", "Attr has correct QName")
harness.check(attr.identifier.name, "ds", "Attr has correct name")
harness.check(str(attr.type), "String", "Attr type is the correct name")
harness.ok(attr.type.isDOMString(), "Should be DOMString type")
harness.ok(attr.type.isString(), "Should be String collective type")
harness.ok(not attr.type.isByteString(), "Should be not be ByteString type")
# Cannot represent constant ByteString in IDL.
threw = False
try:
parser.parse("""
interface ConstByteString {
const ByteString foo = "hello"
};
""")
except WebIDL.WebIDLError:
threw = True
harness.ok(threw, "Should have thrown a WebIDL error")
# Cannot have optional ByteStrings with default values
threw = False
try:
parser.parse("""
interface OptionalByteString {
void passByteString(optional ByteString arg = "hello");
};
""")
results2 = parser.finish();
except WebIDL.WebIDLError:
threw = True
harness.ok(threw, "Should have thrown a WebIDL error")

View File

@ -62,6 +62,7 @@ def WebIDLTest(parser, harness):
"byte", "byte",
"octet", "octet",
"DOMString", "DOMString",
"ByteString",
#"sequence<float>", #"sequence<float>",
"object", "object",
"ArrayBuffer", "ArrayBuffer",

View File

@ -74,6 +74,7 @@ MOCHITEST_FILES := \
test_bug862092.html \ test_bug862092.html \
test_bug560072.html \ test_bug560072.html \
test_lenientThis.html \ test_lenientThis.html \
test_ByteString.html \
$(NULL) $(NULL)
MOCHITEST_CHROME_FILES = \ MOCHITEST_CHROME_FILES = \

View File

@ -137,6 +137,10 @@ public:
already_AddRefed<TestInterface> Test(const GlobalObject&, const nsAString&, already_AddRefed<TestInterface> Test(const GlobalObject&, const nsAString&,
ErrorResult&); ErrorResult&);
static static
already_AddRefed<TestInterface> Test(const GlobalObject&, const nsACString&,
ErrorResult&);
static
already_AddRefed<TestInterface> Test2(const GlobalObject&, already_AddRefed<TestInterface> Test2(const GlobalObject&,
JSContext*, JSContext*,
const DictForConstructor&, const DictForConstructor&,
@ -370,6 +374,9 @@ public:
void ReceiveStringSequence(nsTArray<nsString>&); void ReceiveStringSequence(nsTArray<nsString>&);
void PassStringSequence(const Sequence<nsString>&); void PassStringSequence(const Sequence<nsString>&);
void ReceiveByteStringSequence(nsTArray<nsCString>&);
void PassByteStringSequence(const Sequence<nsCString>&);
void ReceiveAnySequence(JSContext*, nsTArray<JS::Value>&); void ReceiveAnySequence(JSContext*, nsTArray<JS::Value>&);
void ReceiveNullableAnySequence(JSContext*, Nullable<nsTArray<JS::Value> >&); void ReceiveNullableAnySequence(JSContext*, Nullable<nsTArray<JS::Value> >&);
void ReceiveAnySequenceSequence(JSContext*, nsTArray<nsTArray<JS::Value> >&); void ReceiveAnySequenceSequence(JSContext*, nsTArray<nsTArray<JS::Value> >&);
@ -398,7 +405,7 @@ public:
void PassFloat64Array(Float64Array&); void PassFloat64Array(Float64Array&);
JSObject* ReceiveUint8Array(JSContext*); JSObject* ReceiveUint8Array(JSContext*);
// String types // DOMString types
void PassString(const nsAString&); void PassString(const nsAString&);
void PassNullableString(const nsAString&); void PassNullableString(const nsAString&);
void PassOptionalString(const Optional<nsAString>&); void PassOptionalString(const Optional<nsAString>&);
@ -409,6 +416,13 @@ public:
void PassOptionalNullableStringWithDefaultValue(const nsAString&); void PassOptionalNullableStringWithDefaultValue(const nsAString&);
void PassVariadicString(const Sequence<nsString>&); void PassVariadicString(const Sequence<nsString>&);
// ByteString types
void PassByteString(const nsCString&);
void PassNullableByteString(const nsCString&);
void PassOptionalByteString(const Optional<nsCString>&);
void PassOptionalNullableByteString(const Optional<nsCString>&);
void PassVariadicByteString(const Sequence<nsCString>&);
// Enumerated types // Enumerated types
void PassEnum(TestEnum); void PassEnum(TestEnum);
void PassNullableEnum(const Nullable<TestEnum>&); void PassNullableEnum(const Nullable<TestEnum>&);
@ -753,6 +767,13 @@ private:
void PassOptionalNullableStringWithDefaultValue(nsAString&) MOZ_DELETE; void PassOptionalNullableStringWithDefaultValue(nsAString&) MOZ_DELETE;
void PassVariadicString(Sequence<nsString>&) MOZ_DELETE; void PassVariadicString(Sequence<nsString>&) MOZ_DELETE;
// cstrings should be const as well
void PassByteString(nsCString&) MOZ_DELETE;
void PassNullableByteString(nsCString&) MOZ_DELETE;
void PassOptionalByteString(Optional<nsCString>&) MOZ_DELETE;
void PassOptionalNullableByteString(Optional<nsCString>&) MOZ_DELETE;
void PassVariadicByteString(Sequence<nsCString>&) MOZ_DELETE;
// Make sure dictionary arguments are always const // Make sure dictionary arguments are always const
void PassDictionary(JSContext*, Dict&) MOZ_DELETE; void PassDictionary(JSContext*, Dict&) MOZ_DELETE;
void PassOtherDictionary(GrandparentDict&) MOZ_DELETE; void PassOtherDictionary(GrandparentDict&) MOZ_DELETE;

View File

@ -338,6 +338,9 @@ interface TestInterface {
sequence<DOMString> receiveStringSequence(); sequence<DOMString> receiveStringSequence();
void passStringSequence(sequence<DOMString> arg); void passStringSequence(sequence<DOMString> arg);
sequence<ByteString> receiveByteStringSequence();
void passByteStringSequence(sequence<ByteString> arg);
sequence<any> receiveAnySequence(); sequence<any> receiveAnySequence();
sequence<any>? receiveNullableAnySequence(); sequence<any>? receiveNullableAnySequence();
sequence<sequence<any>> receiveAnySequenceSequence(); sequence<sequence<any>> receiveAnySequenceSequence();
@ -366,7 +369,7 @@ interface TestInterface {
void passFloat64Array(Float64Array arg); void passFloat64Array(Float64Array arg);
Uint8Array receiveUint8Array(); Uint8Array receiveUint8Array();
// String types // DOMString types
void passString(DOMString arg); void passString(DOMString arg);
void passNullableString(DOMString? arg); void passNullableString(DOMString? arg);
void passOptionalString(optional DOMString arg); void passOptionalString(optional DOMString arg);
@ -377,6 +380,13 @@ interface TestInterface {
void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null); void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null);
void passVariadicString(DOMString... arg); void passVariadicString(DOMString... arg);
// ByteString types
void passByteString(ByteString arg);
void passNullableByteString(ByteString? arg);
void passOptionalByteString(optional ByteString arg);
void passOptionalNullableByteString(optional ByteString? arg);
void passVariadicByteString(ByteString... arg);
// Enumerated types // Enumerated types
void passEnum(TestEnum arg); void passEnum(TestEnum arg);
void passNullableEnum(TestEnum? arg); void passNullableEnum(TestEnum? arg);

View File

@ -234,6 +234,9 @@ interface TestExampleInterface {
sequence<DOMString> receiveStringSequence(); sequence<DOMString> receiveStringSequence();
void passStringSequence(sequence<DOMString> arg); void passStringSequence(sequence<DOMString> arg);
sequence<ByteString> receiveByteStringSequence();
void passByteStringSequence(sequence<ByteString> arg);
sequence<any> receiveAnySequence(); sequence<any> receiveAnySequence();
sequence<any>? receiveNullableAnySequence(); sequence<any>? receiveNullableAnySequence();
//XXXbz No support for sequence of sequence return values yet. //XXXbz No support for sequence of sequence return values yet.
@ -264,7 +267,7 @@ interface TestExampleInterface {
void passFloat64Array(Float64Array arg); void passFloat64Array(Float64Array arg);
Uint8Array receiveUint8Array(); Uint8Array receiveUint8Array();
// String types // DOMString types
void passString(DOMString arg); void passString(DOMString arg);
void passNullableString(DOMString? arg); void passNullableString(DOMString? arg);
void passOptionalString(optional DOMString arg); void passOptionalString(optional DOMString arg);
@ -275,6 +278,13 @@ interface TestExampleInterface {
void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null); void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null);
void passVariadicString(DOMString... arg); void passVariadicString(DOMString... arg);
// ByteString types
void passByteString(ByteString arg);
void passNullableByteString(ByteString? arg);
void passOptionalByteString(optional ByteString arg);
void passOptionalNullableByteString(optional ByteString? arg);
void passVariadicByteString(ByteString... arg);
// Enumerated types // Enumerated types
void passEnum(TestEnum arg); void passEnum(TestEnum arg);
void passNullableEnum(TestEnum? arg); void passNullableEnum(TestEnum? arg);

View File

@ -252,6 +252,7 @@ interface TestJSImplInterface {
void passNullableExternalInterfaceSequence(sequence<TestExternalInterface?> arg); void passNullableExternalInterfaceSequence(sequence<TestExternalInterface?> arg);
sequence<DOMString> receiveStringSequence(); sequence<DOMString> receiveStringSequence();
sequence<ByteString> receiveByteStringSequence();
// Callback interface problem. See bug 843261. // Callback interface problem. See bug 843261.
//void passStringSequence(sequence<DOMString> arg); //void passStringSequence(sequence<DOMString> arg);
sequence<any> receiveAnySequence(); sequence<any> receiveAnySequence();
@ -287,7 +288,7 @@ interface TestJSImplInterface {
//void passFloat64Array(Float64Array arg); //void passFloat64Array(Float64Array arg);
//Uint8Array receiveUint8Array(); //Uint8Array receiveUint8Array();
// String types // DOMString types
void passString(DOMString arg); void passString(DOMString arg);
void passNullableString(DOMString? arg); void passNullableString(DOMString? arg);
void passOptionalString(optional DOMString arg); void passOptionalString(optional DOMString arg);
@ -298,6 +299,13 @@ interface TestJSImplInterface {
void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null); void passOptionalNullableStringWithDefaultValue(optional DOMString? arg = null);
void passVariadicString(DOMString... arg); void passVariadicString(DOMString... arg);
// ByteString types
void passByteString(ByteString arg);
void passNullableByteString(ByteString? arg);
void passOptionalByteString(optional ByteString arg);
void passOptionalNullableByteString(optional ByteString? arg);
void passVariadicByteString(ByteString... arg);
// Enumerated types // Enumerated types
void passEnum(MyTestEnum arg); void passEnum(MyTestEnum arg);
void passNullableEnum(MyTestEnum? arg); void passNullableEnum(MyTestEnum? arg);

View File

@ -0,0 +1,32 @@
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=796850
-->
<head>
<meta charset="utf-8">
<title>Test for ByteString support</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=796850">Mozilla Bug 796850</a>
<p id="display"></p>
<pre id="test">
<script type="application/javascript">
/** Test for Bug 796850 **/
var xhr = new XMLHttpRequest();
caught = false;
try {
xhr.open("\u5427", "about:mozilla", true);
}
catch (TypeError) {
caught = true;
}
ok(caught, "Character values > 255 not rejected for ByteString");
</script>
</pre>
</body>
</html>

View File

@ -71,10 +71,10 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget {
// request // request
[Throws] [Throws]
void open(DOMString method, DOMString url, optional boolean async = true, void open(ByteString method, DOMString url, optional boolean async = true,
optional DOMString? user, optional DOMString? password); optional DOMString? user, optional DOMString? password);
[Throws] [Throws]
void setRequestHeader(DOMString header, DOMString value); void setRequestHeader(ByteString header, ByteString value);
[SetterThrows] [SetterThrows]
attribute unsigned long timeout; attribute unsigned long timeout;
@ -109,12 +109,12 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget {
[Throws=Workers] [Throws=Workers]
readonly attribute unsigned short status; readonly attribute unsigned short status;
readonly attribute DOMString statusText; readonly attribute ByteString statusText;
[Throws] [Throws]
DOMString? getResponseHeader(DOMString header); ByteString? getResponseHeader(ByteString header);
[Throws=Workers] [Throws=Workers]
DOMString getAllResponseHeaders(); ByteString getAllResponseHeaders();
[Throws=Workers] [Throws=Workers]
void overrideMimeType(DOMString mime); void overrideMimeType(DOMString mime);

View File

@ -523,7 +523,7 @@ class EventRunnable : public MainThreadProxyRunnable
nsTArray<nsCOMPtr<nsISupports> > mClonedObjects; nsTArray<nsCOMPtr<nsISupports> > mClonedObjects;
jsval mResponse; jsval mResponse;
nsString mResponseText; nsString mResponseText;
nsString mStatusText; nsCString mStatusText;
uint64_t mLoaded; uint64_t mLoaded;
uint64_t mTotal; uint64_t mTotal;
uint32_t mEventStreamId; uint32_t mEventStreamId;
@ -970,11 +970,11 @@ public:
class GetAllResponseHeadersRunnable : public WorkerThreadProxySyncRunnable class GetAllResponseHeadersRunnable : public WorkerThreadProxySyncRunnable
{ {
nsString& mResponseHeaders; nsCString& mResponseHeaders;
public: public:
GetAllResponseHeadersRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy, GetAllResponseHeadersRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
nsString& aResponseHeaders) nsCString& aResponseHeaders)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), : WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy),
mResponseHeaders(aResponseHeaders) mResponseHeaders(aResponseHeaders)
{ } { }
@ -994,7 +994,7 @@ class GetResponseHeaderRunnable : public WorkerThreadProxySyncRunnable
public: public:
GetResponseHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy, GetResponseHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsCString& aHeader, nsCString& aValue) const nsACString& aHeader, nsCString& aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mHeader(aHeader), : WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mHeader(aHeader),
mValue(aValue) mValue(aValue)
{ } { }
@ -1008,7 +1008,7 @@ public:
class OpenRunnable : public WorkerThreadProxySyncRunnable class OpenRunnable : public WorkerThreadProxySyncRunnable
{ {
nsString mMethod; nsCString mMethod;
nsString mURL; nsString mURL;
Optional<nsAString> mUser; Optional<nsAString> mUser;
nsString mUserStr; nsString mUserStr;
@ -1020,7 +1020,7 @@ class OpenRunnable : public WorkerThreadProxySyncRunnable
public: public:
OpenRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy, OpenRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsAString& aMethod, const nsAString& aURL, const nsACString& aMethod, const nsAString& aURL,
const Optional<nsAString>& aUser, const Optional<nsAString>& aUser,
const Optional<nsAString>& aPassword, const Optional<nsAString>& aPassword,
bool aBackgroundRequest, bool aWithCredentials, bool aBackgroundRequest, bool aWithCredentials,
@ -1201,7 +1201,7 @@ class SetRequestHeaderRunnable : public WorkerThreadProxySyncRunnable
public: public:
SetRequestHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy, SetRequestHeaderRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy,
const nsCString& aHeader, const nsCString& aValue) const nsACString& aHeader, const nsACString& aValue)
: WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mHeader(aHeader), : WorkerThreadProxySyncRunnable(aWorkerPrivate, aProxy), mHeader(aHeader),
mValue(aValue) mValue(aValue)
{ } { }
@ -1716,7 +1716,7 @@ XMLHttpRequest::Notify(JSContext* aCx, Status aStatus)
} }
void void
XMLHttpRequest::Open(const nsAString& aMethod, const nsAString& aUrl, XMLHttpRequest::Open(const nsACString& aMethod, const nsAString& aUrl,
bool aAsync, const Optional<nsAString>& aUser, bool aAsync, const Optional<nsAString>& aUser,
const Optional<nsAString>& aPassword, ErrorResult& aRv) const Optional<nsAString>& aPassword, ErrorResult& aRv)
{ {
@ -1754,8 +1754,8 @@ XMLHttpRequest::Open(const nsAString& aMethod, const nsAString& aUrl,
} }
void void
XMLHttpRequest::SetRequestHeader(const nsAString& aHeader, XMLHttpRequest::SetRequestHeader(const nsACString& aHeader,
const nsAString& aValue, ErrorResult& aRv) const nsACString& aValue, ErrorResult& aRv)
{ {
mWorkerPrivate->AssertIsOnWorkerThread(); mWorkerPrivate->AssertIsOnWorkerThread();
@ -1770,9 +1770,7 @@ XMLHttpRequest::SetRequestHeader(const nsAString& aHeader,
} }
nsRefPtr<SetRequestHeaderRunnable> runnable = nsRefPtr<SetRequestHeaderRunnable> runnable =
new SetRequestHeaderRunnable(mWorkerPrivate, mProxy, new SetRequestHeaderRunnable(mWorkerPrivate, mProxy, aHeader, aValue);
NS_ConvertUTF16toUTF8(aHeader),
NS_ConvertUTF16toUTF8(aValue));
if (!runnable->Dispatch(GetJSContext())) { if (!runnable->Dispatch(GetJSContext())) {
aRv.Throw(NS_ERROR_FAILURE); aRv.Throw(NS_ERROR_FAILURE);
return; return;
@ -2012,8 +2010,8 @@ XMLHttpRequest::Abort(ErrorResult& aRv)
} }
void void
XMLHttpRequest::GetResponseHeader(const nsAString& aHeader, XMLHttpRequest::GetResponseHeader(const nsACString& aHeader,
nsAString& aResponseHeader, ErrorResult& aRv) nsACString& aResponseHeader, ErrorResult& aRv)
{ {
mWorkerPrivate->AssertIsOnWorkerThread(); mWorkerPrivate->AssertIsOnWorkerThread();
@ -2027,20 +2025,19 @@ XMLHttpRequest::GetResponseHeader(const nsAString& aHeader,
return; return;
} }
nsCString value; nsCString responseHeader;
nsRefPtr<GetResponseHeaderRunnable> runnable = nsRefPtr<GetResponseHeaderRunnable> runnable =
new GetResponseHeaderRunnable(mWorkerPrivate, mProxy, new GetResponseHeaderRunnable(mWorkerPrivate, mProxy, aHeader,
NS_ConvertUTF16toUTF8(aHeader), value); responseHeader);
if (!runnable->Dispatch(GetJSContext())) { if (!runnable->Dispatch(GetJSContext())) {
aRv.Throw(NS_ERROR_FAILURE); aRv.Throw(NS_ERROR_FAILURE);
return; return;
} }
aResponseHeader = responseHeader;
aResponseHeader = NS_ConvertUTF8toUTF16(value);
} }
void void
XMLHttpRequest::GetAllResponseHeaders(nsAString& aResponseHeaders, XMLHttpRequest::GetAllResponseHeaders(nsACString& aResponseHeaders,
ErrorResult& aRv) ErrorResult& aRv)
{ {
mWorkerPrivate->AssertIsOnWorkerThread(); mWorkerPrivate->AssertIsOnWorkerThread();
@ -2055,7 +2052,7 @@ XMLHttpRequest::GetAllResponseHeaders(nsAString& aResponseHeaders,
return; return;
} }
nsString responseHeaders; nsCString responseHeaders;
nsRefPtr<GetAllResponseHeadersRunnable> runnable = nsRefPtr<GetAllResponseHeadersRunnable> runnable =
new GetAllResponseHeadersRunnable(mWorkerPrivate, mProxy, responseHeaders); new GetAllResponseHeadersRunnable(mWorkerPrivate, mProxy, responseHeaders);
if (!runnable->Dispatch(GetJSContext())) { if (!runnable->Dispatch(GetJSContext())) {

View File

@ -29,7 +29,7 @@ public:
{ {
nsString mResponseText; nsString mResponseText;
uint32_t mStatus; uint32_t mStatus;
nsString mStatusText; nsCString mStatusText;
uint16_t mReadyState; uint16_t mReadyState;
jsval mResponse; jsval mResponse;
nsresult mResponseTextResult; nsresult mResponseTextResult;
@ -122,12 +122,12 @@ public:
} }
void void
Open(const nsAString& aMethod, const nsAString& aUrl, bool aAsync, Open(const nsACString& aMethod, const nsAString& aUrl, bool aAsync,
const Optional<nsAString>& aUser, const Optional<nsAString>& aPassword, const Optional<nsAString>& aUser, const Optional<nsAString>& aPassword,
ErrorResult& aRv); ErrorResult& aRv);
void void
SetRequestHeader(const nsAString& aHeader, const nsAString& aValue, SetRequestHeader(const nsACString& aHeader, const nsACString& aValue,
ErrorResult& aRv); ErrorResult& aRv);
uint32_t uint32_t
@ -199,17 +199,17 @@ public:
} }
void void
GetStatusText(nsAString& aStatusText) const GetStatusText(nsACString& aStatusText) const
{ {
aStatusText = mStateData.mStatusText; aStatusText = mStateData.mStatusText;
} }
void void
GetResponseHeader(const nsAString& aHeader, nsAString& aResponseHeader, GetResponseHeader(const nsACString& aHeader, nsACString& aResponseHeader,
ErrorResult& aRv); ErrorResult& aRv);
void void
GetAllResponseHeaders(nsAString& aResponseHeaders, ErrorResult& aRv); GetAllResponseHeaders(nsACString& aResponseHeaders, ErrorResult& aRv);
void void
OverrideMimeType(const nsAString& aMimeType, ErrorResult& aRv); OverrideMimeType(const nsAString& aMimeType, ErrorResult& aRv);

View File

@ -690,29 +690,50 @@ VectorImage::Draw(gfxContext* aContext,
AutoSVGRenderingState autoSVGState(aSVGContext, AutoSVGRenderingState autoSVGState(aSVGContext,
time, time,
mSVGDocumentWrapper->GetRootSVGElem()); mSVGDocumentWrapper->GetRootSVGElem());
mSVGDocumentWrapper->UpdateViewportBounds(aViewportSize);
// gfxUtils::DrawPixelSnapped may rasterize this image to a temporary surface
// if we hit the tiling path. Unfortunately, the temporary surface isn't
// created at the size at which we'll ultimately draw, causing fuzzy output.
// To fix this we pre-apply the transform's scaling to the drawing parameters
// and then remove the scaling from the transform, so the fact that temporary
// surfaces won't take the scaling into account doesn't matter. (Bug 600207.)
gfxSize scale(aUserSpaceToImageSpace.ScaleFactors(true));
gfxPoint translation(aUserSpaceToImageSpace.GetTranslation());
// Rescale everything.
nsIntSize scaledViewport(aViewportSize.width / scale.width,
aViewportSize.height / scale.height);
gfxIntSize scaledViewportGfx(scaledViewport.width, scaledViewport.height);
nsIntRect scaledSubimage(aSubimage);
scaledSubimage.ScaleRoundOut(1.0 / scale.width, 1.0 / scale.height);
// Remove the scaling from the transform.
gfxMatrix unscale;
unscale.Translate(gfxPoint(translation.x / scale.width,
translation.y / scale.height));
unscale.Scale(1.0 / scale.width, 1.0 / scale.height);
unscale.Translate(-translation);
gfxMatrix unscaledTransform(aUserSpaceToImageSpace * unscale);
mSVGDocumentWrapper->UpdateViewportBounds(scaledViewport);
mSVGDocumentWrapper->FlushImageTransformInvalidation(); mSVGDocumentWrapper->FlushImageTransformInvalidation();
// XXXdholbert Do we need to convert image size from
// CSS pixels to dev pixels here? (is gfxCallbackDrawable's 2nd arg in dev
// pixels?)
gfxIntSize imageSizeGfx(aViewportSize.width, aViewportSize.height);
// Based on imgFrame::Draw // Based on imgFrame::Draw
gfxRect sourceRect = aUserSpaceToImageSpace.Transform(aFill); gfxRect sourceRect = unscaledTransform.Transform(aFill);
gfxRect imageRect(0, 0, aViewportSize.width, aViewportSize.height); gfxRect imageRect(0, 0, scaledViewport.width, scaledViewport.height);
gfxRect subimage(aSubimage.x, aSubimage.y, aSubimage.width, aSubimage.height); gfxRect subimage(scaledSubimage.x, scaledSubimage.y,
scaledSubimage.width, scaledSubimage.height);
nsRefPtr<gfxDrawingCallback> cb = nsRefPtr<gfxDrawingCallback> cb =
new SVGDrawingCallback(mSVGDocumentWrapper, new SVGDrawingCallback(mSVGDocumentWrapper,
nsIntRect(nsIntPoint(0, 0), aViewportSize), nsIntRect(nsIntPoint(0, 0), scaledViewport),
aFlags); aFlags);
nsRefPtr<gfxDrawable> drawable = new gfxCallbackDrawable(cb, imageSizeGfx); nsRefPtr<gfxDrawable> drawable = new gfxCallbackDrawable(cb, scaledViewportGfx);
gfxUtils::DrawPixelSnapped(aContext, drawable, gfxUtils::DrawPixelSnapped(aContext, drawable,
aUserSpaceToImageSpace, unscaledTransform,
subimage, sourceRect, imageRect, aFill, subimage, sourceRect, imageRect, aFill,
gfxASurface::ImageFormatARGB32, aFilter, gfxASurface::ImageFormatARGB32, aFilter,
aFlags); aFlags);

View File

@ -1128,3 +1128,5 @@ sys/thr.h
sys/user.h sys/user.h
kvm.h kvm.h
spawn.h spawn.h
err.h
xlocale.h

View File

@ -3991,7 +3991,7 @@ CheckDivOrMod(FunctionCompiler &f, ParseNode *expr, MDefinition **def, Type *typ
return true; return true;
} }
return f.failf(expr, "arguments to / or &% must both be double, signed, or unsigned, " return f.failf(expr, "arguments to / or %% must both be double, signed, or unsigned; "
"%s and %s are given", lhsType.toChars(), rhsType.toChars()); "%s and %s are given", lhsType.toChars(), rhsType.toChars());
} }
@ -4025,7 +4025,7 @@ CheckComparison(FunctionCompiler &f, ParseNode *comp, MDefinition **def, Type *t
return true; return true;
} }
return f.failf(comp, "arguments to a comparison must both be signed, unsigned or doubles, " return f.failf(comp, "arguments to a comparison must both be signed, unsigned or doubles; "
"%s and %s are given", lhsType.toChars(), rhsType.toChars()); "%s and %s are given", lhsType.toChars(), rhsType.toChars());
} }

View File

@ -479,8 +479,14 @@ typedef JSObject*
typedef JSObject* typedef JSObject*
(*ConstructNavigatorProperty)(JSContext *cx, JS::Handle<JSObject*> naviObj); (*ConstructNavigatorProperty)(JSContext *cx, JS::Handle<JSObject*> naviObj);
// Check whether a constructor should be enabled for the given object.
// Note that the object should NOT be an Xray, since Xrays will end up
// defining constructors on the underlying object.
// This is a typedef for the function type itself, not the function
// pointer, so it's more obvious that pointers to a ConstructorEnabled
// can be null.
typedef bool typedef bool
(*PrefEnabled)(); (ConstructorEnabled)(JSContext* cx, JS::Handle<JSObject*> obj);
extern bool extern bool
DefineStaticJSVals(JSContext *cx); DefineStaticJSVals(JSContext *cx);

View File

@ -2,17 +2,10 @@
== tall--contain--width.html ref-tall-empty.html == tall--contain--width.html ref-tall-empty.html
== wide--contain--height.html ref-wide-empty.html == wide--contain--height.html ref-wide-empty.html
== wide--contain--width.html ref-wide-empty.html == wide--contain--width.html ref-wide-empty.html
== tall--cover--height.html ref-tall-lime.html
# We don't really care about the failures for this == tall--cover--width.html ref-tall-lime.html
# extreme edge case (the test exists more to test for safety against division by == wide--cover--height.html ref-wide-lime.html
# zero), so there is no bug has been filed to fix it, although a patch would == wide--cover--width.html ref-wide-lime.html
# probably be accepted.
# They're still marked as failing though, rather than 'load', since
# we want to know if they start working when we upgrade to Azure.
fails == tall--cover--height.html ref-tall-lime.html
fails == tall--cover--width.html ref-tall-lime.html
fails == wide--cover--height.html ref-wide-lime.html
fails == wide--cover--width.html ref-wide-lime.html
== zero-height-ratio-contain.html ref-tall-empty.html == zero-height-ratio-contain.html ref-tall-empty.html
== zero-height-ratio-cover.html ref-tall-empty.html == zero-height-ratio-cover.html ref-tall-empty.html

View File

@ -84,16 +84,10 @@ skip-if(B2G) == tall--contain--nonpercent-width-omitted-height-viewbox.html ref-
== tall--contain--percent-width-omitted-height-viewbox.html ref-tall-lime48x384-aqua48x384.html == tall--contain--percent-width-omitted-height-viewbox.html ref-tall-lime48x384-aqua48x384.html
== tall--contain--percent-width-percent-height.html ref-tall-lime256x384-aqua256x384.html == tall--contain--percent-width-percent-height.html ref-tall-lime256x384-aqua256x384.html
== tall--contain--percent-width-percent-height-viewbox.html ref-tall-lime48x384-aqua48x384.html == tall--contain--percent-width-percent-height-viewbox.html ref-tall-lime48x384-aqua48x384.html
== tall--cover--nonpercent-width-nonpercent-height.html ref-tall-lime256x512-aqua256x256.html
# We smear the background image when scaling it in these two tests... == tall--cover--nonpercent-width-nonpercent-height-viewbox.html ref-tall-lime256x512-aqua256x256.html
# Android uses FILTER_NEAREST for background images so the smear doesn't occur
fails-if(!(Android||B2G)) == tall--cover--nonpercent-width-nonpercent-height.html ref-tall-lime256x512-aqua256x256.html
fails-if(!(Android||B2G)) == tall--cover--nonpercent-width-nonpercent-height-viewbox.html ref-tall-lime256x512-aqua256x256.html
# ...but we don't in identical tests with image-rendering: -moz-crisp-edges.
== tall--cover--nonpercent-width-nonpercent-height--crisp.html ref-tall-lime256x512-aqua256x256.html == tall--cover--nonpercent-width-nonpercent-height--crisp.html ref-tall-lime256x512-aqua256x256.html
== tall--cover--nonpercent-width-nonpercent-height-viewbox--crisp.html ref-tall-lime256x512-aqua256x256.html == tall--cover--nonpercent-width-nonpercent-height-viewbox--crisp.html ref-tall-lime256x512-aqua256x256.html
== tall--cover--nonpercent-width-omitted-height.html ref-tall-lime256x384-aqua256x384.html == tall--cover--nonpercent-width-omitted-height.html ref-tall-lime256x384-aqua256x384.html
== tall--cover--nonpercent-width-omitted-height-viewbox.html ref-tall-lime256x768.html == tall--cover--nonpercent-width-omitted-height-viewbox.html ref-tall-lime256x768.html
== tall--cover--nonpercent-width-percent-height.html ref-tall-lime256x384-aqua256x384.html == tall--cover--nonpercent-width-percent-height.html ref-tall-lime256x384-aqua256x384.html

View File

@ -154,4 +154,4 @@ HTTP == svg-stylesheet-external-1.html blue100x100.svg
# XXXseth: The underlying problems also apply to media fragments, # XXXseth: The underlying problems also apply to media fragments,
# but the test case would be much simpler. This should be switched # but the test case would be much simpler. This should be switched
# over to use media fragments once bug 790640 lands. # over to use media fragments once bug 790640 lands.
skip-if(B2G) == svg-border-image-repaint-1.html svg-border-image-repaint-1-ref.html skip-if(B2G) fuzzy(2,1) == svg-border-image-repaint-1.html svg-border-image-repaint-1-ref.html

View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="80" height="80">
<circle cx="40" cy="40" r="40" style="fill: green"/>
</svg>

After

Width:  |  Height:  |  Size: 141 B

View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="20" height="20">
<circle cx="10" cy="10" r="10" style="fill: green"/>
</svg>

After

Width:  |  Height:  |  Size: 141 B

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-small.svg');
background-size: 40px 40px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 80px;
height: 80px;
transform: scale(2.0);
transform-origin: 0 0;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-large.svg');
background-size: 40px 40px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 80px;
height: 80px;
transform: scale(0.5);
transform-origin: 0 0;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-large.svg');
background-size: 80px 80px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 160px;
height: 160px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html reftest-zoom="2.0">
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-small.svg');
background-size: 40px 40px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 80px;
height: 80px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-small.svg');
background-size: 20px 20px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 40px;
height: 40px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<html reftest-zoom="0.5">
<head>
<style>
body {
margin: 0px;
padding: 0px;
border: 0px;
}
div {
background: url('circle-large.svg');
background-size: 40px 40px;
background-repeat: repeat;
margin: 0px;
padding: 0px;
border: 0px;
width: 80px;
height: 80px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

View File

@ -4,3 +4,9 @@
== img-zoomIn-1.html squaredCircle-150x150-ref.html == img-zoomIn-1.html squaredCircle-150x150-ref.html
== img-zoomOut-1.html squaredCircle-50x50-ref.html == img-zoomOut-1.html squaredCircle-50x50-ref.html
# Ensure that scaled SVG images aren't fuzzy when tiled.
== img-fuzzy-zoomOut-1.html img-fuzzy-zoomOut-1-ref.html
== img-fuzzy-zoomIn-1.html img-fuzzy-zoomIn-1-ref.html
== img-fuzzy-transform-zoomOut-1.html img-fuzzy-zoomOut-1-ref.html
== img-fuzzy-transform-zoomIn-1.html img-fuzzy-zoomIn-1-ref.html

View File

@ -248,19 +248,20 @@ nsSVGImageFrame::TransformContextForPainting(gfxContext* aGfxContext)
} }
imageTransform = imageTransform =
GetRasterImageTransform(nativeWidth, nativeHeight, FOR_PAINTING); GetRasterImageTransform(nativeWidth, nativeHeight, FOR_PAINTING);
// NOTE: We need to cancel out the effects of Full-Page-Zoom, or else
// it'll get applied an extra time by DrawSingleUnscaledImage.
nscoord appUnitsPerDevPx = PresContext()->AppUnitsPerDevPixel();
gfxFloat pageZoomFactor =
nsPresContext::AppUnitsToFloatCSSPixels(appUnitsPerDevPx);
imageTransform.Scale(pageZoomFactor, pageZoomFactor);
} }
if (imageTransform.IsSingular()) { if (imageTransform.IsSingular()) {
return false; return false;
} }
// NOTE: We need to cancel out the effects of Full-Page-Zoom, or else aGfxContext->Multiply(imageTransform);
// it'll get applied an extra time by DrawSingleUnscaledImage.
nscoord appUnitsPerDevPx = PresContext()->AppUnitsPerDevPixel();
gfxFloat pageZoomFactor =
nsPresContext::AppUnitsToFloatCSSPixels(appUnitsPerDevPx);
aGfxContext->Multiply(imageTransform.Scale(pageZoomFactor, pageZoomFactor));
return true; return true;
} }

View File

@ -490,10 +490,10 @@
# define GTEST_ENV_HAS_TR1_TUPLE_ 1 # define GTEST_ENV_HAS_TR1_TUPLE_ 1
# endif # endif
// C++11 specifies that <tuple> provides std::tuple. Users can't use // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
// gtest in C++11 mode until their standard library is at least that // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
// compliant. // can build with clang but need to use gcc4.2's libstdc++).
# if GTEST_LANG_CXX11 # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
# define GTEST_ENV_HAS_STD_TUPLE_ 1 # define GTEST_ENV_HAS_STD_TUPLE_ 1
# endif # endif

View File

@ -124,6 +124,21 @@
# and Java Implementation # and Java Implementation
'enable_android_opensl%': 0, 'enable_android_opensl%': 0,
}], }],
['OS=="linux"', {
'include_alsa_audio%': 1,
}, {
'include_alsa_audio%': 0,
}],
['OS=="solaris" or os_bsd==1', {
'include_pulse_audio%': 1,
}, {
'include_pulse_audio%': 0,
}],
['OS=="linux" or OS=="solaris" or os_bsd==1', {
'include_v4l2_video_capture%': 1,
}, {
'include_v4l2_video_capture%': 0,
}],
['OS=="ios"', { ['OS=="ios"', {
'enable_video%': 0, 'enable_video%': 0,
'enable_protobuf%': 0, 'enable_protobuf%': 0,
@ -215,6 +230,18 @@
}], }],
], ],
}], }],
['os_bsd==1', {
'defines': [
'WEBRTC_BSD',
'WEBRTC_THREAD_RR',
],
}],
['OS=="dragonfly" or OS=="netbsd"', {
'defines': [
# doesn't support pthread_condattr_setclock
'WEBRTC_CLOCK_TYPE_REALTIME',
],
}],
['OS=="ios"', { ['OS=="ios"', {
'defines': [ 'defines': [
'WEBRTC_MAC', 'WEBRTC_MAC',

View File

@ -46,7 +46,7 @@ bool AudioDeviceUtility::StringCompare(
} // namespace webrtc } // namespace webrtc
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
// ============================================================================ // ============================================================================
// Linux & Mac // Linux & Mac
@ -109,6 +109,6 @@ bool AudioDeviceUtility::StringCompare(
} // namespace webrtc } // namespace webrtc
#endif // defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #endif // defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)

View File

@ -27,7 +27,7 @@
#include "latebindingsymboltable_linux.h" #include "latebindingsymboltable_linux.h"
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
#include <dlfcn.h> #include <dlfcn.h>
#endif #endif
@ -37,7 +37,7 @@ using namespace webrtc;
namespace webrtc_adm_linux { namespace webrtc_adm_linux {
inline static const char *GetDllError() { inline static const char *GetDllError() {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
char *err = dlerror(); char *err = dlerror();
if (err) { if (err) {
return err; return err;
@ -50,7 +50,7 @@ inline static const char *GetDllError() {
} }
DllHandle InternalLoadDll(const char dll_name[]) { DllHandle InternalLoadDll(const char dll_name[]) {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
DllHandle handle = dlopen(dll_name, RTLD_NOW); DllHandle handle = dlopen(dll_name, RTLD_NOW);
#else #else
#error Not implemented #error Not implemented
@ -63,7 +63,7 @@ DllHandle InternalLoadDll(const char dll_name[]) {
} }
void InternalUnloadDll(DllHandle handle) { void InternalUnloadDll(DllHandle handle) {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
if (dlclose(handle) != 0) { if (dlclose(handle) != 0) {
WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1, WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
"%d", GetDllError()); "%d", GetDllError());
@ -76,7 +76,7 @@ void InternalUnloadDll(DllHandle handle) {
static bool LoadSymbol(DllHandle handle, static bool LoadSymbol(DllHandle handle,
const char *symbol_name, const char *symbol_name,
void **symbol) { void **symbol) {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
*symbol = dlsym(handle, symbol_name); *symbol = dlsym(handle, symbol_name);
char *err = dlerror(); char *err = dlerror();
if (err) { if (err) {
@ -101,7 +101,7 @@ bool InternalLoadSymbols(DllHandle handle,
int num_symbols, int num_symbols,
const char *const symbol_names[], const char *const symbol_names[],
void *symbols[]) { void *symbols[]) {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
// Clear any old errors. // Clear any old errors.
dlerror(); dlerror();
#endif #endif

View File

@ -42,7 +42,7 @@
namespace webrtc_adm_linux { namespace webrtc_adm_linux {
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
typedef void *DllHandle; typedef void *DllHandle;
const DllHandle kInvalidDllHandle = NULL; const DllHandle kInvalidDllHandle = NULL;

View File

@ -29,7 +29,11 @@
namespace webrtc_adm_linux_pulse { namespace webrtc_adm_linux_pulse {
#ifdef __OpenBSD__
LATE_BINDING_SYMBOL_TABLE_DEFINE_BEGIN(PulseAudioSymbolTable, "libpulse.so")
#else
LATE_BINDING_SYMBOL_TABLE_DEFINE_BEGIN(PulseAudioSymbolTable, "libpulse.so.0") LATE_BINDING_SYMBOL_TABLE_DEFINE_BEGIN(PulseAudioSymbolTable, "libpulse.so.0")
#endif
#define X(sym) \ #define X(sym) \
LATE_BINDING_SYMBOL_TABLE_DEFINE_ENTRY(PulseAudioSymbolTable, sym) LATE_BINDING_SYMBOL_TABLE_DEFINE_ENTRY(PulseAudioSymbolTable, sym)
PULSE_AUDIO_SYMBOLS_LIST PULSE_AUDIO_SYMBOLS_LIST

View File

@ -12,6 +12,7 @@
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cstdlib> // for abs()
#include <cstring> #include <cstring>
#include <iterator> #include <iterator>

View File

@ -18,7 +18,7 @@
#include <Windows.h> // FILETIME #include <Windows.h> // FILETIME
#include <WinSock.h> // timeval #include <WinSock.h> // timeval
#include <MMSystem.h> // timeGetTime #include <MMSystem.h> // timeGetTime
#elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_BSD) || (defined WEBRTC_MAC))
#include <sys/time.h> // gettimeofday #include <sys/time.h> // gettimeofday
#include <time.h> #include <time.h>
#endif #endif
@ -156,7 +156,7 @@ void get_time(WindowsHelpTimer* help_timer, FILETIME& current_time) {
WindowsHelpTimer* _helpTimer; WindowsHelpTimer* _helpTimer;
}; };
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
// A clock reading times from the POSIX API. // A clock reading times from the POSIX API.
class UnixSystemClock : public RtpRtcpClock { class UnixSystemClock : public RtpRtcpClock {
@ -214,7 +214,7 @@ void WindowsSystemClock::CurrentNTP(WebRtc_UWord32& secs,
frac = (WebRtc_UWord32)dtemp; frac = (WebRtc_UWord32)dtemp;
} }
#elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_BSD) || (defined WEBRTC_MAC))
WebRtc_Word64 UnixSystemClock::GetTimeInMS() { WebRtc_Word64 UnixSystemClock::GetTimeInMS() {
return TickTime::MillisecondTimestamp(); return TickTime::MillisecondTimestamp();
@ -253,7 +253,7 @@ static WindowsHelpTimer global_help_timer = {0, 0, {{ 0, 0}, 0}, 0};
RtpRtcpClock* GetSystemClock() { RtpRtcpClock* GetSystemClock() {
#if defined(_WIN32) #if defined(_WIN32)
return new WindowsSystemClock(&global_help_timer); return new WindowsSystemClock(&global_help_timer);
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return new UnixSystemClock(); return new UnixSystemClock();
#else #else
return NULL; return NULL;
@ -330,7 +330,7 @@ bool StringCompare(const char* str1, const char* str2,
const WebRtc_UWord32 length) { const WebRtc_UWord32 length) {
return (_strnicmp(str1, str2, length) == 0) ? true : false; return (_strnicmp(str1, str2, length) == 0) ? true : false;
} }
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
bool StringCompare(const char* str1, const char* str2, bool StringCompare(const char* str1, const char* str2,
const WebRtc_UWord32 length) { const WebRtc_UWord32 length) {
return (strncasecmp(str1, str2, length) == 0) ? true : false; return (strncasecmp(str1, str2, length) == 0) ? true : false;

View File

@ -18,16 +18,16 @@
#if defined(_WIN32) #if defined(_WIN32)
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#include <arpa/inet.h> #include <arpa/inet.h>
#include <ctype.h> #include <ctype.h>
#include <fcntl.h> #include <fcntl.h>
#include <netdb.h> #include <netdb.h>
#include <sys/socket.h>
#include <net/if.h> #include <net/if.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h> #include <sys/time.h>
#include <unistd.h> #include <unistd.h>
#ifndef WEBRTC_IOS #ifndef WEBRTC_IOS
@ -36,9 +36,11 @@
#endif // defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #endif // defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
#if defined(WEBRTC_MAC) #if defined(WEBRTC_MAC)
#include <ifaddrs.h>
#include <machine/types.h> #include <machine/types.h>
#endif #endif
#if defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#include <ifaddrs.h>
#endif
#if defined(WEBRTC_LINUX) #if defined(WEBRTC_LINUX)
#include <linux/netlink.h> #include <linux/netlink.h>
#include <linux/rtnetlink.h> #include <linux/rtnetlink.h>
@ -51,7 +53,7 @@
#include "typedefs.h" #include "typedefs.h"
#include "udp_socket_manager_wrapper.h" #include "udp_socket_manager_wrapper.h"
#if defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#define GetLastError() errno #define GetLastError() errno
#define IFRSIZE ((int)(size * sizeof (struct ifreq))) #define IFRSIZE ((int)(size * sizeof (struct ifreq)))
@ -61,7 +63,7 @@
(int)(nlh)->nlmsg_len >= (int)sizeof(struct nlmsghdr) && \ (int)(nlh)->nlmsg_len >= (int)sizeof(struct nlmsghdr) && \
(int)(nlh)->nlmsg_len <= (len)) (int)(nlh)->nlmsg_len <= (len))
#endif // defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #endif // defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
namespace webrtc { namespace webrtc {
@ -2371,7 +2373,7 @@ WebRtc_Word32 UdpTransport::InetPresentationToNumeric(WebRtc_Word32 af,
const char* src, const char* src,
void* dst) void* dst)
{ {
#if defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
const WebRtc_Word32 result = inet_pton(af, src, dst); const WebRtc_Word32 result = inet_pton(af, src, dst);
return result > 0 ? 0 : -1; return result > 0 ? 0 : -1;
@ -2493,7 +2495,7 @@ WebRtc_Word32 UdpTransport::LocalHostAddressIPV6(char n_localIP[16])
"getaddrinfo failed to find address"); "getaddrinfo failed to find address");
return -1; return -1;
#elif defined(WEBRTC_MAC) #elif defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
struct ifaddrs* ptrIfAddrs = NULL; struct ifaddrs* ptrIfAddrs = NULL;
struct ifaddrs* ptrIfAddrsStart = NULL; struct ifaddrs* ptrIfAddrsStart = NULL;
@ -2685,7 +2687,7 @@ WebRtc_Word32 UdpTransport::LocalHostAddress(WebRtc_UWord32& localIP)
"gethostbyname failed, error:%d", error); "gethostbyname failed, error:%d", error);
return -1; return -1;
} }
#elif (defined(WEBRTC_MAC)) #elif (defined(WEBRTC_BSD) || defined(WEBRTC_MAC))
char localname[255]; char localname[255];
if (gethostname(localname, 255) != -1) if (gethostname(localname, 255) != -1)
{ {
@ -2824,7 +2826,7 @@ WebRtc_Word32 UdpTransport::IPAddress(const SocketAddress& address,
sourcePort = htons(source_port); sourcePort = htons(source_port);
return 0; return 0;
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
WebRtc_Word32 ipFamily = address._sockaddr_storage.sin_family; WebRtc_Word32 ipFamily = address._sockaddr_storage.sin_family;
const void* ptrNumericIP = NULL; const void* ptrNumericIP = NULL;

View File

@ -19,7 +19,7 @@
#if defined(_WIN32) #if defined(_WIN32)
#include <Windows.h> #include <Windows.h>
#include <mmsystem.h> #include <mmsystem.h>
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#include <string.h> #include <string.h>
#include <sys/time.h> #include <sys/time.h>
#include <time.h> #include <time.h>
@ -238,7 +238,7 @@ inline WebRtc_UWord32 RtpDumpImpl::GetTimeInMS() const
{ {
#if defined(_WIN32) #if defined(_WIN32)
return timeGetTime(); return timeGetTime();
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
struct timeval tv; struct timeval tv;
struct timezone tz; struct timezone tz;
unsigned long val; unsigned long val;

View File

@ -54,7 +54,7 @@ WebRtc_Word32 DeviceInfoImpl::NumberOfCapabilities(
if (_lastUsedDeviceNameLength == strlen((char*) deviceUniqueIdUTF8)) if (_lastUsedDeviceNameLength == strlen((char*) deviceUniqueIdUTF8))
{ {
// Is it the same device that is asked for again. // Is it the same device that is asked for again.
#if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) #if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
if(strncasecmp((char*)_lastUsedDeviceName, if(strncasecmp((char*)_lastUsedDeviceName,
(char*) deviceUniqueIdUTF8, (char*) deviceUniqueIdUTF8,
_lastUsedDeviceNameLength)==0) _lastUsedDeviceNameLength)==0)
@ -91,7 +91,7 @@ WebRtc_Word32 DeviceInfoImpl::GetCapability(const char* deviceUniqueIdUTF8,
ReadLockScoped cs(_apiLock); ReadLockScoped cs(_apiLock);
if ((_lastUsedDeviceNameLength != strlen((char*) deviceUniqueIdUTF8)) if ((_lastUsedDeviceNameLength != strlen((char*) deviceUniqueIdUTF8))
#if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) #if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
|| (strncasecmp((char*)_lastUsedDeviceName, || (strncasecmp((char*)_lastUsedDeviceName,
(char*) deviceUniqueIdUTF8, (char*) deviceUniqueIdUTF8,
_lastUsedDeviceNameLength)!=0)) _lastUsedDeviceNameLength)!=0))
@ -155,7 +155,7 @@ WebRtc_Word32 DeviceInfoImpl::GetBestMatchedCapability(
ReadLockScoped cs(_apiLock); ReadLockScoped cs(_apiLock);
if ((_lastUsedDeviceNameLength != strlen((char*) deviceUniqueIdUTF8)) if ((_lastUsedDeviceNameLength != strlen((char*) deviceUniqueIdUTF8))
#if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) #if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
|| (strncasecmp((char*)_lastUsedDeviceName, || (strncasecmp((char*)_lastUsedDeviceName,
(char*) deviceUniqueIdUTF8, (char*) deviceUniqueIdUTF8,
_lastUsedDeviceNameLength)!=0)) _lastUsedDeviceNameLength)!=0))

View File

@ -19,7 +19,13 @@
#include <stdlib.h> #include <stdlib.h>
//v4l includes //v4l includes
#if defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__)
#include <sys/videoio.h>
#elif defined(__sun)
#include <sys/videodev2.h>
#else
#include <linux/videodev2.h> #include <linux/videodev2.h>
#endif
#include "ref_count.h" #include "ref_count.h"
#include "trace.h" #include "trace.h"

View File

@ -12,12 +12,20 @@
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <fcntl.h> #include <fcntl.h>
#include <linux/videodev2.h>
#include <errno.h> #include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <string.h> #include <string.h>
//v4l includes
#if defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__)
#include <sys/videoio.h>
#elif defined(__sun)
#include <sys/videodev2.h>
#else
#include <linux/videodev2.h>
#endif
#include <new> #include <new>
#include "ref_count.h" #include "ref_count.h"

View File

@ -48,7 +48,7 @@
], ],
}, { # include_internal_video_capture == 1 }, { # include_internal_video_capture == 1
'conditions': [ 'conditions': [
['OS=="linux"', { ['include_v4l2_video_capture==1', {
'include_dirs': [ 'include_dirs': [
'linux', 'linux',
], ],
@ -157,7 +157,7 @@
'test/video_capture_main_mac.mm', 'test/video_capture_main_mac.mm',
], ],
'conditions': [ 'conditions': [
['OS=="mac" or OS=="linux"', { ['OS!="win" and OS!="android"', {
'cflags': [ 'cflags': [
'-Wno-write-strings', '-Wno-write-strings',
], ],
@ -165,11 +165,15 @@
'-lpthread -lm', '-lpthread -lm',
], ],
}], }],
['include_v4l2_video_capture==1', {
'libraries': [
'-lXext',
'-lX11',
],
}],
['OS=="linux"', { ['OS=="linux"', {
'libraries': [ 'libraries': [
'-lrt', '-lrt',
'-lXext',
'-lX11',
], ],
}], }],
['OS=="mac"', { ['OS=="mac"', {

View File

@ -11,7 +11,7 @@
#ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ASM_DEFINES_H_ #ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ASM_DEFINES_H_
#define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ASM_DEFINES_H_ #define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ASM_DEFINES_H_
#if defined(__linux__) && defined(__ELF__) #if (defined(__linux__) || defined(__FreeBSD__)) && defined(__ELF__)
.section .note.GNU-stack,"",%progbits .section .note.GNU-stack,"",%progbits
#endif #endif

View File

@ -194,7 +194,7 @@ inline WebRtc_Word64 TickTime::QueryOsForTicks() {
} }
result.ticks_ = now + (num_wrap_time_get_time << 32); result.ticks_ = now + (num_wrap_time_get_time << 32);
#endif #endif
#elif defined(WEBRTC_LINUX) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
struct timespec ts; struct timespec ts;
// TODO(wu): Remove CLOCK_REALTIME implementation. // TODO(wu): Remove CLOCK_REALTIME implementation.
#ifdef WEBRTC_CLOCK_TYPE_REALTIME #ifdef WEBRTC_CLOCK_TYPE_REALTIME
@ -241,7 +241,7 @@ inline WebRtc_Word64 TickTime::MillisecondTimestamp() {
#else #else
return ticks; return ticks;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return ticks / 1000000LL; return ticks / 1000000LL;
#else #else
return ticks / 1000LL; return ticks / 1000LL;
@ -258,7 +258,7 @@ inline WebRtc_Word64 TickTime::MicrosecondTimestamp() {
#else #else
return ticks * 1000LL; return ticks * 1000LL;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return ticks / 1000LL; return ticks / 1000LL;
#else #else
return ticks; return ticks;
@ -278,7 +278,7 @@ inline WebRtc_Word64 TickTime::MillisecondsToTicks(const WebRtc_Word64 ms) {
#else #else
return ms; return ms;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return ms * 1000000LL; return ms * 1000000LL;
#else #else
return ms * 1000LL; return ms * 1000LL;
@ -294,7 +294,7 @@ inline WebRtc_Word64 TickTime::TicksToMilliseconds(const WebRtc_Word64 ticks) {
#else #else
return ticks; return ticks;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return ticks / 1000000LL; return ticks / 1000000LL;
#else #else
return ticks / 1000LL; return ticks / 1000LL;
@ -323,7 +323,7 @@ inline WebRtc_Word64 TickInterval::Milliseconds() const {
// interval_ is in ms // interval_ is in ms
return interval_; return interval_;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
// interval_ is in ns // interval_ is in ns
return interval_ / 1000000; return interval_ / 1000000;
#else #else
@ -342,7 +342,7 @@ inline WebRtc_Word64 TickInterval::Microseconds() const {
// interval_ is in ms // interval_ is in ms
return interval_ * 1000LL; return interval_ * 1000LL;
#endif #endif
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
// interval_ is in ns // interval_ is in ns
return interval_ / 1000; return interval_ / 1000;
#else #else

View File

@ -12,7 +12,6 @@
#include <assert.h> #include <assert.h>
#include <inttypes.h> #include <inttypes.h>
#include <malloc.h>
#include "common_types.h" #include "common_types.h"

View File

@ -8,14 +8,14 @@
* be found in the AUTHORS file in the root of the source tree. * be found in the AUTHORS file in the root of the source tree.
*/ */
#include "condition_variable_wrapper.h"
#if defined(_WIN32) #if defined(_WIN32)
#include <windows.h> #include <windows.h>
#include "condition_variable_win.h" #include "condition_variable_win.h"
#include "condition_variable_wrapper.h" #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
#include <pthread.h> #include <pthread.h>
#include "condition_variable_posix.h" #include "condition_variable_posix.h"
#include "condition_variable_wrapper.h"
#endif #endif
namespace webrtc { namespace webrtc {
@ -23,7 +23,7 @@ namespace webrtc {
ConditionVariableWrapper* ConditionVariableWrapper::CreateConditionVariable() { ConditionVariableWrapper* ConditionVariableWrapper::CreateConditionVariable() {
#if defined(_WIN32) #if defined(_WIN32)
return new ConditionVariableWindows; return new ConditionVariableWindows;
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
return ConditionVariablePosix::Create(); return ConditionVariablePosix::Create();
#else #else
return NULL; return NULL;

View File

@ -79,7 +79,7 @@ bool ConditionVariablePosix::SleepCS(CriticalSectionWrapper& crit_sect,
unsigned long max_time_inMS) { unsigned long max_time_inMS) {
const unsigned long INFINITE = 0xFFFFFFFF; const unsigned long INFINITE = 0xFFFFFFFF;
const int MILLISECONDS_PER_SECOND = 1000; const int MILLISECONDS_PER_SECOND = 1000;
#ifndef WEBRTC_LINUX #if !defined(WEBRTC_LINUX) && !defined(WEBRTC_BSD)
const int MICROSECONDS_PER_MILLISECOND = 1000; const int MICROSECONDS_PER_MILLISECOND = 1000;
#endif #endif
const int NANOSECONDS_PER_SECOND = 1000000000; const int NANOSECONDS_PER_SECOND = 1000000000;

View File

@ -14,7 +14,7 @@
#include "cpu_win.h" #include "cpu_win.h"
#elif defined(WEBRTC_MAC) #elif defined(WEBRTC_MAC)
#include "cpu_mac.h" #include "cpu_mac.h"
#elif defined(WEBRTC_ANDROID) #elif defined(WEBRTC_ANDROID) || defined(WEBRTC_BSD)
// Not implemented yet, might be possible to use Linux implementation // Not implemented yet, might be possible to use Linux implementation
#else // defined(WEBRTC_LINUX) #else // defined(WEBRTC_LINUX)
#include "cpu_linux.h" #include "cpu_linux.h"
@ -26,7 +26,7 @@ CpuWrapper* CpuWrapper::CreateCpu() {
return new CpuWindows(); return new CpuWindows();
#elif defined(WEBRTC_MAC) #elif defined(WEBRTC_MAC)
return new CpuWrapperMac(); return new CpuWrapperMac();
#elif defined(WEBRTC_ANDROID) #elif defined(WEBRTC_ANDROID) || defined(WEBRTC_BSD)
return 0; return 0;
#else #else
return new CpuLinux(); return new CpuLinux();

View File

@ -12,13 +12,15 @@
#if defined(_WIN32) #if defined(_WIN32)
#include <Windows.h> #include <Windows.h>
#elif defined(WEBRTC_MAC) #elif defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#include <sys/sysctl.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/sysctl.h>
#elif defined(WEBRTC_ANDROID) #elif defined(WEBRTC_ANDROID)
// Not implemented yet, might be possible to use Linux implementation // Not implemented yet, might be possible to use Linux implementation
#else // defined(WEBRTC_LINUX) #elif defined(WEBRTC_LINUX)
#include <sys/sysinfo.h> #include <sys/sysinfo.h>
#else // defined(_SC_NPROCESSORS_ONLN)
#include <unistd.h>
#endif #endif
#include "trace.h" #include "trace.h"
@ -41,8 +43,15 @@ WebRtc_UWord32 CpuInfo::DetectNumberOfCores() {
WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,
"Available number of cores:%d", number_of_cores_); "Available number of cores:%d", number_of_cores_);
#elif defined(WEBRTC_MAC) #elif defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
int name[] = {CTL_HW, HW_AVAILCPU}; int name[] = {
CTL_HW,
#ifdef HW_AVAILCPU
HW_AVAILCPU,
#else
HW_NCPU,
#endif
};
int ncpu; int ncpu;
size_t size = sizeof(ncpu); size_t size = sizeof(ncpu);
if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) { if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) {
@ -54,6 +63,8 @@ WebRtc_UWord32 CpuInfo::DetectNumberOfCores() {
"Failed to get number of cores"); "Failed to get number of cores");
number_of_cores_ = 1; number_of_cores_ = 1;
} }
#elif defined(_SC_NPROCESSORS_ONLN)
_numberOfCores = sysconf(_SC_NPROCESSORS_ONLN);
#else #else
WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1, WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1,
"No function to get number of cores"); "No function to get number of cores");

View File

@ -59,6 +59,17 @@
#include <sys/prctl.h> #include <sys/prctl.h>
#endif #endif
#if defined(__NetBSD__)
#include <lwp.h>
#elif defined(__FreeBSD__)
#include <sys/param.h>
#include <sys/thr.h>
#endif
#if defined(WEBRTC_BSD) && !defined(__NetBSD__)
#include <pthread_np.h>
#endif
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace.h"
@ -141,6 +152,20 @@ uint32_t ThreadWrapper::GetThreadId() {
return static_cast<uint32_t>(syscall(__NR_gettid)); return static_cast<uint32_t>(syscall(__NR_gettid));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
return pthread_mach_thread_np(pthread_self()); return pthread_mach_thread_np(pthread_self());
#elif defined(__NetBSD__)
return _lwp_self();
#elif defined(__DragonFly__)
return lwp_gettid();
#elif defined(__OpenBSD__)
return reinterpret_cast<uintptr_t> (pthread_self());
#elif defined(__FreeBSD__)
# if __FreeBSD_version > 900030
return pthread_getthreadid_np();
# else
long lwpid;
thr_self(&lwpid);
return lwpid;
# endif
#else #else
return reinterpret_cast<uint32_t>(pthread_self()); return reinterpret_cast<uint32_t>(pthread_self());
#endif #endif
@ -172,7 +197,7 @@ ThreadPosix::~ThreadPosix() {
delete crit_state_; delete crit_state_;
} }
#define HAS_THREAD_ID !defined(WEBRTC_IOS) && !defined(WEBRTC_MAC) #define HAS_THREAD_ID !defined(WEBRTC_IOS) && !defined(WEBRTC_MAC) && !defined(WEBRTC_BSD)
bool ThreadPosix::Start(unsigned int& thread_id) bool ThreadPosix::Start(unsigned int& thread_id)
{ {
@ -237,13 +262,17 @@ bool ThreadPosix::Start(unsigned int& thread_id)
// CPU_ZERO and CPU_SET are not available in NDK r7, so disable // CPU_ZERO and CPU_SET are not available in NDK r7, so disable
// SetAffinity on Android for now. // SetAffinity on Android for now.
#if (defined(WEBRTC_LINUX) && (!defined(WEBRTC_ANDROID)) && (!defined(WEBRTC_GONK))) #if defined(__FreeBSD__) || (defined(WEBRTC_LINUX) && (!defined(WEBRTC_ANDROID)) && (!defined(WEBRTC_GONK)))
bool ThreadPosix::SetAffinity(const int* processor_numbers, bool ThreadPosix::SetAffinity(const int* processor_numbers,
const unsigned int amount_of_processors) { const unsigned int amount_of_processors) {
if (!processor_numbers || (amount_of_processors == 0)) { if (!processor_numbers || (amount_of_processors == 0)) {
return false; return false;
} }
#if defined(__FreeBSD__)
cpuset_t mask;
#else
cpu_set_t mask; cpu_set_t mask;
#endif
CPU_ZERO(&mask); CPU_ZERO(&mask);
for (unsigned int processor = 0; for (unsigned int processor = 0;
@ -251,7 +280,11 @@ bool ThreadPosix::SetAffinity(const int* processor_numbers,
++processor) { ++processor) {
CPU_SET(processor_numbers[processor], &mask); CPU_SET(processor_numbers[processor], &mask);
} }
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_GONK) #if defined(__FreeBSD__)
const int result = pthread_setaffinity_np(thread_,
sizeof(mask),
&mask);
#elif defined(WEBRTC_ANDROID) || defined(WEBRTC_GONK)
// Android. // Android.
const int result = syscall(__NR_sched_setaffinity, const int result = syscall(__NR_sched_setaffinity,
pid_, pid_,
@ -325,6 +358,10 @@ void ThreadPosix::Run() {
if (set_thread_name_) { if (set_thread_name_) {
#ifdef WEBRTC_LINUX #ifdef WEBRTC_LINUX
prctl(PR_SET_NAME, (unsigned long)name_, 0, 0, 0); prctl(PR_SET_NAME, (unsigned long)name_, 0, 0, 0);
#elif defined(__NetBSD__)
pthread_setname_np(pthread_self(), "%s", (void *)name_);
#elif defined(WEBRTC_BSD)
pthread_set_name_np(pthread_self(), name_);
#endif #endif
WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,
"Thread with name:%s started ", name_); "Thread with name:%s started ", name_);

View File

@ -54,7 +54,7 @@ WebRtc_Word32 TracePosix::AddTime(char* trace_message,
} }
struct tm buffer; struct tm buffer;
const struct tm* system_time = const struct tm* system_time =
localtime_r(&system_time_high_res.tv_sec, &buffer); localtime_r((const time_t *)(&system_time_high_res.tv_sec), &buffer);
const WebRtc_UWord32 ms_time = system_time_high_res.tv_usec / 1000; const WebRtc_UWord32 ms_time = system_time_high_res.tv_usec / 1000;
WebRtc_UWord32 prev_tickCount = 0; WebRtc_UWord32 prev_tickCount = 0;

View File

@ -21,7 +21,7 @@
// For access to standard POSIXish features, use WEBRTC_POSIX instead of a // For access to standard POSIXish features, use WEBRTC_POSIX instead of a
// more specific macro. // more specific macro.
#if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) || \ #if defined(WEBRTC_MAC) || defined(WEBRTC_LINUX) || \
defined(WEBRTC_ANDROID) defined(WEBRTC_ANDROID) || defined(WEBRTC_BSD)
#define WEBRTC_POSIX #define WEBRTC_POSIX
#endif #endif

View File

@ -173,7 +173,7 @@ inline int ChannelId(const int moduleId) {
// Linux specific. // Linux specific.
#ifndef WEBRTC_ANDROID #ifndef WEBRTC_ANDROID
#ifdef WEBRTC_LINUX #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD)
// Build information macros. // Build information macros.
#if defined(_DEBUG) #if defined(_DEBUG)
#define BUILDMODE "d" #define BUILDMODE "d"

View File

@ -472,7 +472,7 @@ int VoENetworkImpl::SetSendTOS(int channel,
"SetSendTOS(channel=%d, DSCP=%d, useSetSockopt=%d)", "SetSendTOS(channel=%d, DSCP=%d, useSetSockopt=%d)",
channel, DSCP, useSetSockopt); channel, DSCP, useSetSockopt);
#if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_MAC) #if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_BSD) && !defined(WEBRTC_MAC)
_shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning,
"SetSendTOS() is not supported on this platform"); "SetSendTOS() is not supported on this platform");
return -1; return -1;
@ -528,7 +528,7 @@ int VoENetworkImpl::SetSendTOS(int channel,
"SetSendTOS() external transport is enabled"); "SetSendTOS() external transport is enabled");
return -1; return -1;
} }
#if defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) #if defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
useSetSockopt = true; useSetSockopt = true;
WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1),
" force useSetSockopt=true since there is no alternative" " force useSetSockopt=true since there is no alternative"
@ -551,7 +551,7 @@ int VoENetworkImpl::GetSendTOS(int channel,
WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1),
"GetSendTOS(channel=%d)", channel); "GetSendTOS(channel=%d)", channel);
#if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_MAC) #if !defined(_WIN32) && !defined(WEBRTC_LINUX) && !defined(WEBRTC_BSD) && !defined(WEBRTC_MAC)
_shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning, _shared->SetLastError(VE_FUNC_NOT_SUPPORTED, kTraceWarning,
"GetSendTOS() is not supported on this platform"); "GetSendTOS() is not supported on this platform");
return -1; return -1;

View File

@ -414,7 +414,7 @@ namespace webrtc
// *** WEBRTC_MAC *** // *** WEBRTC_MAC ***
// including iPhone // including iPhone
#ifdef WEBRTC_MAC #if defined(WEBRTC_BSD) || defined(WEBRTC_MAC)
#include <pthread.h> #include <pthread.h>
#include <sys/types.h> #include <sys/types.h>
@ -431,6 +431,7 @@ namespace webrtc
#include <sched.h> #include <sched.h>
#include <sys/time.h> #include <sys/time.h>
#include <time.h> #include <time.h>
#if !defined(WEBRTC_BSD)
#include <AudioUnit/AudioUnit.h> #include <AudioUnit/AudioUnit.h>
#if !defined(WEBRTC_IOS) #if !defined(WEBRTC_IOS)
#include <CoreServices/CoreServices.h> #include <CoreServices/CoreServices.h>
@ -439,6 +440,7 @@ namespace webrtc
#include <AudioToolbox/AudioConverter.h> #include <AudioToolbox/AudioConverter.h>
#include <CoreAudio/HostTime.h> #include <CoreAudio/HostTime.h>
#endif #endif
#endif
#define DWORD unsigned long int #define DWORD unsigned long int
#define WINAPI #define WINAPI
@ -531,7 +533,7 @@ namespace webrtc
#else #else
#define IPHONE_NOT_SUPPORTED(stat) #define IPHONE_NOT_SUPPORTED(stat)
#endif // #ifdef WEBRTC_MAC #endif // #if defined(WEBRTC_BSD) || defined(WEBRTC_MAC)

View File

@ -66,21 +66,32 @@ public class TabCounter extends GeckoTextSwitcher
} }
public void setCountWithAnimation(int count) { public void setCountWithAnimation(int count) {
if (mCount == count)
return;
// Don't animate from initial state // Don't animate from initial state
if (mCount != 0) { if (mCount == 0) {
if (count < mCount) { setCount(count);
setInAnimation(mFlipInBackward); return;
setOutAnimation(mFlipOutForward);
} else if (count > mCount) {
setInAnimation(mFlipInForward);
setOutAnimation(mFlipOutBackward);
}
} }
if (mCount == count) {
return;
}
if (count < mCount) {
setInAnimation(mFlipInBackward);
setOutAnimation(mFlipOutForward);
} else {
setInAnimation(mFlipInForward);
setOutAnimation(mFlipOutBackward);
}
// Eliminate screen artifact. Set explicit In/Out animation pair order. This will always
// animate pair in In->Out child order, prevent alternating use of the Out->In case.
setDisplayedChild(0);
// Set In value, trigger animation to Out value
setCurrentText(String.valueOf(mCount));
setText(String.valueOf(count)); setText(String.valueOf(count));
mCount = count; mCount = count;
} }