merge mozilla-inbound to mozilla-central a=merge

This commit is contained in:
Carsten "Tomcat" Book 2016-02-02 11:50:53 +01:00
commit 9468a26fac
274 changed files with 4668 additions and 3403 deletions

View File

@ -122,7 +122,14 @@ public:
*/ */
inline void ScheduleTextUpdate(nsIContent* aTextNode) inline void ScheduleTextUpdate(nsIContent* aTextNode)
{ {
if (mTextHash.PutEntry(aTextNode)) // Make sure we are not called with a node that is not in the DOM tree or
// not visible.
MOZ_ASSERT(aTextNode->GetParentNode(), "A text node is not in DOM");
MOZ_ASSERT(aTextNode->GetPrimaryFrame(), "A text node doesn't have a frame");
MOZ_ASSERT(aTextNode->GetPrimaryFrame()->StyleVisibility()->IsVisible(),
"A text node is not visible");
mTextHash.PutEntry(aTextNode);
ScheduleProcessing(); ScheduleProcessing();
} }

View File

@ -144,12 +144,6 @@
} }
} }
function sendErrorReport() {
var event = new CustomEvent("AboutNetErrorSendReport", {bubbles:true});
document.dispatchEvent(event);
}
function initPage() function initPage()
{ {
var err = getErrorCode(); var err = getErrorCode();
@ -260,13 +254,7 @@
var event = new CustomEvent("AboutNetErrorSetAutomatic", var event = new CustomEvent("AboutNetErrorSetAutomatic",
{bubbles:true, detail:evt.target.checked}); {bubbles:true, detail:evt.target.checked});
document.dispatchEvent(event); document.dispatchEvent(event);
if (evt.target.checked) {
sendErrorReport();
}
}, false); }, false);
var retryBtn = document.getElementById('reportCertificateErrorRetry');
retryBtn.addEventListener('click', sendErrorReport, false);
} }
} }
if (getErrorCode() == "weakCryptoUsed" || getErrorCode() == "sslv3Used") { if (getErrorCode() == "weakCryptoUsed" || getErrorCode() == "sslv3Used") {
@ -527,12 +515,6 @@
<p> <p>
<input type="checkbox" id="automaticallyReportInFuture" /> <input type="checkbox" id="automaticallyReportInFuture" />
<label for="automaticallyReportInFuture" id="automaticallyReportInFuture">&errorReporting.automatic2;</label> <label for="automaticallyReportInFuture" id="automaticallyReportInFuture">&errorReporting.automatic2;</label>
<span id="reportingState">
<button id="reportCertificateErrorRetry">&errorReporting.tryAgain;</button>
<span id="reportSendingMessage">&errorReporting.sending;</span>
<span id="reportSentMessage">&errorReporting.sent;</span>
</span>
</p> </p>
</div> </div>

View File

@ -96,13 +96,6 @@
})); }));
}); });
var retryBtn = document.getElementById("reportCertificateErrorRetry");
retryBtn.addEventListener("click", function () {
document.dispatchEvent(new CustomEvent("AboutCertErrorSendReport", {
bubbles: true
}));
});
addEventListener("AboutCertErrorOptions", function (event) { addEventListener("AboutCertErrorOptions", function (event) {
var options = JSON.parse(event.detail); var options = JSON.parse(event.detail);
if (options && options.enabled) { if (options && options.enabled) {
@ -287,12 +280,6 @@
<p> <p>
<input type="checkbox" id="automaticallyReportInFuture" /> <input type="checkbox" id="automaticallyReportInFuture" />
<label for="automaticallyReportInFuture" id="automaticallyReportInFuture">&errorReporting.automatic;</label> <label for="automaticallyReportInFuture" id="automaticallyReportInFuture">&errorReporting.automatic;</label>
<span id="reportingState">
<button id="reportCertificateErrorRetry">&errorReporting.tryAgain;</button>
<span id="reportSendingMessage">&errorReporting.sending;</span>
<span id="reportSentMessage">&errorReporting.sent;</span>
</span>
</p> </p>
</div> </div>

View File

@ -111,8 +111,8 @@ var FullZoom = {
// nsIContentPrefObserver // nsIContentPrefObserver
onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue) { onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue, aIsPrivate) {
this._onContentPrefChanged(aGroup, aValue); this._onContentPrefChanged(aGroup, aValue, aIsPrivate);
}, },
onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) { onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) {
@ -127,7 +127,7 @@ var FullZoom = {
* @param aValue The new value of the changed preference. Pass undefined to * @param aValue The new value of the changed preference. Pass undefined to
* indicate the preference's removal. * indicate the preference's removal.
*/ */
_onContentPrefChanged: function FullZoom__onContentPrefChanged(aGroup, aValue) { _onContentPrefChanged: function FullZoom__onContentPrefChanged(aGroup, aValue, aIsPrivate) {
if (this._isNextContentPrefChangeInternal) { if (this._isNextContentPrefChangeInternal) {
// Ignore changes that FullZoom itself makes. This works because the // Ignore changes that FullZoom itself makes. This works because the
// content pref service calls callbacks before notifying observers, and it // content pref service calls callbacks before notifying observers, and it
@ -140,9 +140,10 @@ var FullZoom = {
if (!browser.currentURI) if (!browser.currentURI)
return; return;
let ctxt = this._loadContextFromBrowser(browser);
let domain = this._cps2.extractDomain(browser.currentURI.spec); let domain = this._cps2.extractDomain(browser.currentURI.spec);
if (aGroup) { if (aGroup) {
if (aGroup == domain) if (aGroup == domain && ctxt.usePrivateBrowsing == aIsPrivate)
this._applyPrefToZoom(aValue, browser); this._applyPrefToZoom(aValue, browser);
return; return;
} }
@ -154,7 +155,6 @@ var FullZoom = {
// zoom should be set to the new global preference now that the global // zoom should be set to the new global preference now that the global
// preference has changed. // preference has changed.
let hasPref = false; let hasPref = false;
let ctxt = this._loadContextFromBrowser(browser);
let token = this._getBrowserToken(browser); let token = this._getBrowserToken(browser);
this._cps2.getByDomainAndName(browser.currentURI.spec, this.name, ctxt, { this._cps2.getByDomainAndName(browser.currentURI.spec, this.name, ctxt, {
handleResult: function () { hasPref = true; }, handleResult: function () { hasPref = true; },

View File

@ -2716,100 +2716,23 @@ var BrowserOnClick = {
}, },
onSSLErrorReport: function(browser, documentURI, location, securityInfo) { onSSLErrorReport: function(browser, documentURI, location, securityInfo) {
function showReportStatus(reportStatus) {
gBrowser.selectedBrowser
.messageManager
.sendAsyncMessage("Browser:SSLErrorReportStatus",
{
reportStatus: reportStatus,
documentURI: documentURI
});
}
if (!Services.prefs.getBoolPref("security.ssl.errorReporting.enabled")) { if (!Services.prefs.getBoolPref("security.ssl.errorReporting.enabled")) {
showReportStatus("error");
Cu.reportError("User requested certificate error report sending, but certificate error reporting is disabled"); Cu.reportError("User requested certificate error report sending, but certificate error reporting is disabled");
return; return;
} }
let bin = TLS_ERROR_REPORT_TELEMETRY_MANUAL_SEND;
if (Services.prefs.getBoolPref("security.ssl.errorReporting.automatic")) {
bin = TLS_ERROR_REPORT_TELEMETRY_AUTO_SEND;
}
Services.telemetry.getHistogramById("TLS_ERROR_REPORT_UI").add(bin);
let serhelper = Cc["@mozilla.org/network/serialization-helper;1"] let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
.getService(Ci.nsISerializationHelper); .getService(Ci.nsISerializationHelper);
let transportSecurityInfo = serhelper.deserializeObject(securityInfo); let transportSecurityInfo = serhelper.deserializeObject(securityInfo);
transportSecurityInfo.QueryInterface(Ci.nsITransportSecurityInfo) transportSecurityInfo.QueryInterface(Ci.nsITransportSecurityInfo)
showReportStatus("activity"); let errorReporter = Cc["@mozilla.org/securityreporter;1"]
.getService(Ci.nsISecurityReporter);
/* // if location.port is the empty string, set to -1 (for consistency with
* Requested info for the report: // port values from nsIURI)
* - Domain of bad connection let port = location.port === "" ? -1 : location.port;
* - Error type (e.g. Pinning, domain mismatch, etc) errorReporter.reportTLSError(transportSecurityInfo,
* - Cert chain (at minimum, same data to distrust each cert in the location.hostname, port);
* chain)
* - Request data (e.g. User Agent, IP, Timestamp)
*
* The request data should be added to the report by the receiving server.
*/
// Convert the nsIX509CertList into a format that can be parsed into
// JSON
let asciiCertChain = [];
if (transportSecurityInfo.failedCertChain) {
let certs = transportSecurityInfo.failedCertChain.getEnumerator();
while (certs.hasMoreElements()) {
let cert = certs.getNext();
cert.QueryInterface(Ci.nsIX509Cert);
asciiCertChain.push(btoa(getDERString(cert)));
}
}
let report = {
hostname: location.hostname,
port: location.port,
timestamp: Math.round(Date.now() / 1000),
errorCode: transportSecurityInfo.errorCode,
failedCertChain: asciiCertChain,
userAgent: window.navigator.userAgent,
version: 1,
build: gAppInfo.appBuildID,
product: gAppInfo.name,
channel: UpdateUtils.UpdateChannel
}
let reportURL = Services.prefs.getCharPref("security.ssl.errorReporting.url");
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
try {
xhr.open("POST", reportURL);
} catch (e) {
Cu.reportError("xhr.open exception", e);
showReportStatus("error");
}
xhr.onerror = function (e) {
// error making request to reportURL
Cu.reportError("xhr onerror", e);
showReportStatus("error");
};
xhr.onload = function (event) {
if (xhr.status !== 201 && xhr.status !== 0) {
// request returned non-success status
Cu.reportError("xhr returned failure code", xhr.status);
showReportStatus("error");
} else {
showReportStatus("complete");
}
};
xhr.send(JSON.stringify(report));
}, },
onAboutCertError: function (browser, elementId, isTopFrame, location, securityInfoAsString) { onAboutCertError: function (browser, elementId, isTopFrame, location, securityInfoAsString) {

View File

@ -210,10 +210,8 @@ const TLS_ERROR_REPORT_TELEMETRY_FAILURE = 7;
var AboutCertErrorListener = { var AboutCertErrorListener = {
init(chromeGlobal) { init(chromeGlobal) {
addMessageListener("AboutCertErrorDetails", this); addMessageListener("AboutCertErrorDetails", this);
addMessageListener("Browser:SSLErrorReportStatus", this);
chromeGlobal.addEventListener("AboutCertErrorLoad", this, false, true); chromeGlobal.addEventListener("AboutCertErrorLoad", this, false, true);
chromeGlobal.addEventListener("AboutCertErrorSetAutomatic", this, false, true); chromeGlobal.addEventListener("AboutCertErrorSetAutomatic", this, false, true);
chromeGlobal.addEventListener("AboutCertErrorSendReport", this, false, true);
}, },
get isAboutCertError() { get isAboutCertError() {
@ -232,9 +230,6 @@ var AboutCertErrorListener = {
case "AboutCertErrorSetAutomatic": case "AboutCertErrorSetAutomatic":
this.onSetAutomatic(event); this.onSetAutomatic(event);
break; break;
case "AboutCertErrorSendReport":
this.onSendReport();
break;
} }
}, },
@ -247,9 +242,6 @@ var AboutCertErrorListener = {
case "AboutCertErrorDetails": case "AboutCertErrorDetails":
this.onDetails(msg); this.onDetails(msg);
break; break;
case "Browser:SSLErrorReportStatus":
this.onReportStatus(msg);
break;
} }
}, },
@ -258,6 +250,11 @@ var AboutCertErrorListener = {
let ownerDoc = originalTarget.ownerDocument; let ownerDoc = originalTarget.ownerDocument;
ClickEventHandler.onAboutCertError(originalTarget, ownerDoc); ClickEventHandler.onAboutCertError(originalTarget, ownerDoc);
// Set up the TLS Error Reporting UI - reports are sent automatically
// (from nsHttpChannel::OnStopRequest) if the user has previously enabled
// automatic sending of reports. The UI ensures that a report is sent
// for the certificate error currently displayed if the user enables it
// here.
let automatic = Services.prefs.getBoolPref("security.ssl.errorReporting.automatic"); let automatic = Services.prefs.getBoolPref("security.ssl.errorReporting.automatic");
content.dispatchEvent(new content.CustomEvent("AboutCertErrorOptions", { content.dispatchEvent(new content.CustomEvent("AboutCertErrorOptions", {
detail: JSON.stringify({ detail: JSON.stringify({
@ -265,10 +262,6 @@ var AboutCertErrorListener = {
automatic, automatic,
}) })
})); }));
if (automatic) {
this.onSendReport();
}
}, },
onDetails(msg) { onDetails(msg) {
@ -277,16 +270,12 @@ var AboutCertErrorListener = {
}, },
onSetAutomatic(event) { onSetAutomatic(event) {
if (event.detail) {
this.onSendReport();
}
sendAsyncMessage("Browser:SetSSLErrorReportAuto", { sendAsyncMessage("Browser:SetSSLErrorReportAuto", {
automatic: event.detail automatic: event.detail
}); });
},
onSendReport() { // if we're enabling reports, send a report for this failure
if (event.detail) {
let doc = content.document; let doc = content.document;
let location = doc.location.href; let location = doc.location.href;
@ -304,41 +293,8 @@ var AboutCertErrorListener = {
location: {hostname: doc.location.hostname, port: doc.location.port}, location: {hostname: doc.location.hostname, port: doc.location.port},
securityInfo: serializedSecurityInfo securityInfo: serializedSecurityInfo
}); });
}
}, },
onReportStatus(msg) {
let doc = content.document;
if (doc.documentURI != msg.data.documentURI) {
return;
}
let reportSendingMsg = doc.getElementById("reportSendingMessage");
let reportSentMsg = doc.getElementById("reportSentMessage");
let retryBtn = doc.getElementById("reportCertificateErrorRetry");
switch (msg.data.reportStatus) {
case "activity":
// Hide the button that was just clicked
retryBtn.style.removeProperty("display");
reportSentMsg.style.removeProperty("display");
reportSendingMsg.style.display = "block";
break;
case "error":
// show the retry button
retryBtn.style.display = "block";
reportSendingMsg.style.removeProperty("display");
sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_FAILURE});
break;
case "complete":
// Show a success indicator
reportSentMsg.style.display = "block";
reportSendingMsg.style.removeProperty("display");
sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_SUCCESS});
break;
}
}
}; };
AboutCertErrorListener.init(this); AboutCertErrorListener.init(this);
@ -348,8 +304,6 @@ var AboutNetErrorListener = {
init: function(chromeGlobal) { init: function(chromeGlobal) {
chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true); chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true);
chromeGlobal.addEventListener('AboutNetErrorSetAutomatic', this, false, true); chromeGlobal.addEventListener('AboutNetErrorSetAutomatic', this, false, true);
chromeGlobal.addEventListener('AboutNetErrorSendReport', this, false, true);
chromeGlobal.addEventListener('AboutNetErrorUIExpanded', this, false, true);
chromeGlobal.addEventListener('AboutNetErrorOverride', this, false, true); chromeGlobal.addEventListener('AboutNetErrorOverride', this, false, true);
}, },
@ -369,13 +323,6 @@ var AboutNetErrorListener = {
case "AboutNetErrorSetAutomatic": case "AboutNetErrorSetAutomatic":
this.onSetAutomatic(aEvent); this.onSetAutomatic(aEvent);
break; break;
case "AboutNetErrorSendReport":
this.onSendReport(aEvent);
break;
case "AboutNetErrorUIExpanded":
sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_EXPANDED});
break;
case "AboutNetErrorOverride": case "AboutNetErrorOverride":
this.onOverride(aEvent); this.onOverride(aEvent);
break; break;
@ -389,68 +336,21 @@ var AboutNetErrorListener = {
enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"), enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"),
automatic: automatic automatic: automatic
}) })
} }));
));
sendAsyncMessage("Browser:SSLErrorReportTelemetry", sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN}); {reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN});
if (automatic) {
this.onSendReport(evt);
}
// hide parts of the UI we don't need yet
let contentDoc = content.document;
let reportSendingMsg = contentDoc.getElementById("reportSendingMessage");
let reportSentMsg = contentDoc.getElementById("reportSentMessage");
let retryBtn = contentDoc.getElementById("reportCertificateErrorRetry");
reportSendingMsg.style.display = "none";
reportSentMsg.style.display = "none";
retryBtn.style.display = "none";
}, },
onSetAutomatic: function(evt) { onSetAutomatic: function(evt) {
sendAsyncMessage("Browser:SetSSLErrorReportAuto", { sendAsyncMessage("Browser:SetSSLErrorReportAuto", {
automatic: evt.detail automatic: evt.detail
}); });
},
onSendReport: function(evt) { // if we're enabling reports, send a report for this failure
if (evt.detail) {
let contentDoc = content.document; let contentDoc = content.document;
let reportSendingMsg = contentDoc.getElementById("reportSendingMessage");
let reportSentMsg = contentDoc.getElementById("reportSentMessage");
let retryBtn = contentDoc.getElementById("reportCertificateErrorRetry");
addMessageListener("Browser:SSLErrorReportStatus", function(message) {
// show and hide bits - but only if this is a message for the right
// document - we'll compare on document URI
if (contentDoc.documentURI === message.data.documentURI) {
switch(message.data.reportStatus) {
case "activity":
// Hide the button that was just clicked
retryBtn.style.display = "none";
reportSentMsg.style.display = "none";
reportSendingMsg.style.removeProperty("display");
break;
case "error":
// show the retry button
retryBtn.style.removeProperty("display");
reportSendingMsg.style.display = "none";
sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_FAILURE});
break;
case "complete":
// Show a success indicator
reportSentMsg.style.removeProperty("display");
reportSendingMsg.style.display = "none";
sendAsyncMessage("Browser:SSLErrorReportTelemetry",
{reportStatus: TLS_ERROR_REPORT_TELEMETRY_SUCCESS});
break;
}
}
});
let location = contentDoc.location.href; let location = contentDoc.location.href;
let serhelper = Cc["@mozilla.org/network/serialization-helper;1"] let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
@ -470,6 +370,8 @@ var AboutNetErrorListener = {
}, },
securityInfo: serializedSecurityInfo securityInfo: serializedSecurityInfo
}); });
}
}, },
onOverride: function(evt) { onOverride: function(evt) {

View File

@ -28,13 +28,12 @@ registerCleanupFunction(() => {
add_task(function* test_send_report_neterror() { add_task(function* test_send_report_neterror() {
yield testSendReportAutomatically(URL_BAD_CHAIN, "succeed", "neterror"); yield testSendReportAutomatically(URL_BAD_CHAIN, "succeed", "neterror");
yield testSendReportAutomatically(URL_NO_CERT, "nocert", "neterror"); yield testSendReportAutomatically(URL_NO_CERT, "nocert", "neterror");
yield testSendReportFailRetry(URL_NO_CERT, "nocert", "neterror");
yield testSetAutomatic(URL_NO_CERT, "nocert", "neterror"); yield testSetAutomatic(URL_NO_CERT, "nocert", "neterror");
}); });
add_task(function* test_send_report_certerror() { add_task(function* test_send_report_certerror() {
yield testSendReportAutomatically(URL_BAD_CERT, "badcert", "certerror"); yield testSendReportAutomatically(URL_BAD_CERT, "badcert", "certerror");
yield testSendReportFailRetry(URL_BAD_CERT, "badcert", "certerror");
yield testSetAutomatic(URL_BAD_CERT, "badcert", "certerror"); yield testSetAutomatic(URL_BAD_CERT, "badcert", "certerror");
}); });
@ -65,10 +64,11 @@ function* testSendReportAutomatically(testURL, suffix, errorURISuffix) {
let browser = tab.linkedBrowser; let browser = tab.linkedBrowser;
// Load the page and wait for the error report submission. // Load the page and wait for the error report submission.
let promiseReport = createErrorReportPromise(browser); let promiseStatus = createReportResponseStatusPromise(URL_REPORTS + suffix);
browser.loadURI(testURL); browser.loadURI(testURL);
yield promiseReport;
ok(true, "SSL error report submitted successfully"); ok(!isErrorStatus(yield promiseStatus),
"SSL error report submitted successfully");
// Check that we loaded the right error page. // Check that we loaded the right error page.
yield checkErrorPage(browser, errorURISuffix); yield checkErrorPage(browser, errorURISuffix);
@ -78,30 +78,6 @@ function* testSendReportAutomatically(testURL, suffix, errorURISuffix) {
cleanup(); cleanup();
}; };
function* testSendReportFailRetry(testURL, suffix, errorURISuffix) {
try {
yield testSendReportAutomatically(testURL, "error", errorURISuffix);
ok(false, "sending a report should have failed");
} catch (err) {
ok(err, "saw a failure notification");
}
Services.prefs.setCharPref(PREF_REPORT_URL, URL_REPORTS + suffix);
let browser = gBrowser.selectedBrowser;
let promiseReport = createErrorReportPromise(browser);
let promiseRetry = ContentTask.spawn(browser, null, function* () {
content.document.getElementById("reportCertificateErrorRetry").click();
});
yield Promise.all([promiseReport, promiseRetry]);
ok(true, "SSL error report submitted successfully");
// Cleanup.
gBrowser.removeCurrentTab();
cleanup();
}
function* testSetAutomatic(testURL, suffix, errorURISuffix) { function* testSetAutomatic(testURL, suffix, errorURISuffix) {
Services.prefs.setBoolPref(PREF_REPORT_ENABLED, true); Services.prefs.setBoolPref(PREF_REPORT_ENABLED, true);
Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, false); Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, false);
@ -118,15 +94,15 @@ function* testSetAutomatic(testURL, suffix, errorURISuffix) {
// Check that we loaded the right error page. // Check that we loaded the right error page.
yield checkErrorPage(browser, errorURISuffix); yield checkErrorPage(browser, errorURISuffix);
let statusPromise = createReportResponseStatusPromise(URL_REPORTS + suffix);
// Click the checkbox, enable automatic error reports. // Click the checkbox, enable automatic error reports.
let promiseReport = createErrorReportPromise(browser);
yield ContentTask.spawn(browser, null, function* () { yield ContentTask.spawn(browser, null, function* () {
content.document.getElementById("automaticallyReportInFuture").click(); content.document.getElementById("automaticallyReportInFuture").click();
}); });
// Wait for the error report submission. // Wait for the error report submission.
yield promiseReport; yield statusPromise;
ok(true, "SSL error report submitted successfully");
let isAutomaticReportingEnabled = () => let isAutomaticReportingEnabled = () =>
Services.prefs.getBoolPref(PREF_REPORT_AUTOMATIC); Services.prefs.getBoolPref(PREF_REPORT_AUTOMATIC);
@ -170,32 +146,22 @@ function* testSendReportDisabled(testURL, errorURISuffix) {
gBrowser.removeTab(tab); gBrowser.removeTab(tab);
} }
function createErrorReportPromise(browser) { function isErrorStatus(status) {
return ContentTask.spawn(browser, null, function* () { return status < 200 || status >= 300;
let type = "Browser:SSLErrorReportStatus"; }
let active = false;
yield new Promise((resolve, reject) => { // use the observer service to see when a report is sent
addMessageListener(type, function onReportStatus(message) { function createReportResponseStatusPromise(expectedURI) {
switch (message.data.reportStatus) { return new Promise(resolve => {
case "activity": let observer = (subject, topic, data) => {
active = true; subject.QueryInterface(Ci.nsIHttpChannel);
break; let requestURI = subject.URI.spec;
case "complete": if (requestURI == expectedURI) {
removeMessageListener(type, onReportStatus); Services.obs.removeObserver(observer, "http-on-examine-response");
if (active) { resolve(subject.responseStatus);
resolve(message.data.reportStatus);
} else {
reject("activity should be seen before success");
} }
break; };
case "error": Services.obs.addObserver(observer, "http-on-examine-response", false);
removeMessageListener(type, onReportStatus);
reject("sending the report failed");
break;
}
});
});
}); });
} }

View File

@ -85,7 +85,7 @@ function handleRequest(request, response) {
break; break;
default: default:
response.setStatusLine("1.1", 500, "Server error"); response.setStatusLine("1.1", 500, "Server error");
response.write("<html>succeed, nocert or error expected</html>"); response.write("<html>succeed, nocert or error expected (got " + request.queryString + ")</html>");
break; break;
} }
} }

View File

@ -0,0 +1,4 @@
# The source "build" only needs a mozconfig because we use the build system as
# our script for generating it. This allows us to run configure without any
# extra dependencies on specific toolchains, e.g. gtk3.
ac_add_options --disable-compile-environment

View File

@ -36,6 +36,3 @@ you know there's a good reason why this site doesn't use trusted identification.
<!ENTITY certerror.copyToClipboard.label "Copy text to clipboard"> <!ENTITY certerror.copyToClipboard.label "Copy text to clipboard">
<!ENTITY errorReporting.automatic "Report errors like this to help Mozilla identify misconfigured sites"> <!ENTITY errorReporting.automatic "Report errors like this to help Mozilla identify misconfigured sites">
<!ENTITY errorReporting.sending "Sending report">
<!ENTITY errorReporting.sent "Report sent">
<!ENTITY errorReporting.tryAgain "Try again">

View File

@ -206,9 +206,6 @@ functionality specific to firefox. -->
<!ENTITY errorReporting.automatic2 "Report errors like this to help Mozilla identify and block malicious sites"> <!ENTITY errorReporting.automatic2 "Report errors like this to help Mozilla identify and block malicious sites">
<!ENTITY errorReporting.learnMore "Learn more…"> <!ENTITY errorReporting.learnMore "Learn more…">
<!ENTITY errorReporting.sending "Sending report">
<!ENTITY errorReporting.sent "Report sent">
<!ENTITY errorReporting.tryAgain "Try again">
<!ENTITY remoteXUL.title "Remote XUL"> <!ENTITY remoteXUL.title "Remote XUL">
<!ENTITY remoteXUL.longDesc "<p><ul><li>Please contact the website owners to inform them of this problem.</li></ul></p>"> <!ENTITY remoteXUL.longDesc "<p><ul><li>Please contact the website owners to inform them of this problem.</li></ul></p>">

View File

@ -7,6 +7,9 @@
#include "mozilla/BasePrincipal.h" #include "mozilla/BasePrincipal.h"
#include "nsDocShell.h" #include "nsDocShell.h"
#ifdef MOZ_CRASHREPORTER
#include "nsExceptionHandler.h"
#endif
#include "nsIAddonPolicyService.h" #include "nsIAddonPolicyService.h"
#include "nsIContentSecurityPolicy.h" #include "nsIContentSecurityPolicy.h"
#include "nsIObjectInputStream.h" #include "nsIObjectInputStream.h"
@ -121,7 +124,13 @@ OriginAttributes::CreateSuffix(nsACString& aStr) const
} }
if (!mAddonId.IsEmpty()) { if (!mAddonId.IsEmpty()) {
MOZ_RELEASE_ASSERT(mAddonId.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) == kNotFound); if (mAddonId.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) != kNotFound) {
#ifdef MOZ_CRASHREPORTER
CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("Crash_AddonId"),
NS_ConvertUTF16toUTF8(mAddonId));
#endif
MOZ_CRASH();
}
params->Set(NS_LITERAL_STRING("addonId"), mAddonId); params->Set(NS_LITERAL_STRING("addonId"), mAddonId);
} }

View File

@ -32,8 +32,13 @@ EXPORTS.mozilla = [
'BasePrincipal.h' 'BasePrincipal.h'
] ]
UNIFIED_SOURCES += [ SOURCES += [
# Compile this separately since nsExceptionHandler.h conflicts
# with something from nsNullPrincipal.cpp.
'BasePrincipal.cpp', 'BasePrincipal.cpp',
]
UNIFIED_SOURCES += [
'DomainPolicy.cpp', 'DomainPolicy.cpp',
'nsJSPrincipals.cpp', 'nsJSPrincipals.cpp',
'nsNullPrincipal.cpp', 'nsNullPrincipal.cpp',

View File

@ -27,6 +27,7 @@
#include "nsXPIDLString.h" #include "nsXPIDLString.h"
#include "nsCRT.h" #include "nsCRT.h"
#include "nsCRTGlue.h" #include "nsCRTGlue.h"
#include "nsDocShell.h"
#include "nsError.h" #include "nsError.h"
#include "nsDOMCID.h" #include "nsDOMCID.h"
#include "nsIXPConnect.h" #include "nsIXPConnect.h"

View File

@ -530,7 +530,7 @@ case "$target" in
MSVS_VERSION=2013 MSVS_VERSION=2013
MSVC_C_RUNTIME_DLL=msvcr120.dll MSVC_C_RUNTIME_DLL=msvcr120.dll
MSVC_CXX_RUNTIME_DLL=msvcp120.dll MSVC_CXX_RUNTIME_DLL=msvcp120.dll
elif test "$_CC_MAJOR_VERSION" = "19"; then elif test "$_CC_MAJOR_VERSION" = "19" -a "$_CC_BUILD_VERSION" -ge "23506"; then
_CC_SUITE=14 _CC_SUITE=14
MSVS_VERSION=2015 MSVS_VERSION=2015
MSVC_C_RUNTIME_DLL=vcruntime140.dll MSVC_C_RUNTIME_DLL=vcruntime140.dll
@ -557,7 +557,7 @@ case "$target" in
CXXFLAGS="$CXXFLAGS -wd4091" CXXFLAGS="$CXXFLAGS -wd4091"
else else
AC_MSG_ERROR([This version (${_CC_MAJOR_VERSION}.${_CC_MINOR_VERSION}.${_CC_BUILD_VERSION}) of the MSVC compiler is unsupported. AC_MSG_ERROR([This version (${_CC_MAJOR_VERSION}.${_CC_MINOR_VERSION}.${_CC_BUILD_VERSION}) of the MSVC compiler is unsupported.
You must install Visual C++ 2013 Update 3 or newer in order to build. You must install Visual C++ 2013 Update 3, Visual C++ 2015 Update 1, or newer in order to build.
See https://developer.mozilla.org/en/Windows_Build_Prerequisites.]) See https://developer.mozilla.org/en/Windows_Build_Prerequisites.])
fi fi
AC_SUBST(MSVS_VERSION) AC_SUBST(MSVS_VERSION)

View File

@ -72,7 +72,6 @@ skip-if = buildapp == 'mulet'
[browser_bug655270.js] [browser_bug655270.js]
[browser_bug655273.js] [browser_bug655273.js]
[browser_bug670318.js] [browser_bug670318.js]
skip-if = (os == 'mac' && debug) # Bug 1241704
[browser_bug673467.js] [browser_bug673467.js]
[browser_bug852909.js] [browser_bug852909.js]
[browser_bug92473.js] [browser_bug92473.js]

View File

@ -14,7 +14,7 @@ add_task(function* test() {
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
function* (browser) { function* (browser) {
yield ContentTask.spawn(browser, URL, function* (URL) { yield ContentTask.spawn(browser, URL, function* (URL) {
let history = docShell.sessionHistory; let history = docShell.QueryInterface(Ci.nsIWebNavigation).sessionHistory;
let count = 0; let count = 0;
let testDone = {}; let testDone = {};

View File

@ -10,6 +10,9 @@
#include "nsContentUtils.h" #include "nsContentUtils.h"
#include "nsCExternalHandlerService.h" #include "nsCExternalHandlerService.h"
#include "mozilla/UniquePtr.h"
using namespace mozilla;
using namespace mozilla::dom; using namespace mozilla::dom;
USING_ARCHIVEREADER_NAMESPACE USING_ARCHIVEREADER_NAMESPACE
@ -191,8 +194,8 @@ ArchiveReaderZipEvent::Exec()
} }
// Read the name: // Read the name:
nsAutoArrayPtr<char> filename(new char[filenameLen + 1]); auto filename = MakeUnique<char[]>(filenameLen + 1);
rv = inputStream->Read(filename, filenameLen, &ret); rv = inputStream->Read(filename.get(), filenameLen, &ret);
if (NS_FAILED(rv) || ret != filenameLen) { if (NS_FAILED(rv) || ret != filenameLen) {
return RunShare(NS_ERROR_UNEXPECTED); return RunShare(NS_ERROR_UNEXPECTED);
} }
@ -201,7 +204,8 @@ ArchiveReaderZipEvent::Exec()
// We ignore the directories: // We ignore the directories:
if (filename[filenameLen - 1] != '/') { if (filename[filenameLen - 1] != '/') {
mFileList.AppendElement(new ArchiveZipItem(filename, centralStruct, mEncoding)); mFileList.AppendElement(new ArchiveZipItem(filename.get(), centralStruct,
mEncoding));
} }
// Ignore the rest // Ignore the rest

View File

@ -128,6 +128,11 @@
#include <cutils/properties.h> #include <cutils/properties.h>
#endif #endif
#ifdef MOZ_PAY
#include "nsIPaymentContentHelperService.h"
#include "mozilla/dom/DOMRequest.h"
#endif
namespace mozilla { namespace mozilla {
namespace dom { namespace dom {
@ -2672,6 +2677,36 @@ Navigator::MozE10sEnabled()
return true; return true;
} }
#ifdef MOZ_PAY
already_AddRefed<DOMRequest>
Navigator::MozPay(JSContext* aCx,
JS::Handle<JS::Value> aJwts,
ErrorResult& aRv)
{
if (!mWindow || !mWindow->GetDocShell()) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsresult rv;
nsCOMPtr<nsIPaymentContentHelperService> service =
do_GetService("@mozilla.org/payment/content-helper-service;1", &rv);
if (!service) {
aRv.Throw(rv);
return nullptr;
}
RefPtr<nsIDOMDOMRequest> request;
rv = service->Pay(mWindow, aJwts, getter_AddRefs(request));
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return nullptr;
}
return request.forget().downcast<DOMRequest>();
}
#endif // MOZ_PAY
/* static */ /* static */
already_AddRefed<nsPIDOMWindowInner> already_AddRefed<nsPIDOMWindowInner>
Navigator::GetWindowFromGlobal(JSObject* aGlobal) Navigator::GetWindowFromGlobal(JSObject* aGlobal)

View File

@ -42,6 +42,7 @@ class WakeLock;
class ArrayBufferViewOrBlobOrStringOrFormData; class ArrayBufferViewOrBlobOrStringOrFormData;
struct MobileIdOptions; struct MobileIdOptions;
class ServiceWorkerContainer; class ServiceWorkerContainer;
class DOMRequest;
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla
@ -315,6 +316,12 @@ public:
bool MozE10sEnabled(); bool MozE10sEnabled();
#ifdef MOZ_PAY
already_AddRefed<DOMRequest> MozPay(JSContext* aCx,
JS::Handle<JS::Value> aJwts,
ErrorResult& aRv);
#endif // MOZ_PAY
static void GetAcceptLanguages(nsTArray<nsString>& aLanguages); static void GetAcceptLanguages(nsTArray<nsString>& aLanguages);
// WebIDL helper methods // WebIDL helper methods

View File

@ -8,6 +8,8 @@
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/WebKitCSSMatrixBinding.h" #include "mozilla/dom/WebKitCSSMatrixBinding.h"
#include "nsCSSParser.h"
#include "nsStyleTransformMatrix.h"
namespace mozilla { namespace mozilla {
namespace dom { namespace dom {
@ -56,11 +58,58 @@ WebKitCSSMatrix*
WebKitCSSMatrix::SetMatrixValue(const nsAString& aTransformList, WebKitCSSMatrix::SetMatrixValue(const nsAString& aTransformList,
ErrorResult& aRv) ErrorResult& aRv)
{ {
DOMMatrix::SetMatrixValue(aTransformList, aRv); // An empty string is a no-op.
if (NS_WARN_IF(aRv.Failed())) { if (aTransformList.IsEmpty()) {
return this;
}
nsCSSValue value;
nsCSSParser parser;
bool parseSuccess = parser.ParseTransformProperty(aTransformList,
true,
value);
if (!parseSuccess) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return nullptr; return nullptr;
} }
// A value of "none" results in a 2D identity matrix.
if (value.GetUnit() == eCSSUnit_None) {
mMatrix3D = nullptr;
mMatrix2D = new gfx::Matrix();
return this;
}
// A value other than a transform-list is a syntax error.
if (value.GetUnit() != eCSSUnit_SharedList) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return nullptr;
}
RuleNodeCacheConditions dummy;
nsStyleTransformMatrix::TransformReferenceBox dummyBox;
bool contains3dTransform = false;
gfx::Matrix4x4 transform = nsStyleTransformMatrix::ReadTransforms(
value.GetSharedListValue()->mHead,
nullptr, nullptr, dummy, dummyBox,
nsPresContext::AppUnitsPerCSSPixel(),
&contains3dTransform);
if (!contains3dTransform) {
mMatrix3D = nullptr;
mMatrix2D = new gfx::Matrix();
SetA(transform._11);
SetB(transform._12);
SetC(transform._21);
SetD(transform._22);
SetE(transform._41);
SetF(transform._42);
} else {
mMatrix3D = new gfx::Matrix4x4(transform);
mMatrix2D = nullptr;
}
return this; return this;
} }

View File

@ -3282,15 +3282,39 @@ nsIDocument::ElementFromPoint(float aX, float aY)
return ElementFromPointHelper(aX, aY, false, true); return ElementFromPointHelper(aX, aY, false, true);
} }
void
nsIDocument::ElementsFromPoint(float aX, float aY,
nsTArray<RefPtr<Element>>& aElements)
{
ElementsFromPointHelper(aX, aY, nsIDocument::FLUSH_LAYOUT, aElements);
}
Element* Element*
nsDocument::ElementFromPointHelper(float aX, float aY, nsDocument::ElementFromPointHelper(float aX, float aY,
bool aIgnoreRootScrollFrame, bool aIgnoreRootScrollFrame,
bool aFlushLayout) bool aFlushLayout)
{ {
// As per the the spec, we return null if either coord is negative nsAutoTArray<RefPtr<Element>, 1> elementArray;
if (!aIgnoreRootScrollFrame && (aX < 0 || aY < 0)) { ElementsFromPointHelper(aX, aY,
((aIgnoreRootScrollFrame ? nsIDocument::IGNORE_ROOT_SCROLL_FRAME : 0) |
(aFlushLayout ? nsIDocument::FLUSH_LAYOUT : 0) |
nsIDocument::IS_ELEMENT_FROM_POINT),
elementArray);
if (elementArray.IsEmpty()) {
return nullptr; return nullptr;
} }
return elementArray[0];
}
void
nsDocument::ElementsFromPointHelper(float aX, float aY,
uint32_t aFlags,
nsTArray<RefPtr<mozilla::dom::Element>>& aElements)
{
// As per the the spec, we return null if either coord is negative
if (!(aFlags & nsIDocument::IGNORE_ROOT_SCROLL_FRAME) && (aX < 0 || aY < 0)) {
return;
}
nscoord x = nsPresContext::CSSPixelsToAppUnits(aX); nscoord x = nsPresContext::CSSPixelsToAppUnits(aX);
nscoord y = nsPresContext::CSSPixelsToAppUnits(aY); nscoord y = nsPresContext::CSSPixelsToAppUnits(aY);
@ -3298,32 +3322,58 @@ nsDocument::ElementFromPointHelper(float aX, float aY,
// Make sure the layout information we get is up-to-date, and // Make sure the layout information we get is up-to-date, and
// ensure we get a root frame (for everything but XUL) // ensure we get a root frame (for everything but XUL)
if (aFlushLayout) if (aFlags & nsIDocument::FLUSH_LAYOUT) {
FlushPendingNotifications(Flush_Layout); FlushPendingNotifications(Flush_Layout);
}
nsIPresShell *ps = GetShell(); nsIPresShell *ps = GetShell();
if (!ps) { if (!ps) {
return nullptr; return;
} }
nsIFrame *rootFrame = ps->GetRootFrame(); nsIFrame *rootFrame = ps->GetRootFrame();
// XUL docs, unlike HTML, have no frame tree until everything's done loading // XUL docs, unlike HTML, have no frame tree until everything's done loading
if (!rootFrame) { if (!rootFrame) {
return nullptr; // return null to premature XUL callers as a reminder to wait return; // return null to premature XUL callers as a reminder to wait
} }
nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, pt, nsTArray<nsIFrame*> outFrames;
// Emulate what GetFrameAtPoint does, since we want all the frames under our
// point.
nsLayoutUtils::GetFramesForArea(rootFrame, nsRect(pt, nsSize(1, 1)), outFrames,
nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC | nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC |
(aIgnoreRootScrollFrame ? nsLayoutUtils::IGNORE_ROOT_SCROLL_FRAME : 0)); ((aFlags & nsIDocument::IGNORE_ROOT_SCROLL_FRAME) ? nsLayoutUtils::IGNORE_ROOT_SCROLL_FRAME : 0));
if (!ptFrame) {
return nullptr; // Dunno when this would ever happen, as we should at least have a root frame under us?
if (outFrames.IsEmpty()) {
return;
} }
nsIContent* elem = GetContentInThisDocument(ptFrame); // Used to filter out repeated elements in sequence.
if (elem && !elem->IsElement()) { nsIContent* lastAdded = nullptr;
elem = elem->GetParent();
for (uint32_t i = 0; i < outFrames.Length(); i++) {
nsIContent* node = GetContentInThisDocument(outFrames[i]);
if (!node || !node->IsElement()) {
// If this helper is called via ElementsFromPoint, we need to make sure
// our frame is an element. Otherwise return whatever the top frame is
// even if it isn't the top-painted element.
if (!(aFlags & nsIDocument::IS_ELEMENT_FROM_POINT)) {
continue;
}
node = node->GetParent();
}
if (node && node != lastAdded) {
aElements.AppendElement(node->AsElement());
lastAdded = node;
// If this helper is called via ElementFromPoint, just return the first
// element we find.
if (aFlags & nsIDocument::IS_ELEMENT_FROM_POINT) {
return;
}
}
} }
return elem ? elem->AsElement() : nullptr;
} }
nsresult nsresult

View File

@ -1034,6 +1034,10 @@ public:
bool aIgnoreRootScrollFrame, bool aIgnoreRootScrollFrame,
bool aFlushLayout) override; bool aFlushLayout) override;
virtual void ElementsFromPointHelper(float aX, float aY,
uint32_t aFlags,
nsTArray<RefPtr<mozilla::dom::Element>>& aElements) override;
virtual nsresult NodesFromRectHelper(float aX, float aY, virtual nsresult NodesFromRectHelper(float aX, float aY,
float aTopSize, float aRightSize, float aTopSize, float aRightSize,
float aBottomSize, float aLeftSize, float aBottomSize, float aLeftSize,

View File

@ -2340,6 +2340,7 @@ CreateNativeGlobalForInner(JSContext* aCx,
if (aNewInner->GetOuterWindow()) { if (aNewInner->GetOuterWindow()) {
top = aNewInner->GetTopInternal(); top = aNewInner->GetTopInternal();
} }
JS::CompartmentOptions options; JS::CompartmentOptions options;
// Sometimes add-ons load their own XUL windows, either as separate top-level // Sometimes add-ons load their own XUL windows, either as separate top-level
@ -2353,6 +2354,8 @@ CreateNativeGlobalForInner(JSContext* aCx,
options.creationOptions().setSameZoneAs(top->GetGlobalJSObject()); options.creationOptions().setSameZoneAs(top->GetGlobalJSObject());
} }
xpc::InitGlobalObjectOptions(options, aPrincipal);
// Determine if we need the Components object. // Determine if we need the Components object.
bool needComponents = nsContentUtils::IsSystemPrincipal(aPrincipal) || bool needComponents = nsContentUtils::IsSystemPrincipal(aPrincipal) ||
TreatAsRemoteXUL(aPrincipal); TreatAsRemoteXUL(aPrincipal);

View File

@ -1669,6 +1669,16 @@ public:
bool aIgnoreRootScrollFrame, bool aIgnoreRootScrollFrame,
bool aFlushLayout) = 0; bool aFlushLayout) = 0;
enum ElementsFromPointFlags {
IGNORE_ROOT_SCROLL_FRAME = 1,
FLUSH_LAYOUT = 2,
IS_ELEMENT_FROM_POINT = 4
};
virtual void ElementsFromPointHelper(float aX, float aY,
uint32_t aFlags,
nsTArray<RefPtr<mozilla::dom::Element>>& aElements) = 0;
virtual nsresult NodesFromRectHelper(float aX, float aY, virtual nsresult NodesFromRectHelper(float aX, float aY,
float aTopSize, float aRightSize, float aTopSize, float aRightSize,
float aBottomSize, float aLeftSize, float aBottomSize, float aLeftSize,
@ -2531,6 +2541,9 @@ public:
virtual mozilla::dom::DOMStringList* StyleSheetSets() = 0; virtual mozilla::dom::DOMStringList* StyleSheetSets() = 0;
virtual void EnableStyleSheetsForSet(const nsAString& aSheetSet) = 0; virtual void EnableStyleSheetsForSet(const nsAString& aSheetSet) = 0;
Element* ElementFromPoint(float aX, float aY); Element* ElementFromPoint(float aX, float aY);
void ElementsFromPoint(float aX,
float aY,
nsTArray<RefPtr<mozilla::dom::Element>>& aElements);
/** /**
* Retrieve the location of the caret position (DOM node and character * Retrieve the location of the caret position (DOM node and character

View File

@ -11,7 +11,6 @@
#include "nsDOMNavigationTiming.h" #include "nsDOMNavigationTiming.h"
#include "nsContentUtils.h" #include "nsContentUtils.h"
#include "nsIScriptSecurityManager.h" #include "nsIScriptSecurityManager.h"
#include "nsGlobalWindow.h"
#include "nsIDOMWindow.h" #include "nsIDOMWindow.h"
#include "nsILoadInfo.h" #include "nsILoadInfo.h"
#include "nsIURI.h" #include "nsIURI.h"
@ -30,8 +29,6 @@
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "mozilla/IntegerPrintfMacros.h" #include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/TimeStamp.h" #include "mozilla/TimeStamp.h"
#include "SharedWorker.h"
#include "ServiceWorker.h"
#include "js/HeapAPI.h" #include "js/HeapAPI.h"
#include "GeckoProfiler.h" #include "GeckoProfiler.h"
#include "WorkerPrivate.h" #include "WorkerPrivate.h"
@ -918,37 +915,6 @@ PerformanceBase::ClearResourceTimings()
mResourceEntries.Clear(); mResourceEntries.Clear();
} }
DOMHighResTimeStamp
PerformanceBase::TranslateTime(DOMHighResTimeStamp aTime,
const WindowOrWorkerOrSharedWorkerOrServiceWorker& aTimeSource,
ErrorResult& aRv)
{
TimeStamp otherCreationTimeStamp;
if (aTimeSource.IsWindow()) {
RefPtr<nsPerformance> performance = aTimeSource.GetAsWindow().GetPerformance();
if (NS_WARN_IF(!performance)) {
aRv.Throw(NS_ERROR_FAILURE);
}
otherCreationTimeStamp = performance->CreationTimeStamp();
} else if (aTimeSource.IsWorker()) {
otherCreationTimeStamp = aTimeSource.GetAsWorker().CreationTimeStamp();
} else if (aTimeSource.IsSharedWorker()) {
SharedWorker& sharedWorker = aTimeSource.GetAsSharedWorker();
WorkerPrivate* workerPrivate = sharedWorker.GetWorkerPrivate();
otherCreationTimeStamp = workerPrivate->CreationTimeStamp();
} else if (aTimeSource.IsServiceWorker()) {
ServiceWorker& serviceWorker = aTimeSource.GetAsServiceWorker();
WorkerPrivate* workerPrivate = serviceWorker.GetWorkerPrivate();
otherCreationTimeStamp = workerPrivate->CreationTimeStamp();
} else {
MOZ_CRASH("This should not be possible.");
}
return RoundTime(
aTime + (otherCreationTimeStamp - CreationTimeStamp()).ToMilliseconds());
}
DOMHighResTimeStamp DOMHighResTimeStamp
PerformanceBase::RoundTime(double aTime) const PerformanceBase::RoundTime(double aTime) const
{ {

View File

@ -30,7 +30,6 @@ namespace dom {
class PerformanceEntry; class PerformanceEntry;
class PerformanceObserver; class PerformanceObserver;
class WindowOrWorkerOrSharedWorkerOrServiceWorker;
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla
@ -318,11 +317,6 @@ public:
virtual DOMHighResTimeStamp Now() const = 0; virtual DOMHighResTimeStamp Now() const = 0;
DOMHighResTimeStamp
TranslateTime(DOMHighResTimeStamp aTime,
const mozilla::dom::WindowOrWorkerOrSharedWorkerOrServiceWorker& aTimeSource,
mozilla::ErrorResult& aRv);
void Mark(const nsAString& aName, mozilla::ErrorResult& aRv); void Mark(const nsAString& aName, mozilla::ErrorResult& aRv);
void ClearMarks(const mozilla::dom::Optional<nsAString>& aName); void ClearMarks(const mozilla::dom::Optional<nsAString>& aName);
void Measure(const nsAString& aName, void Measure(const nsAString& aName,

View File

@ -3803,8 +3803,8 @@ ArrayBufferBuilder::getArrayBuffer(JSContext* aCx)
} }
mMapPtr = nullptr; mMapPtr = nullptr;
// The memory-mapped contents will be released when obj been finalized(GCed // The memory-mapped contents will be released when the ArrayBuffer becomes
// or neutered). // detached or is GC'd.
return obj; return obj;
} }

View File

@ -1 +0,0 @@
/* nothing here */

View File

@ -257,7 +257,6 @@ support-files =
file_explicit_user_agent.sjs file_explicit_user_agent.sjs
referrer_change_server.sjs referrer_change_server.sjs
file_change_policy_redirect.html file_change_policy_redirect.html
empty_worker.js
file_bug1198095.js file_bug1198095.js
[test_anonymousContent_api.html] [test_anonymousContent_api.html]
@ -868,7 +867,6 @@ skip-if = e10s || os != 'linux' || buildapp != 'browser'
[test_change_policy.html] [test_change_policy.html]
skip-if = buildapp == 'b2g' #no ssl support skip-if = buildapp == 'b2g' #no ssl support
[test_document.all_iteration.html] [test_document.all_iteration.html]
[test_performance_translate.html]
[test_bug1198095.html] [test_bug1198095.html]
[test_bug1187157.html] [test_bug1187157.html]
[test_bug769117.html] [test_bug769117.html]

View File

@ -1,75 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Test for performance.translate()</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="test_performance_user_timing.js"></script>
</head>
<body>
<pre id="test">
<script class="testbody" type="text/javascript">
function testBasic() {
ok("translateTime" in performance, "Performance.translateTime exists.");
try {
performance.translateTime(0, null);
ok(false, "Wrong use of performance.translateTime.");
} catch(e) {
ok(true, "Wrong use of performance.translateTime.");
}
next();
}
function testWindow() {
is(performance.translateTime(42, this), 42, "translating time with the same window.");
var now = performance.now();
var ifr = document.createElement('iframe');
ifr.src = 'file_empty.html';
document.body.appendChild(ifr);
ifr.onload = function() {
var a = performance.translateTime(0, ifr.contentWindow);
ok (a >= now, "Time has been translated from a window that started loading later than we did");
next();
}
}
function testWorker() {
var now = performance.now();
var w = new Worker('empty_worker.js');
var a = performance.translateTime(0, w);
// bug 1226147
ok (a >= now, "Time has been translated from a Worker that started loading later than we did");
next();
}
function testSharedWorker() {
var now = performance.now();
var w = new SharedWorker('empty_worker.js');
var a = performance.translateTime(0, w);
ok (a >= now, "Time has been translated from a SharedWorker that started loading later than we did");
next();
}
var tests = [ testBasic, testWindow, testWorker, testSharedWorker ];
function next() {
if (!tests.length) {
SimpleTest.finish();
return;
}
var test = tests.shift();
test();
}
SimpleTest.waitForExplicitFinish();
addLoadEvent(next);
</script>
</pre>
</body>
</html>

View File

@ -3023,6 +3023,11 @@ RegisterDOMNames();
// The return value is whatever the ProtoHandleGetter we used // The return value is whatever the ProtoHandleGetter we used
// returned. This should be the DOM prototype for the global. // returned. This should be the DOM prototype for the global.
//
// Typically this method's caller will want to ensure that
// xpc::InitGlobalObjectOptions is called before, and xpc::InitGlobalObject is
// called after, this method, to ensure that this global object and its
// compartment are consistent with other global objects.
template <class T, ProtoHandleGetter GetProto> template <class T, ProtoHandleGetter GetProto>
JS::Handle<JSObject*> JS::Handle<JSObject*>
CreateGlobal(JSContext* aCx, T* aNative, nsWrapperCache* aCache, CreateGlobal(JSContext* aCx, T* aNative, nsWrapperCache* aCache,

View File

@ -2273,8 +2273,7 @@ nsGonkCameraControl::CreatePoster(Image* aImage, uint32_t aWidth, uint32_t aHeig
// ARGB is 32 bits / pixel // ARGB is 32 bits / pixel
size_t tmpLength = mWidth * mHeight * sizeof(uint32_t); size_t tmpLength = mWidth * mHeight * sizeof(uint32_t);
nsAutoArrayPtr<uint8_t> tmp; UniquePtr<uint8_t[]> tmp = MakeUnique<uint8_t[]>(tmpLength);
tmp = new uint8_t[tmpLength];
GrallocImage* nativeImage = static_cast<GrallocImage*>(mImage.get()); GrallocImage* nativeImage = static_cast<GrallocImage*>(mImage.get());
android::sp<GraphicBuffer> graphicBuffer = nativeImage->GetGraphicBuffer(); android::sp<GraphicBuffer> graphicBuffer = nativeImage->GetGraphicBuffer();
@ -2284,7 +2283,7 @@ nsGonkCameraControl::CreatePoster(Image* aImage, uint32_t aWidth, uint32_t aHeig
uint32_t stride = mWidth * 4; uint32_t stride = mWidth * 4;
int err = libyuv::ConvertToARGB(static_cast<uint8_t*>(graphicSrc), int err = libyuv::ConvertToARGB(static_cast<uint8_t*>(graphicSrc),
srcLength, tmp, stride, 0, 0, srcLength, tmp.get(), stride, 0, 0,
mWidth, mHeight, mWidth, mHeight, mWidth, mHeight, mWidth, mHeight,
libyuv::kRotate0, libyuv::FOURCC_NV21); libyuv::kRotate0, libyuv::FOURCC_NV21);
@ -2307,7 +2306,7 @@ nsGonkCameraControl::CreatePoster(Image* aImage, uint32_t aWidth, uint32_t aHeig
} }
nsString opt; nsString opt;
nsresult rv = encoder->InitFromData(tmp, tmpLength, mWidth, nsresult rv = encoder->InitFromData(tmp.get(), tmpLength, mWidth,
mHeight, stride, mHeight, stride,
imgIEncoder::INPUT_FORMAT_HOSTARGB, imgIEncoder::INPUT_FORMAT_HOSTARGB,
opt); opt);

View File

@ -7,6 +7,7 @@
#include "mozilla/dom/TextDecoder.h" #include "mozilla/dom/TextDecoder.h"
#include "mozilla/dom/EncodingUtils.h" #include "mozilla/dom/EncodingUtils.h"
#include "mozilla/dom/UnionTypes.h" #include "mozilla/dom/UnionTypes.h"
#include "mozilla/UniquePtrExtensions.h"
#include "nsContentUtils.h" #include "nsContentUtils.h"
#include <stdint.h> #include <stdint.h>
@ -65,18 +66,18 @@ TextDecoder::Decode(const char* aInput, const int32_t aLength,
} }
// Need a fallible allocator because the caller may be a content // Need a fallible allocator because the caller may be a content
// and the content can specify the length of the string. // and the content can specify the length of the string.
nsAutoArrayPtr<char16_t> buf(new (fallible) char16_t[outLen + 1]); auto buf = MakeUniqueFallible<char16_t[]>(outLen + 1);
if (!buf) { if (!buf) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY); aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return; return;
} }
int32_t length = aLength; int32_t length = aLength;
rv = mDecoder->Convert(aInput, &length, buf, &outLen); rv = mDecoder->Convert(aInput, &length, buf.get(), &outLen);
MOZ_ASSERT(mFatal || rv != NS_ERROR_ILLEGAL_INPUT); MOZ_ASSERT(mFatal || rv != NS_ERROR_ILLEGAL_INPUT);
buf[outLen] = 0; buf[outLen] = 0;
if (!aOutDecodedString.Append(buf, outLen, fallible)) { if (!aOutDecodedString.Append(buf.get(), outLen, fallible)) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY); aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return; return;
} }

View File

@ -6,6 +6,7 @@
#include "mozilla/dom/TextEncoder.h" #include "mozilla/dom/TextEncoder.h"
#include "mozilla/dom/EncodingUtils.h" #include "mozilla/dom/EncodingUtils.h"
#include "mozilla/UniquePtrExtensions.h"
#include "nsContentUtils.h" #include "nsContentUtils.h"
namespace mozilla { namespace mozilla {
@ -54,18 +55,18 @@ TextEncoder::Encode(JSContext* aCx,
} }
// Need a fallible allocator because the caller may be a content // Need a fallible allocator because the caller may be a content
// and the content can specify the length of the string. // and the content can specify the length of the string.
nsAutoArrayPtr<char> buf(new (fallible) char[maxLen + 1]); auto buf = MakeUniqueFallible<char[]>(maxLen + 1);
if (!buf) { if (!buf) {
aRv.Throw(NS_ERROR_OUT_OF_MEMORY); aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
return; return;
} }
int32_t dstLen = maxLen; int32_t dstLen = maxLen;
rv = mEncoder->Convert(data, &srcLen, buf, &dstLen); rv = mEncoder->Convert(data, &srcLen, buf.get(), &dstLen);
// Now reset the encoding algorithm state to the default values for encoding. // Now reset the encoding algorithm state to the default values for encoding.
int32_t finishLen = maxLen - dstLen; int32_t finishLen = maxLen - dstLen;
rv = mEncoder->Finish(buf + dstLen, &finishLen); rv = mEncoder->Finish(&buf[dstLen], &finishLen);
if (NS_SUCCEEDED(rv)) { if (NS_SUCCEEDED(rv)) {
dstLen += finishLen; dstLen += finishLen;
} }

View File

@ -1107,7 +1107,7 @@ Event::TimeStamp() const
MOZ_ASSERT(workerPrivate); MOZ_ASSERT(workerPrivate);
TimeDuration duration = TimeDuration duration =
mEvent->timeStamp - workerPrivate->CreationTimeStamp(); mEvent->timeStamp - workerPrivate->NowBaseTimeStamp();
return duration.ToMilliseconds(); return duration.ToMilliseconds();
} }

View File

@ -2006,6 +2006,7 @@ EventStateManager::GetContentViewer(nsIContentViewer** aCv)
nsCOMPtr<mozIDOMWindowProxy> focusedWindow; nsCOMPtr<mozIDOMWindowProxy> focusedWindow;
fm->GetFocusedWindow(getter_AddRefs(focusedWindow)); fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
if (!focusedWindow) return NS_ERROR_FAILURE;
auto* ourWindow = nsPIDOMWindowOuter::From(focusedWindow); auto* ourWindow = nsPIDOMWindowOuter::From(focusedWindow);

View File

@ -74,9 +74,8 @@ function testWorkerEvents() {
var worker = new Worker(window.URL.createObjectURL(blob)); var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(evt) { worker.onmessage = function(evt) {
var timeAfterEvent = window.performance.now(); var timeAfterEvent = window.performance.now();
var time = window.performance.translateTime(evt.data, worker); ok(evt.data > timeBeforeEvent &&
ok(time >= timeBeforeEvent && evt.data < timeAfterEvent,
time <= timeAfterEvent,
"Event timestamp in dedicated worker (" + evt.data + "Event timestamp in dedicated worker (" + evt.data +
") is in expected range: (" + ") is in expected range: (" +
timeBeforeEvent + ", " + timeAfterEvent + ")"); timeBeforeEvent + ", " + timeAfterEvent + ")");

View File

@ -250,15 +250,13 @@ Directory::GetPath(nsAString& aRetval) const
already_AddRefed<Promise> already_AddRefed<Promise>
Directory::GetFilesAndDirectories() Directory::GetFilesAndDirectories()
{ {
nsresult error = NS_OK;
nsString realPath;
ErrorResult rv; ErrorResult rv;
RefPtr<GetDirectoryListingTask> task = RefPtr<GetDirectoryListingTask> task =
new GetDirectoryListingTask(mFileSystem, mPath, mFilters, rv); new GetDirectoryListingTask(mFileSystem, mPath, mFilters, rv);
if (NS_WARN_IF(rv.Failed())) { if (NS_WARN_IF(rv.Failed())) {
return nullptr; return nullptr;
} }
task->SetError(error);
FileSystemPermissionRequest::RequestForTask(task); FileSystemPermissionRequest::RequestForTask(task);
return task->GetPromise(); return task->GetPromise();
} }

View File

@ -8,6 +8,7 @@
#include "mozilla/dom/HTMLFrameSetElementBinding.h" #include "mozilla/dom/HTMLFrameSetElementBinding.h"
#include "mozilla/dom/EventHandlerBinding.h" #include "mozilla/dom/EventHandlerBinding.h"
#include "nsGlobalWindow.h" #include "nsGlobalWindow.h"
#include "mozilla/UniquePtrExtensions.h"
NS_IMPL_NS_NEW_HTML_ELEMENT(FrameSet) NS_IMPL_NS_NEW_HTML_ELEMENT(FrameSet)
@ -81,7 +82,7 @@ HTMLFrameSetElement::SetAttr(int32_t aNameSpaceID,
*/ */
if (aAttribute == nsGkAtoms::rows && aNameSpaceID == kNameSpaceID_None) { if (aAttribute == nsGkAtoms::rows && aNameSpaceID == kNameSpaceID_None) {
int32_t oldRows = mNumRows; int32_t oldRows = mNumRows;
ParseRowCol(aValue, mNumRows, getter_Transfers(mRowSpecs)); ParseRowCol(aValue, mNumRows, &mRowSpecs);
if (mNumRows != oldRows) { if (mNumRows != oldRows) {
mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE; mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE;
@ -89,7 +90,7 @@ HTMLFrameSetElement::SetAttr(int32_t aNameSpaceID,
} else if (aAttribute == nsGkAtoms::cols && } else if (aAttribute == nsGkAtoms::cols &&
aNameSpaceID == kNameSpaceID_None) { aNameSpaceID == kNameSpaceID_None) {
int32_t oldCols = mNumCols; int32_t oldCols = mNumCols;
ParseRowCol(aValue, mNumCols, getter_Transfers(mColSpecs)); ParseRowCol(aValue, mNumCols, &mColSpecs);
if (mNumCols != oldCols) { if (mNumCols != oldCols) {
mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE; mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE;
@ -116,19 +117,19 @@ HTMLFrameSetElement::GetRowSpec(int32_t *aNumValues,
const nsAttrValue* value = GetParsedAttr(nsGkAtoms::rows); const nsAttrValue* value = GetParsedAttr(nsGkAtoms::rows);
if (value && value->Type() == nsAttrValue::eString) { if (value && value->Type() == nsAttrValue::eString) {
nsresult rv = ParseRowCol(value->GetStringValue(), mNumRows, nsresult rv = ParseRowCol(value->GetStringValue(), mNumRows,
getter_Transfers(mRowSpecs)); &mRowSpecs);
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);
} }
if (!mRowSpecs) { // we may not have had an attr or had an empty attr if (!mRowSpecs) { // we may not have had an attr or had an empty attr
mRowSpecs = new nsFramesetSpec[1]; mRowSpecs = MakeUnique<nsFramesetSpec[]>(1);
mNumRows = 1; mNumRows = 1;
mRowSpecs[0].mUnit = eFramesetUnit_Relative; mRowSpecs[0].mUnit = eFramesetUnit_Relative;
mRowSpecs[0].mValue = 1; mRowSpecs[0].mValue = 1;
} }
} }
*aSpecs = mRowSpecs; *aSpecs = mRowSpecs.get();
*aNumValues = mNumRows; *aNumValues = mNumRows;
return NS_OK; return NS_OK;
} }
@ -146,19 +147,19 @@ HTMLFrameSetElement::GetColSpec(int32_t *aNumValues,
const nsAttrValue* value = GetParsedAttr(nsGkAtoms::cols); const nsAttrValue* value = GetParsedAttr(nsGkAtoms::cols);
if (value && value->Type() == nsAttrValue::eString) { if (value && value->Type() == nsAttrValue::eString) {
nsresult rv = ParseRowCol(value->GetStringValue(), mNumCols, nsresult rv = ParseRowCol(value->GetStringValue(), mNumCols,
getter_Transfers(mColSpecs)); &mColSpecs);
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);
} }
if (!mColSpecs) { // we may not have had an attr or had an empty attr if (!mColSpecs) { // we may not have had an attr or had an empty attr
mColSpecs = new nsFramesetSpec[1]; mColSpecs = MakeUnique<nsFramesetSpec[]>(1);
mNumCols = 1; mNumCols = 1;
mColSpecs[0].mUnit = eFramesetUnit_Relative; mColSpecs[0].mUnit = eFramesetUnit_Relative;
mColSpecs[0].mValue = 1; mColSpecs[0].mValue = 1;
} }
} }
*aSpecs = mColSpecs; *aSpecs = mColSpecs.get();
*aNumValues = mNumCols; *aNumValues = mNumCols;
return NS_OK; return NS_OK;
} }
@ -205,7 +206,7 @@ HTMLFrameSetElement::GetAttributeChangeHint(const nsIAtom* aAttribute,
nsresult nsresult
HTMLFrameSetElement::ParseRowCol(const nsAString & aValue, HTMLFrameSetElement::ParseRowCol(const nsAString & aValue,
int32_t& aNumSpecs, int32_t& aNumSpecs,
nsFramesetSpec** aSpecs) UniquePtr<nsFramesetSpec[]>* aSpecs)
{ {
if (aValue.IsEmpty()) { if (aValue.IsEmpty()) {
aNumSpecs = 0; aNumSpecs = 0;
@ -233,7 +234,7 @@ HTMLFrameSetElement::ParseRowCol(const nsAString & aValue,
commaX = spec.FindChar(sComma, commaX + 1); commaX = spec.FindChar(sComma, commaX + 1);
} }
nsFramesetSpec* specs = new (fallible) nsFramesetSpec[count]; auto specs = MakeUniqueFallible<nsFramesetSpec[]>(count);
if (!specs) { if (!specs) {
*aSpecs = nullptr; *aSpecs = nullptr;
aNumSpecs = 0; aNumSpecs = 0;
@ -327,7 +328,7 @@ HTMLFrameSetElement::ParseRowCol(const nsAString & aValue,
aNumSpecs = count; aNumSpecs = count;
// Transfer ownership to caller here // Transfer ownership to caller here
*aSpecs = specs; *aSpecs = Move(specs);
return NS_OK; return NS_OK;
} }

View File

@ -8,6 +8,7 @@
#define HTMLFrameSetElement_h #define HTMLFrameSetElement_h
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/UniquePtr.h"
#include "nsIDOMHTMLFrameSetElement.h" #include "nsIDOMHTMLFrameSetElement.h"
#include "nsGenericHTMLElement.h" #include "nsGenericHTMLElement.h"
@ -145,7 +146,7 @@ protected:
private: private:
nsresult ParseRowCol(const nsAString& aValue, nsresult ParseRowCol(const nsAString& aValue,
int32_t& aNumSpecs, int32_t& aNumSpecs,
nsFramesetSpec** aSpecs); UniquePtr<nsFramesetSpec[]>* aSpecs);
/** /**
* The number of size specs in our "rows" attr * The number of size specs in our "rows" attr
@ -163,11 +164,11 @@ private:
/** /**
* The parsed representation of the "rows" attribute * The parsed representation of the "rows" attribute
*/ */
nsAutoArrayPtr<nsFramesetSpec> mRowSpecs; // parsed, non-computed dimensions UniquePtr<nsFramesetSpec[]> mRowSpecs; // parsed, non-computed dimensions
/** /**
* The parsed representation of the "cols" attribute * The parsed representation of the "cols" attribute
*/ */
nsAutoArrayPtr<nsFramesetSpec> mColSpecs; // parsed, non-computed dimensions UniquePtr<nsFramesetSpec[]> mColSpecs; // parsed, non-computed dimensions
}; };
} // namespace dom } // namespace dom

View File

@ -10,7 +10,7 @@ interface nsIContentURIGrouper;
interface nsILoadContext; interface nsILoadContext;
interface mozIStorageConnection; interface mozIStorageConnection;
[scriptable, uuid(746c7a02-f6c1-4869-b434-7c8b86e60e61)] [scriptable, uuid(43635c53-b445-4c4e-8cc5-562697299b55)]
interface nsIContentPrefObserver : nsISupports interface nsIContentPrefObserver : nsISupports
{ {
/** /**
@ -20,8 +20,13 @@ interface nsIContentPrefObserver : nsISupports
* if it's a global pref (applies to all sites) * if it's a global pref (applies to all sites)
* @param aName the name of the pref that was set * @param aName the name of the pref that was set
* @param aValue the new value of the pref * @param aValue the new value of the pref
* @param aIsPrivate an optional flag determining whether the
* original context is private or not
*/ */
void onContentPrefSet(in AString aGroup, in AString aName, in nsIVariant aValue); void onContentPrefSet(in AString aGroup,
in AString aName,
in nsIVariant aValue,
[optional] in boolean aIsPrivate);
/** /**
* Called when a content pref is removed. * Called when a content pref is removed.

View File

@ -673,10 +673,6 @@ ContentChild::Init(MessageLoop* aIOLoop,
} }
sSingleton = this; sSingleton = this;
// Make sure there's an nsAutoScriptBlocker on the stack when dispatching
// urgent messages.
GetIPCChannel()->BlockScripts();
// If communications with the parent have broken down, take the process // If communications with the parent have broken down, take the process
// down so it's not hanging around. // down so it's not hanging around.
bool abortOnError = true; bool abortOnError = true;

View File

@ -38,6 +38,7 @@
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "mozilla/TextEvents.h" #include "mozilla/TextEvents.h"
#include "mozilla/TouchEvents.h" #include "mozilla/TouchEvents.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/unused.h" #include "mozilla/unused.h"
#include "BlobParent.h" #include "BlobParent.h"
#include "nsCOMPtr.h" #include "nsCOMPtr.h"
@ -2125,25 +2126,25 @@ TabParent::RecvEnableDisableCommands(const nsString& aAction,
{ {
nsCOMPtr<nsIRemoteBrowser> remoteBrowser = do_QueryInterface(mFrameElement); nsCOMPtr<nsIRemoteBrowser> remoteBrowser = do_QueryInterface(mFrameElement);
if (remoteBrowser) { if (remoteBrowser) {
nsAutoArrayPtr<const char*> enabledCommands, disabledCommands; UniquePtr<const char*[]> enabledCommands, disabledCommands;
if (aEnabledCommands.Length()) { if (aEnabledCommands.Length()) {
enabledCommands = new const char* [aEnabledCommands.Length()]; enabledCommands = MakeUnique<const char*[]>(aEnabledCommands.Length());
for (uint32_t c = 0; c < aEnabledCommands.Length(); c++) { for (uint32_t c = 0; c < aEnabledCommands.Length(); c++) {
enabledCommands[c] = aEnabledCommands[c].get(); enabledCommands[c] = aEnabledCommands[c].get();
} }
} }
if (aDisabledCommands.Length()) { if (aDisabledCommands.Length()) {
disabledCommands = new const char* [aDisabledCommands.Length()]; disabledCommands = MakeUnique<const char*[]>(aDisabledCommands.Length());
for (uint32_t c = 0; c < aDisabledCommands.Length(); c++) { for (uint32_t c = 0; c < aDisabledCommands.Length(); c++) {
disabledCommands[c] = aDisabledCommands[c].get(); disabledCommands[c] = aDisabledCommands[c].get();
} }
} }
remoteBrowser->EnableDisableCommands(aAction, remoteBrowser->EnableDisableCommands(aAction,
aEnabledCommands.Length(), enabledCommands, aEnabledCommands.Length(), enabledCommands.get(),
aDisabledCommands.Length(), disabledCommands); aDisabledCommands.Length(), disabledCommands.get());
} }
return true; return true;

View File

@ -107,6 +107,7 @@ MP4Decoder::CanHandleMediaType(const nsACString& aMIMETypeExcludingCodecs,
aMIMETypeExcludingCodecs.EqualsASCII(VIDEO_3GPP) || aMIMETypeExcludingCodecs.EqualsASCII(VIDEO_3GPP) ||
#endif #endif
aMIMETypeExcludingCodecs.EqualsASCII("video/mp4") || aMIMETypeExcludingCodecs.EqualsASCII("video/mp4") ||
aMIMETypeExcludingCodecs.EqualsASCII("video/quicktime") ||
aMIMETypeExcludingCodecs.EqualsASCII("video/x-m4v"); aMIMETypeExcludingCodecs.EqualsASCII("video/x-m4v");
if (!isMP4Audio && !isMP4Video) { if (!isMP4Audio && !isMP4Video) {
return false; return false;

View File

@ -427,7 +427,7 @@ TEST(MP4Demuxer, GetNextKeyframe)
}); });
} }
TEST(MP4Demuxer, ZeroInMoov) TEST(MP4Demuxer, ZeroInLastMoov)
{ {
RefPtr<MP4DemuxerBinding> binding = new MP4DemuxerBinding("short-zero-in-moov.mp4"); RefPtr<MP4DemuxerBinding> binding = new MP4DemuxerBinding("short-zero-in-moov.mp4");
binding->RunTestAndWait([binding] () { binding->RunTestAndWait([binding] () {
@ -436,3 +436,12 @@ TEST(MP4Demuxer, ZeroInMoov)
}); });
} }
TEST(MP4Demuxer, ZeroInMoovQuickTime)
{
RefPtr<MP4DemuxerBinding> binding = new MP4DemuxerBinding("short-zero-inband.mov");
binding->RunTestAndWait([binding] () {
// It demuxes without error. That is sufficient.
binding->mTaskQueue->BeginShutdown();
});
}

View File

@ -49,6 +49,7 @@ TEST_HARNESS_FILES.gtest += [
'noise.mp3', 'noise.mp3',
'noise_vbr.mp3', 'noise_vbr.mp3',
'short-zero-in-moov.mp4', 'short-zero-in-moov.mp4',
'short-zero-inband.mov',
'small-shot.mp3', 'small-shot.mp3',
'test.webm', 'test.webm',
'test_case_1224361.vp8.ivf', 'test_case_1224361.vp8.ivf',

Binary file not shown.

View File

@ -24,6 +24,7 @@
#include "mozilla/dom/ToJSValue.h" #include "mozilla/dom/ToJSValue.h"
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "mozilla/Services.h" #include "mozilla/Services.h"
#include "mozilla/UniquePtr.h"
#include "nsIMmsService.h" #include "nsIMmsService.h"
#include "nsIMobileMessageCallback.h" #include "nsIMobileMessageCallback.h"
#include "nsIMobileMessageDatabaseService.h" #include "nsIMobileMessageDatabaseService.h"
@ -424,7 +425,7 @@ MobileMessageManager::GetMessages(const MobileMessageFilter& aFilter,
endDate = aFilter.mEndDate.Value(); endDate = aFilter.mEndDate.Value();
} }
nsAutoArrayPtr<const char16_t*> ptrNumbers; UniquePtr<const char16_t*[]> ptrNumbers;
uint32_t numbersCount = 0; uint32_t numbersCount = 0;
if (!aFilter.mNumbers.IsNull() && if (!aFilter.mNumbers.IsNull() &&
aFilter.mNumbers.Value().Length()) { aFilter.mNumbers.Value().Length()) {
@ -432,7 +433,7 @@ MobileMessageManager::GetMessages(const MobileMessageFilter& aFilter,
uint32_t index; uint32_t index;
numbersCount = numbers.Length(); numbersCount = numbers.Length();
ptrNumbers = new const char16_t* [numbersCount]; ptrNumbers = MakeUnique<const char16_t*[]>(numbersCount);
for (index = 0; index < numbersCount; index++) { for (index = 0; index < numbersCount; index++) {
ptrNumbers[index] = numbers[index].get(); ptrNumbers[index] = numbers[index].get();
} }
@ -464,7 +465,7 @@ MobileMessageManager::GetMessages(const MobileMessageFilter& aFilter,
nsCOMPtr<nsICursorContinueCallback> continueCallback; nsCOMPtr<nsICursorContinueCallback> continueCallback;
nsresult rv = dbService->CreateMessageCursor(hasStartDate, startDate, nsresult rv = dbService->CreateMessageCursor(hasStartDate, startDate,
hasEndDate, endDate, hasEndDate, endDate,
ptrNumbers, numbersCount, ptrNumbers.get(), numbersCount,
delivery, delivery,
hasRead, read, hasRead, read,
hasThreadId, threadId, hasThreadId, threadId,

View File

@ -22,6 +22,7 @@
#include "mozilla/dom/File.h" #include "mozilla/dom/File.h"
#include "mozilla/dom/ToJSValue.h" #include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType #include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
#include "mozilla/UniquePtr.h"
#include "nsContentUtils.h" #include "nsContentUtils.h"
#include "nsTArrayHelpers.h" #include "nsTArrayHelpers.h"
#include "xpcpublic.h" #include "xpcpublic.h"
@ -830,12 +831,12 @@ MobileMessageCursorParent::DoRequest(const CreateMessageCursorRequest& aRequest)
const SmsFilterData& filter = aRequest.filter(); const SmsFilterData& filter = aRequest.filter();
const nsTArray<nsString>& numbers = filter.numbers(); const nsTArray<nsString>& numbers = filter.numbers();
nsAutoArrayPtr<const char16_t*> ptrNumbers; UniquePtr<const char16_t*[]> ptrNumbers;
uint32_t numbersCount = numbers.Length(); uint32_t numbersCount = numbers.Length();
if (numbersCount) { if (numbersCount) {
uint32_t index; uint32_t index;
ptrNumbers = new const char16_t* [numbersCount]; ptrNumbers = MakeUnique<const char16_t*[]>(numbersCount);
for (index = 0; index < numbersCount; index++) { for (index = 0; index < numbersCount; index++) {
ptrNumbers[index] = numbers[index].get(); ptrNumbers[index] = numbers[index].get();
} }
@ -845,7 +846,7 @@ MobileMessageCursorParent::DoRequest(const CreateMessageCursorRequest& aRequest)
filter.startDate(), filter.startDate(),
filter.hasEndDate(), filter.hasEndDate(),
filter.endDate(), filter.endDate(),
ptrNumbers, numbersCount, ptrNumbers.get(), numbersCount,
filter.delivery(), filter.delivery(),
filter.hasRead(), filter.hasRead(),
filter.read(), filter.read(),

View File

@ -111,7 +111,6 @@ NetworkStatsAlarm.prototype = {
const NETWORKSTATSMANAGER_CONTRACTID = "@mozilla.org/networkStatsManager;1"; const NETWORKSTATSMANAGER_CONTRACTID = "@mozilla.org/networkStatsManager;1";
const NETWORKSTATSMANAGER_CID = Components.ID("{ceb874cd-cc1a-4e65-b404-cc2d3e42425f}"); const NETWORKSTATSMANAGER_CID = Components.ID("{ceb874cd-cc1a-4e65-b404-cc2d3e42425f}");
const nsIDOMMozNetworkStatsManager = Ci.nsIDOMMozNetworkStatsManager;
function NetworkStatsManager() { function NetworkStatsManager() {
if (DEBUG) { if (DEBUG) {
@ -122,26 +121,11 @@ function NetworkStatsManager() {
NetworkStatsManager.prototype = { NetworkStatsManager.prototype = {
__proto__: DOMRequestIpcHelper.prototype, __proto__: DOMRequestIpcHelper.prototype,
checkPrivileges: function checkPrivileges() {
if (!this.hasPrivileges) {
throw Components.Exception("Permission denied", Cr.NS_ERROR_FAILURE);
}
},
getSamples: function getSamples(aNetwork, aStart, aEnd, aOptions) { getSamples: function getSamples(aNetwork, aStart, aEnd, aOptions) {
this.checkPrivileges(); if (aStart > aEnd) {
if (aStart.constructor.name !== "Date" ||
aEnd.constructor.name !== "Date" ||
!(aNetwork instanceof this.window.MozNetworkStatsInterface) ||
aStart > aEnd) {
throw Components.results.NS_ERROR_INVALID_ARG; throw Components.results.NS_ERROR_INVALID_ARG;
} }
let appManifestURL = null;
let browsingTrafficOnly = false;
let serviceType = null;
if (aOptions) {
// appManifestURL is used to query network statistics by app; // appManifestURL is used to query network statistics by app;
// serviceType is used to query network statistics by system service. // serviceType is used to query network statistics by system service.
// It is illegal to specify both of them at the same time. // It is illegal to specify both of them at the same time.
@ -152,10 +136,10 @@ NetworkStatsManager.prototype = {
if (!aOptions.appManifestURL && aOptions.browsingTrafficOnly) { if (!aOptions.appManifestURL && aOptions.browsingTrafficOnly) {
throw Components.results.NS_ERROR_NOT_IMPLEMENTED; throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
} }
appManifestURL = aOptions.appManifestURL;
serviceType = aOptions.serviceType; let appManifestURL = aOptions.appManifestURL;
browsingTrafficOnly = aOptions.browsingTrafficOnly || false; let serviceType = aOptions.serviceType;
} let browsingTrafficOnly = aOptions.browsingTrafficOnly;
// TODO Bug 929410 Date object cannot correctly pass through cpmm/ppmm IPC // TODO Bug 929410 Date object cannot correctly pass through cpmm/ppmm IPC
// This is just a work-around by passing timestamp numbers. // This is just a work-around by passing timestamp numbers.
@ -175,12 +159,6 @@ NetworkStatsManager.prototype = {
}, },
clearStats: function clearStats(aNetwork) { clearStats: function clearStats(aNetwork) {
this.checkPrivileges();
if (!aNetwork instanceof this.window.MozNetworkStatsInterface) {
throw Components.results.NS_ERROR_INVALID_ARG;
}
let request = this.createRequest(); let request = this.createRequest();
cpmm.sendAsyncMessage("NetworkStats:Clear", cpmm.sendAsyncMessage("NetworkStats:Clear",
{ network: aNetwork.toJSON(), { network: aNetwork.toJSON(),
@ -189,8 +167,6 @@ NetworkStatsManager.prototype = {
}, },
clearAllStats: function clearAllStats() { clearAllStats: function clearAllStats() {
this.checkPrivileges();
let request = this.createRequest(); let request = this.createRequest();
cpmm.sendAsyncMessage("NetworkStats:ClearAll", cpmm.sendAsyncMessage("NetworkStats:ClearAll",
{id: this.getRequestId(request)}); {id: this.getRequestId(request)});
@ -198,17 +174,6 @@ NetworkStatsManager.prototype = {
}, },
addAlarm: function addAlarm(aNetwork, aThreshold, aOptions) { addAlarm: function addAlarm(aNetwork, aThreshold, aOptions) {
this.checkPrivileges();
if (!aOptions) {
aOptions = Object.create(null);
}
if (aOptions.startTime && aOptions.startTime.constructor.name !== "Date" ||
!(aNetwork instanceof this.window.MozNetworkStatsInterface)) {
throw Components.results.NS_ERROR_INVALID_ARG;
}
let request = this.createRequest(); let request = this.createRequest();
cpmm.sendAsyncMessage("NetworkStats:SetAlarm", cpmm.sendAsyncMessage("NetworkStats:SetAlarm",
{id: this.getRequestId(request), {id: this.getRequestId(request),
@ -222,13 +187,8 @@ NetworkStatsManager.prototype = {
}, },
getAllAlarms: function getAllAlarms(aNetwork) { getAllAlarms: function getAllAlarms(aNetwork) {
this.checkPrivileges();
let network = null; let network = null;
if (aNetwork) { if (aNetwork) {
if (!aNetwork instanceof this.window.MozNetworkStatsInterface) {
throw Components.results.NS_ERROR_INVALID_ARG;
}
network = aNetwork.toJSON(); network = aNetwork.toJSON();
} }
@ -241,8 +201,6 @@ NetworkStatsManager.prototype = {
}, },
removeAlarms: function removeAlarms(aAlarmId) { removeAlarms: function removeAlarms(aAlarmId) {
this.checkPrivileges();
if (aAlarmId == 0) { if (aAlarmId == 0) {
aAlarmId = -1; aAlarmId = -1;
} }
@ -257,8 +215,6 @@ NetworkStatsManager.prototype = {
}, },
getAvailableNetworks: function getAvailableNetworks() { getAvailableNetworks: function getAvailableNetworks() {
this.checkPrivileges();
let request = this.createRequest(); let request = this.createRequest();
cpmm.sendAsyncMessage("NetworkStats:GetAvailableNetworks", cpmm.sendAsyncMessage("NetworkStats:GetAvailableNetworks",
{ id: this.getRequestId(request) }); { id: this.getRequestId(request) });
@ -266,8 +222,6 @@ NetworkStatsManager.prototype = {
}, },
getAvailableServiceTypes: function getAvailableServiceTypes() { getAvailableServiceTypes: function getAvailableServiceTypes() {
this.checkPrivileges();
let request = this.createRequest(); let request = this.createRequest();
cpmm.sendAsyncMessage("NetworkStats:GetAvailableServiceTypes", cpmm.sendAsyncMessage("NetworkStats:GetAvailableServiceTypes",
{ id: this.getRequestId(request) }); { id: this.getRequestId(request) });
@ -275,12 +229,10 @@ NetworkStatsManager.prototype = {
}, },
get sampleRate() { get sampleRate() {
this.checkPrivileges();
return cpmm.sendSyncMessage("NetworkStats:SampleRate")[0]; return cpmm.sendSyncMessage("NetworkStats:SampleRate")[0];
}, },
get maxStorageAge() { get maxStorageAge() {
this.checkPrivileges();
return cpmm.sendSyncMessage("NetworkStats:MaxStorageAge")[0]; return cpmm.sendSyncMessage("NetworkStats:MaxStorageAge")[0];
}, },
@ -390,27 +342,7 @@ NetworkStatsManager.prototype = {
}, },
init: function(aWindow) { init: function(aWindow) {
// Set navigator.mozNetworkStats to null.
if (!Services.prefs.getBoolPref("dom.mozNetworkStats.enabled")) {
return null;
}
let principal = aWindow.document.nodePrincipal; let principal = aWindow.document.nodePrincipal;
let secMan = Services.scriptSecurityManager;
let perm = principal == secMan.getSystemPrincipal() ?
Ci.nsIPermissionManager.ALLOW_ACTION :
Services.perms.testExactPermissionFromPrincipal(principal,
"networkstats-manage");
// Only pages with perm set can use the netstats.
this.hasPrivileges = perm == Ci.nsIPermissionManager.ALLOW_ACTION;
if (DEBUG) {
debug("has privileges: " + this.hasPrivileges);
}
if (!this.hasPrivileges) {
return null;
}
this.initDOMRequestHelper(aWindow, ["NetworkStats:Get:Return", this.initDOMRequestHelper(aWindow, ["NetworkStats:Get:Return",
"NetworkStats:GetAvailableNetworks:Return", "NetworkStats:GetAvailableNetworks:Return",
@ -443,16 +375,10 @@ NetworkStatsManager.prototype = {
}, },
classID : NETWORKSTATSMANAGER_CID, classID : NETWORKSTATSMANAGER_CID,
QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStatsManager, contractID : NETWORKSTATSMANAGER_CONTRACTID,
Ci.nsIDOMGlobalPropertyInitializer, QueryInterface : XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer,
Ci.nsISupportsWeakReference, Ci.nsISupportsWeakReference,
Ci.nsIObserver]), Ci.nsIObserver]),
classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATSMANAGER_CID,
contractID: NETWORKSTATSMANAGER_CONTRACTID,
classDescription: "NetworkStatsManager",
interfaces: [nsIDOMMozNetworkStatsManager],
flags: nsIClassInfo.DOM_OBJECT})
} }
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkStatsAlarm, this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkStatsAlarm,

View File

@ -12,4 +12,3 @@ contract @mozilla.org/networkstatsalarm;1 {a93ea13e-409c-4189-9b1e-95fff220be55}
component {ceb874cd-cc1a-4e65-b404-cc2d3e42425f} NetworkStatsManager.js component {ceb874cd-cc1a-4e65-b404-cc2d3e42425f} NetworkStatsManager.js
contract @mozilla.org/networkStatsManager;1 {ceb874cd-cc1a-4e65-b404-cc2d3e42425f} contract @mozilla.org/networkStatsManager;1 {ceb874cd-cc1a-4e65-b404-cc2d3e42425f}
category JavaScript-navigator-property mozNetworkStats @mozilla.org/networkStatsManager;1

View File

@ -12,7 +12,6 @@ XPIDL_SOURCES += [
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk': if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
XPIDL_SOURCES += [ XPIDL_SOURCES += [
'nsIDOMNetworkStatsManager.idl',
'nsINetworkStatsServiceProxy.idl', 'nsINetworkStatsServiceProxy.idl',
] ]

View File

@ -48,32 +48,30 @@ var steps = [
}; };
req.onerror = function () { req.onerror = function () {
ok(req.error.name == "InvalidInterface", "Get InvalidInterface error"); is(req.error.name, "InvalidInterface", "Get InvalidInterface error");
next(); next();
} }
}, },
function () { function () {
ok(true, "Calling addAlarm() with invalid network or parameters."); ok(true, "Calling addAlarm() with invalid network or parameters.");
var msg = "TypeError: Not enough arguments to MozNetworkStatsManager.addAlarm.";
try { try {
navigator.mozNetworkStats.addAlarm(); navigator.mozNetworkStats.addAlarm();
} catch(ex) { } catch(ex) {
ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS, is(ex.toString(), msg, "addAlarm() throws \"" + msg + "\" when no parameters");
"addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no parameters");
} }
try { try {
navigator.mozNetworkStats.addAlarm(100000); navigator.mozNetworkStats.addAlarm(100000);
} catch(ex) { } catch(ex) {
ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS, is(ex.toString(), msg, "addAlarm() throws " + msg + " when no network");
"addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no network");
} }
try { try {
navigator.mozNetworkStats.addAlarm(new window.MozNetworkStatsInterface(wifi)); navigator.mozNetworkStats.addAlarm(new window.MozNetworkStatsInterface(wifi));
} catch(ex) { } catch(ex) {
ok(ex.result == SpecialPowers.Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS, is(ex.toString(), msg, "addAlarm() throws " + msg + " when no threshold");
"addAlarm() throws NS_ERROR_XPC_NOT_ENOUGH_ARGS exception when no threshold");
} }
req = navigator.mozNetworkStats req = navigator.mozNetworkStats
@ -84,7 +82,7 @@ var steps = [
}; };
req.onerror = function () { req.onerror = function () {
ok(req.error.name == "InvalidThresholdValue", "Get InvalidThresholdValue error"); is(req.error.name, "InvalidThresholdValue", "Get InvalidThresholdValue error");
next(); next();
} }
}, },
@ -109,8 +107,8 @@ var steps = [
.getAllAlarms(new window.MozNetworkStatsInterface(wifi)); .getAllAlarms(new window.MozNetworkStatsInterface(wifi));
req.onsuccess = function () { req.onsuccess = function () {
ok(req.result.length == 1, "Only one alarm"); is(req.result.length, 1, "Only one alarm");
ok(req.result[0].alarmId == 1, "Get correct alarmId"); is(req.result[0].alarmId, 1, "Get correct alarmId");
next(); next();
}; };
@ -226,8 +224,8 @@ SpecialPowers.pushPrefEnv({'set': [["dom.mozNetworkStats.enabled", true]]},
ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist"); ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist");
ok(navigator.mozNetworkStats instanceof SpecialPowers.Ci.nsIDOMMozNetworkStatsManager, ok(navigator.mozNetworkStats instanceof MozNetworkStatsManager,
"navigator.mozNetworkStats should be a nsIDOMMozNetworkStatsManager object"); "navigator.mozNetworkStats should be a MozNetworkStatsManager object");
test(); test();
}); });

View File

@ -333,8 +333,8 @@ SpecialPowers.pushPrefEnv({'set': [["dom.mozNetworkStats.enabled", true]]},
ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist"); ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist");
ok(navigator.mozNetworkStats instanceof SpecialPowers.Ci.nsIDOMMozNetworkStatsManager, ok(navigator.mozNetworkStats instanceof MozNetworkStatsManager,
"navigator.mozNetworkStats should be a nsIDOMMozNetworkStatsManager object"); "navigator.mozNetworkStats should be a MozNetworkStatsManager object");
test(); test();
}); });

View File

@ -22,10 +22,8 @@ SpecialPowers.pushPrefEnv({'set': [["dom.mozNetworkStats.enabled", false]]},
ok(!SpecialPowers.getBoolPref("dom.mozNetworkStats.enabled"), ok(!SpecialPowers.getBoolPref("dom.mozNetworkStats.enabled"),
"Preference 'dom.mozNetworkStats.enabled' is false."); "Preference 'dom.mozNetworkStats.enabled' is false.");
ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist"); ok(!('mozNetworkStats' in navigator),
"navigator.mozNetworkStats should not exist when pref not set");
is(navigator.mozNetworkStats, null,
"mozNetworkStats should be null when not enabled.");
SimpleTest.finish(); SimpleTest.finish();
}); });

View File

@ -27,23 +27,9 @@
ok(!SpecialPowers.hasPermission("networkstats-manage", document), ok(!SpecialPowers.hasPermission("networkstats-manage", document),
"Has no permission 'networkstats-manage'."); "Has no permission 'networkstats-manage'.");
ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist"); ok(!('mozNetworkStats' in navigator),
"navigator.mozNetworkStats should not exist when permission not set");
is(navigator.mozNetworkStats, null,
"mozNetworkStats should be null when no permission.");
var error;
try {
navigator.mozNetworkStats.getAvailableNetworks;
ok(false,
"Accessing navigator.mozNetworkStats.getAvailableNetworks should throw!");
} catch (ex) {
error = ex;
}
ok(error,
"Got an exception accessing navigator.mozNetworkStats.getAvailableNetworks");
SimpleTest.finish(); SimpleTest.finish();
} }
</script> </script>

View File

@ -30,8 +30,8 @@ SpecialPowers.pushPrefEnv({'set': [["dom.mozNetworkStats.enabled", true]]},
ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist"); ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist");
ok(navigator.mozNetworkStats instanceof SpecialPowers.Ci.nsIDOMMozNetworkStatsManager, ok(navigator.mozNetworkStats instanceof MozNetworkStatsManager,
"navigator.mozNetworkStats should be a nsIDOMMozNetworkStatsManager object"); "navigator.mozNetworkStats should be a MozNetworkStatsManager object");
SimpleTest.finish(); SimpleTest.finish();
}); });

View File

@ -41,8 +41,8 @@ function filterTimestamp(date) {
} }
function getNetworks() { function getNetworks() {
return [{ id: '0', type: Ci.nsIDOMMozNetworkStatsManager.WIFI }, return [{ id: '0', type: Ci.nsINetworkInterface.NETWORK_TYPE_WIFI },
{ id: '1234', type: Ci.nsIDOMMozNetworkStatsManager.MOBILE }]; { id: '1234', type: Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE }];
} }
function compareNetworks(networkA, networkB) { function compareNetworks(networkA, networkB) {

View File

@ -158,12 +158,12 @@ add_test(function test_queue() {
}; };
// Fill networks with fake network interfaces to enable netd async requests. // Fill networks with fake network interfaces to enable netd async requests.
var network = {id: "1234", type: Ci.nsIDOMMozNetworkStatsManager.MOBILE}; var network = {id: "1234", type: Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE};
var netId1 = NetworkStatsService.getNetworkId(network.id, network.type); var netId1 = NetworkStatsService.getNetworkId(network.id, network.type);
NetworkStatsService._networks[netId1] = { network: network, NetworkStatsService._networks[netId1] = { network: network,
interfaceName: "net1" }; interfaceName: "net1" };
network = {id: "5678", type: Ci.nsIDOMMozNetworkStatsManager.MOBILE}; network = {id: "5678", type: Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE};
var netId2 = NetworkStatsService.getNetworkId(network.id, network.type); var netId2 = NetworkStatsService.getNetworkId(network.id, network.type);
NetworkStatsService._networks[netId2] = { network: network, NetworkStatsService._networks[netId2] = { network: network,
interfaceName: "net2" }; interfaceName: "net2" };

View File

@ -10,9 +10,6 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/DOMRequestHelper.jsm"); Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
const PAYMENTCONTENTHELPER_CID =
Components.ID("{a920adc0-c36e-4fd0-8de0-aac1ac6ebbd0}");
const PAYMENT_IPC_MSG_NAMES = ["Payment:Success", const PAYMENT_IPC_MSG_NAMES = ["Payment:Success",
"Payment:Failed"]; "Payment:Failed"];
@ -22,39 +19,82 @@ XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
"@mozilla.org/childprocessmessagemanager;1", "@mozilla.org/childprocessmessagemanager;1",
"nsIMessageSender"); "nsIMessageSender");
function PaymentContentHelper() { var _debug;
try {
_debug = Services.prefs.getPrefType(PREF_DEBUG) == Ci.nsIPrefBranch.PREF_BOOL
&& Services.prefs.getBoolPref(PREF_DEBUG);
} catch(e) {
_debug = false;
}
function LOG(s) {
if (!_debug) {
return;
}
dump("-*- PaymentContentHelper: " + s + "\n");
}
function PaymentContentHelper(aWindow) {
this.initDOMRequestHelper(aWindow, PAYMENT_IPC_MSG_NAMES);
}; };
PaymentContentHelper.prototype = { PaymentContentHelper.prototype = {
__proto__: DOMRequestIpcHelper.prototype, __proto__: DOMRequestIpcHelper.prototype,
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavigatorPayment, receiveMessage: function receiveMessage(aMessage) {
Ci.nsIDOMGlobalPropertyInitializer, let name = aMessage.name;
Ci.nsISupportsWeakReference, let msg = aMessage.json;
Ci.nsIObserver]), if (_debug) {
classID: PAYMENTCONTENTHELPER_CID, LOG("Received message '" + name + "': " + JSON.stringify(msg));
classInfo: XPCOMUtils.generateCI({ }
classID: PAYMENTCONTENTHELPER_CID, let requestId = msg.requestId;
contractID: "@mozilla.org/payment/content-helper;1", let request = this.takeRequest(requestId);
classDescription: "Payment Content Helper", if (!request) {
flags: Ci.nsIClassInfo.DOM_OBJECT, return;
interfaces: [Ci.nsINavigatorPayment] }
}), switch (name) {
case "Payment:Success":
Services.DOMRequest.fireSuccess(request, msg.result);
break;
case "Payment:Failed":
Services.DOMRequest.fireError(request, msg.errorMsg);
break;
}
},
};
function PaymentContentHelperService() {
};
PaymentContentHelperService.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPaymentContentHelperService]),
classID: Components.ID("{80035846-6732-4fcc-961b-f336b65218f4}"),
contractID: "@mozilla.org/payment/content-helper-service;1",
_xpcom_factory: XPCOMUtils.generateSingletonFactory(PaymentContentHelperService),
// keys are windows and values are PaymentContentHelpers
helpers: new WeakMap(),
// nsINavigatorPayment // nsINavigatorPayment
pay: function pay(aWindow, aJwts) {
let requestHelper = this.helpers.get(aWindow);
if (!requestHelper) {
requestHelper = new PaymentContentHelper(aWindow);
this.helpers.set(aWindow, requestHelper);
}
let request = requestHelper.createRequest();
let requestId = requestHelper.getRequestId(request);
pay: function pay(aJwts) { let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
let request = this.createRequest();
let requestId = this.getRequestId(request);
let docShell = this._window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation) .getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell); .QueryInterface(Ci.nsIDocShell);
if (!docShell.isActive) { if (!docShell.isActive) {
if (this._debug) { if (_debug) {
this.LOG("The caller application is a background app. No request " + LOG("The caller application is a background app. No request will be " +
"will be sent"); "sent");
} }
let runnable = { let runnable = {
run: function run() { run: function run() {
Services.DOMRequest.fireError(request, "BACKGROUND_APP"); Services.DOMRequest.fireError(request, "BACKGROUND_APP");
@ -75,61 +115,6 @@ PaymentContentHelper.prototype = {
}); });
return request; return request;
}, },
// nsIDOMGlobalPropertyInitializer
init: function(aWindow) {
try {
if (!Services.prefs.getBoolPref("dom.mozPay.enabled")) {
return null;
}
} catch (e) {
return null;
}
this._window = aWindow;
this.initDOMRequestHelper(aWindow, PAYMENT_IPC_MSG_NAMES);
try {
this._debug =
Services.prefs.getPrefType(PREF_DEBUG) == Ci.nsIPrefBranch.PREF_BOOL
&& Services.prefs.getBoolPref(PREF_DEBUG);
} catch(e) {
this._debug = false;
}
return Cu.exportFunction(this.pay.bind(this), aWindow);
},
// nsIFrameMessageListener
receiveMessage: function receiveMessage(aMessage) {
let name = aMessage.name;
let msg = aMessage.json;
if (this._debug) {
this.LOG("Received message '" + name + "': " + JSON.stringify(msg));
}
let requestId = msg.requestId;
let request = this.takeRequest(requestId);
if (!request) {
return;
}
switch (name) {
case "Payment:Success":
Services.DOMRequest.fireSuccess(request, msg.result);
break;
case "Payment:Failed":
Services.DOMRequest.fireError(request, msg.errorMsg);
break;
}
},
LOG: function LOG(s) {
if (!this._debug) {
return;
}
dump("-*- PaymentContentHelper: " + s + "\n");
}
}; };
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([PaymentContentHelper]); this.NSGetFactory = XPCOMUtils.generateNSGetFactory([PaymentContentHelperService]);

View File

@ -1,6 +1,5 @@
component {a920adc0-c36e-4fd0-8de0-aac1ac6ebbd0} Payment.js component {80035846-6732-4fcc-961b-f336b65218f4} Payment.js
contract @mozilla.org/payment/content-helper;1 {a920adc0-c36e-4fd0-8de0-aac1ac6ebbd0} contract @mozilla.org/payment/content-helper-service;1 {80035846-6732-4fcc-961b-f336b65218f4}
category JavaScript-navigator-property mozPay @mozilla.org/payment/content-helper;1
component {b8bce4e7-fbf0-4719-a634-b1bf9018657c} PaymentFlowInfo.js component {b8bce4e7-fbf0-4719-a634-b1bf9018657c} PaymentFlowInfo.js
contract @mozilla.org/payment/flow-info;1 {b8bce4e7-fbf0-4719-a634-b1bf9018657c} contract @mozilla.org/payment/flow-info;1 {b8bce4e7-fbf0-4719-a634-b1bf9018657c}

View File

@ -5,7 +5,7 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
XPIDL_SOURCES += [ XPIDL_SOURCES += [
'nsINavigatorPayment.idl', 'nsIPaymentContentHelperService.idl',
'nsIPaymentFlowInfo.idl', 'nsIPaymentFlowInfo.idl',
'nsIPaymentProviderStrategy.idl', 'nsIPaymentProviderStrategy.idl',
'nsIPaymentUIGlue.idl', 'nsIPaymentUIGlue.idl',

View File

@ -5,13 +5,14 @@
#include "domstubs.idl" #include "domstubs.idl"
interface nsIDOMDOMRequest; interface nsIDOMDOMRequest;
interface mozIDOMWindow;
[scriptable, uuid(44fb7308-7d7b-4975-8a27-e01fe9623bdb)] [scriptable, uuid(80035846-6732-4fcc-961b-f336b65218f4)]
interface nsINavigatorPayment : nsISupports interface nsIPaymentContentHelperService : nsISupports
{ {
// The 'jwts' parameter can be either a single DOMString or an array of // The 'jwts' parameter can be either a single DOMString or an array of
// DOMStrings. In both cases, it represents the base64url encoded and // DOMStrings. In both cases, it represents the base64url encoded and
// digitally signed payment information. Each payment provider should // digitally signed payment information. Each payment provider should
// define its supported JWT format. // define its supported JWT format.
nsIDOMDOMRequest pay(in jsval jwts); nsIDOMDOMRequest pay(in mozIDOMWindow window, in jsval jwts);
}; };

View File

@ -0,0 +1,91 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cm = Components.manager;
const Cu = Components.utils;
const CONTRACT_ID = "@mozilla.org/payment/ui-glue;1";
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
var oldClassID, oldFactory;
var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID();
var newFactory = {
createInstance: function(aOuter, aIID) {
if (aOuter) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
return new MockPaymentsUIGlueInstance().QueryInterface(aIID);
},
lockFactory: function(aLock) {
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory])
};
addMessageListener("MockPaymentsUIGlue.init", function (message) {
try {
oldClassID = registrar.contractIDToCID(CONTRACT_ID);
oldFactory = Cm.getClassObject(oldClassID, Ci.nsIFactory);
} catch (ex) {
oldClassID = "";
oldFactory = null;
dump("TEST-INFO | can't get payments ui glue registered component, " +
"assuming there is none\n");
}
if (oldFactory) {
registrar.unregisterFactory(oldClassID, oldFactory);
}
registrar.registerFactory(newClassID, "", CONTRACT_ID, newFactory);});
addMessageListener("MockPaymentsUIGlue.cleanup", function (message) {
if (oldClassID) {
registrar.registerFactory(oldClassID, "", CONTRACT_ID, null);
}
});
var payments = new Map();
function MockPaymentsUIGlueInstance() {
};
MockPaymentsUIGlueInstance.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPaymentUIGlue]),
confirmPaymentRequest: function(aRequestId,
aRequests,
aSuccessCb,
aErrorCb) {
aSuccessCb.onresult(aRequestId, aRequests[0].type);
},
showPaymentFlow: function(aRequestId,
aPaymentFlowInfo,
aErrorCb) {
let win = Services.ww.openWindow(null,
null,
"_blank",
"chrome,dialog=no,resizable,scrollbars,centerscreen",
null);
payments.set(aRequestId, win);
let docshell = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell);
docshell.paymentRequestId = aRequestId;
win.document.location = aPaymentFlowInfo.uri + aPaymentFlowInfo.jwt;
},
closePaymentFlow: function(aRequestId) {
payments.get(aRequestId).close();
payments.delete(aRequestId);
return Promise.resolve();
},
};

View File

@ -1,12 +1,11 @@
[DEFAULT] [DEFAULT]
skip-if=true # This test uses MockPaymentsUIGlue which uses __exposedProps__ skip-if=buildapp != 'b2g' && toolkit != 'android'
# we need to move this to a chrome test, but these are not
# available in b2g or android for now.
support-files= support-files=
file_mozpayproviderchecker.html file_mozpayproviderchecker.html
file_payprovidersuccess.html file_payprovidersuccess.html
file_payproviderfailure.html file_payproviderfailure.html
MockPaymentsUIChromeScript.js
[test_mozpaymentprovider.html] [test_mozpaymentprovider.html]
[test_mozpay_callbacks.html] [test_mozpay_callbacks.html]

View File

@ -79,7 +79,11 @@ function runTest() {
tests.shift()(); tests.shift()();
} }
SpecialPowers.MockPaymentsUIGlue.init(window); const uiGlue = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('MockPaymentsUIChromeScript.js'));
SimpleTest.registerCleanupFunction(() => {
uiGlue.sendAsyncMessage("MockPaymentsUIGlue.cleanup", {});
});
uiGlue.sendAsyncMessage("MockPaymentsUIGlue.init", {});
SpecialPowers.pushPrefEnv({ SpecialPowers.pushPrefEnv({
"set": [ "set": [
@ -88,13 +92,13 @@ SpecialPowers.pushPrefEnv({
["dom.payment.provider.1.name", "SuccessProvider"], ["dom.payment.provider.1.name", "SuccessProvider"],
["dom.payment.provider.1.description", ""], ["dom.payment.provider.1.description", ""],
["dom.payment.provider.1.uri", ["dom.payment.provider.1.uri",
"http://mochi.test:8888/tests/dom/payment/tests/mochitest/file_payprovidersuccess.html?req="], "https://example.com:443/tests/dom/payment/tests/mochitest/file_payprovidersuccess.html?req="],
["dom.payment.provider.1.type", "mozilla/payments/test/success"], ["dom.payment.provider.1.type", "mozilla/payments/test/success"],
["dom.payment.provider.1.requestMethod", "GET"], ["dom.payment.provider.1.requestMethod", "GET"],
["dom.payment.provider.2.name", "FailureProvider"], ["dom.payment.provider.2.name", "FailureProvider"],
["dom.payment.provider.2.description", ""], ["dom.payment.provider.2.description", ""],
["dom.payment.provider.2.uri", ["dom.payment.provider.2.uri",
"http://mochi.test:8888/tests/dom/payment/tests/mochitest/file_payproviderfailure.html?req="], "https://example.com:443/tests/dom/payment/tests/mochitest/file_payproviderfailure.html?req="],
["dom.payment.provider.2.type", "mozilla/payments/test/failure"], ["dom.payment.provider.2.type", "mozilla/payments/test/failure"],
["dom.payment.provider.2.requestMethod", "GET"], ["dom.payment.provider.2.requestMethod", "GET"],
] ]

View File

@ -20,7 +20,7 @@ var gData = [
{ {
perm: ["networkstats-manage"], perm: ["networkstats-manage"],
obj: "mozNetworkStats", obj: "mozNetworkStats",
idl: "nsIDOMMozNetworkStatsManager", webidl: "MozNetworkStatsManager",
settings: [["dom.mozNetworkStats.enabled", true]], settings: [["dom.mozNetworkStats.enabled", true]],
}, },
] ]

View File

@ -2,7 +2,7 @@ load 41276-1.html
load 48856-1.html load 48856-1.html
load 110650-1.html load 110650-1.html
skip-if(!haveTestPlugin) script 539897-1.html skip-if(!haveTestPlugin) script 539897-1.html
skip-if(!haveTestPlugin) script 540114-1.html asserts(0-1) skip-if(!haveTestPlugin) script 540114-1.html
load 570884.html load 570884.html
# This test relies on the reading of screenX/Y forcing a round trip to # This test relies on the reading of screenX/Y forcing a round trip to
# the X server, which is a bad assumption for <browser remote>. # the X server, which is a bad assumption for <browser remote>.

View File

@ -6,6 +6,8 @@
#include "mozilla/dom/SVGFEConvolveMatrixElement.h" #include "mozilla/dom/SVGFEConvolveMatrixElement.h"
#include "mozilla/dom/SVGFEConvolveMatrixElementBinding.h" #include "mozilla/dom/SVGFEConvolveMatrixElementBinding.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/UniquePtrExtensions.h"
#include "DOMSVGAnimatedNumberList.h" #include "DOMSVGAnimatedNumberList.h"
#include "nsSVGUtils.h" #include "nsSVGUtils.h"
#include "nsSVGFilterInstance.h" #include "nsSVGFilterInstance.h"
@ -203,7 +205,7 @@ SVGFEConvolveMatrixElement::GetPrimitiveDescription(nsSVGFilterInstance* aInstan
if (orderX > NS_SVG_OFFSCREEN_MAX_DIMENSION || if (orderX > NS_SVG_OFFSCREEN_MAX_DIMENSION ||
orderY > NS_SVG_OFFSCREEN_MAX_DIMENSION) orderY > NS_SVG_OFFSCREEN_MAX_DIMENSION)
return failureDescription; return failureDescription;
nsAutoArrayPtr<float> kernel(new (fallible) float[orderX * orderY]); UniquePtr<float[]> kernel = MakeUniqueFallible<float[]>(orderX * orderY);
if (!kernel) if (!kernel)
return failureDescription; return failureDescription;
for (uint32_t i = 0; i < kmLength; i++) { for (uint32_t i = 0; i < kmLength; i++) {

View File

@ -7,6 +7,7 @@
#include "TelephonyChild.h" #include "TelephonyChild.h"
#include "mozilla/dom/telephony/TelephonyDialCallback.h" #include "mozilla/dom/telephony/TelephonyDialCallback.h"
#include "mozilla/UniquePtr.h"
#include "TelephonyIPCService.h" #include "TelephonyIPCService.h"
USING_TELEPHONY_NAMESPACE USING_TELEPHONY_NAMESPACE
@ -212,12 +213,13 @@ TelephonyRequestChild::DoResponse(const DialResponseMMISuccess& aResponse)
uint32_t count = info.get_ArrayOfnsString().Length(); uint32_t count = info.get_ArrayOfnsString().Length();
const nsTArray<nsString>& additionalInformation = info.get_ArrayOfnsString(); const nsTArray<nsString>& additionalInformation = info.get_ArrayOfnsString();
nsAutoArrayPtr<const char16_t*> additionalInfoPtrs(new const char16_t*[count]); auto additionalInfoPtrs = MakeUnique<const char16_t*[]>(count);
for (size_t i = 0; i < count; ++i) { for (size_t i = 0; i < count; ++i) {
additionalInfoPtrs[i] = additionalInformation[i].get(); additionalInfoPtrs[i] = additionalInformation[i].get();
} }
callback->NotifyDialMMISuccessWithStrings(statusMessage, count, additionalInfoPtrs); callback->NotifyDialMMISuccessWithStrings(statusMessage, count,
additionalInfoPtrs.get());
break; break;
} }
case AdditionalInformation::TArrayOfnsMobileCallForwardingOptions: { case AdditionalInformation::TArrayOfnsMobileCallForwardingOptions: {

View File

@ -37,9 +37,11 @@ support-files =
[test_bug830396.xul] [test_bug830396.xul]
[test_bug830858.xul] [test_bug830858.xul]
[test_bug1224790-1.xul] [test_bug1224790-1.xul]
skip-if = os != 'cocoa' # synthesizeNativeOSXClick does not work on 10.6
skip-if = os != 'mac' || os_version == '10.6'
[test_bug1224790-2.xul] [test_bug1224790-2.xul]
skip-if = os != 'cocoa' # synthesizeNativeOSXClick does not work on 10.6
skip-if = os != 'mac' || os_version == '10.6'
[test_callback_wrapping.xul] [test_callback_wrapping.xul]
[test_clonewrapper.xul] [test_clonewrapper.xul]
[test_cyclecollector.xul] [test_cyclecollector.xul]

View File

@ -308,4 +308,19 @@ test(function() {
var m = new WebKitCSSMatrix("matrix(1,0,0,0,0,0)"); var m = new WebKitCSSMatrix("matrix(1,0,0,0,0,0)");
assert_throws("NotSupportedError", function() { m.inverse(); }, "Inverting an invertible matrix should throw.") assert_throws("NotSupportedError", function() { m.inverse(); }, "Inverting an invertible matrix should throw.")
}, "Test that inverting an invertible matrix throws."); }, "Test that inverting an invertible matrix throws.");
test(function() {
var m1 = new WebKitCSSMatrix("translate(10px, 10px)");
var m2 = new DOMMatrix();
m2.translateSelf(10, 10);
assert_true(RoughCompareMatrix(m1, m2), "translate in constructor should result in translated matrix");
assert_throws("SyntaxError", function() { new WebKitCSSMatrix("translate(10em, 10em)"); }, "Transform function may not contain relative units.")
assert_throws("SyntaxError", function() { new WebKitCSSMatrix("translate(10%, 10%)"); }, "Transform function may not contain percentage.")
}, "Test constructor with translate");
test(function() {
assert_throws("SyntaxError", function() { new WebKitCSSMatrix("initial"); }, "initial is not a valid constructor argument.")
assert_throws("SyntaxError", function() { new WebKitCSSMatrix("inherit"); }, "inherit is not a valid constructor arugment.")
}, "Test invalid constructor arguments.");
</script> </script>

View File

@ -278,7 +278,7 @@ partial interface Document {
// http://dev.w3.org/csswg/cssom-view/#extensions-to-the-document-interface // http://dev.w3.org/csswg/cssom-view/#extensions-to-the-document-interface
partial interface Document { partial interface Document {
Element? elementFromPoint (float x, float y); Element? elementFromPoint (float x, float y);
sequence<Element> elementsFromPoint (float x, float y);
CaretPosition? caretPositionFromPoint (float x, float y); CaretPosition? caretPositionFromPoint (float x, float y);
[Pref="dom.document.scrollingElement.enabled"] [Pref="dom.document.scrollingElement.enabled"]

View File

@ -14,15 +14,15 @@ dictionary NetworkStatsGetOptions
* Note that, these two options cannot be specified at the same time for now; * Note that, these two options cannot be specified at the same time for now;
* others, an NS_ERROR_NOT_IMPLMENTED exception will be thrown. * others, an NS_ERROR_NOT_IMPLMENTED exception will be thrown.
*/ */
DOMString appManifestURL; DOMString? appManifestURL = null;
DOMString serviceType; DOMString serviceType = "";
/** /**
* If it is set as true, only the browsing traffic, which is generated from * If it is set as true, only the browsing traffic, which is generated from
* the mozbrowser iframe element within an app, is returned in result. * the mozbrowser iframe element within an app, is returned in result.
* If it is set as false or not set, the total traffic, which is generated * If it is set as false or not set, the total traffic, which is generated
* from both the mozapp and mozbrowser iframe elements, is returned. * from both the mozapp and mozbrowser iframe elements, is returned.
*/ */
boolean browsingTrafficOnly; boolean browsingTrafficOnly = false;
}; };
dictionary NetworkStatsAlarmOptions dictionary NetworkStatsAlarmOptions

View File

@ -1,14 +1,14 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file, * License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */ * You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "nsISupports.idl" [NavigatorProperty="mozNetworkStats",
JSImplementation="@mozilla.org/networkStatsManager;1",
interface nsIDOMDOMRequest; CheckAnyPermissions="networkstats-manage",
Pref="dom.mozNetworkStats.enabled"]
[scriptable, uuid(72c4e583-389d-4d1b-9424-702feabb6055)] interface MozNetworkStatsManager {
interface nsIDOMMozNetworkStatsManager : nsISupports
{
/** /**
* Constants for known interface types. * Constants for known interface types.
*/ */
@ -21,12 +21,12 @@ interface nsIDOMMozNetworkStatsManager : nsISupports
* If options is provided, per-app or per-system service usage will be * If options is provided, per-app or per-system service usage will be
* retrieved; otherwise the target will be overall system usage. * retrieved; otherwise the target will be overall system usage.
* *
* If success, the request result will be an nsIDOMMozNetworkStats object. * If success, the request result will be an MozNetworkStats object.
*/ */
nsIDOMDOMRequest getSamples(in nsISupports network, DOMRequest getSamples(MozNetworkStatsInterface network,
in jsval start, Date start,
in jsval end, Date end,
[optional] in jsval options /* NetworkStatsGetOptions */); optional NetworkStatsGetOptions options);
/** /**
* Install an alarm on a network. The network must be in the return of * Install an alarm on a network. The network must be in the return of
@ -39,9 +39,9 @@ interface nsIDOMMozNetworkStatsManager : nsISupports
* *
* If success, the |result| field of the DOMRequest keeps the alarm Id. * If success, the |result| field of the DOMRequest keeps the alarm Id.
*/ */
nsIDOMDOMRequest addAlarm(in nsISupports network, DOMRequest addAlarm(MozNetworkStatsInterface network,
in long long threshold, long long threshold,
[optional] in jsval options /* NetworkStatsAlarmOptions */); optional NetworkStatsAlarmOptions options);
/** /**
* Obtain all alarms for those networks returned by getAvailableNetworks(). * Obtain all alarms for those networks returned by getAvailableNetworks().
@ -55,33 +55,33 @@ interface nsIDOMMozNetworkStatsManager : nsISupports
* - threshold * - threshold
* - data * - data
*/ */
nsIDOMDOMRequest getAllAlarms([optional] in nsISupports network); DOMRequest getAllAlarms(optional MozNetworkStatsInterface network);
/** /**
* Remove all network alarms. If an |alarmId| is provided, then only that * Remove all network alarms. If an |alarmId| is provided, then only that
* alarm is removed. * alarm is removed.
*/ */
nsIDOMDOMRequest removeAlarms([optional] in long alarmId); DOMRequest removeAlarms(optional unsigned long alarmId = 0);
/** /**
* Remove all stats related with the provided network from DB. * Remove all stats related with the provided network from DB.
*/ */
nsIDOMDOMRequest clearStats(in nsISupports network); DOMRequest clearStats(MozNetworkStatsInterface network);
/** /**
* Remove all stats in the database. * Remove all stats in the database.
*/ */
nsIDOMDOMRequest clearAllStats(); DOMRequest clearAllStats();
/** /**
* Return available networks that used to be saved in the database. * Return available networks that used to be saved in the database.
*/ */
nsIDOMDOMRequest getAvailableNetworks(); // array of MozNetworkStatsInterface. DOMRequest getAvailableNetworks(); // array of MozNetworkStatsInterface.
/** /**
* Return available service types that used to be saved in the database. * Return available service types that used to be saved in the database.
*/ */
nsIDOMDOMRequest getAvailableServiceTypes(); // array of string. DOMRequest getAvailableServiceTypes(); // array of string.
/** /**
* Minimum time in milliseconds between samples stored in the database. * Minimum time in milliseconds between samples stored in the database.

View File

@ -465,3 +465,14 @@ partial interface Navigator {
readonly attribute boolean mozE10sEnabled; readonly attribute boolean mozE10sEnabled;
}; };
#endif #endif
#ifdef MOZ_PAY
partial interface Navigator {
[Throws, NewObject, Pref="dom.mozPay.enabled"]
// The 'jwts' parameter can be either a single DOMString or an array of
// DOMStrings. In both cases, it represents the base64url encoded and
// digitally signed payment information. Each payment provider should
// define its supported JWT format.
DOMRequest mozPay(any jwts);
};
#endif

View File

@ -17,9 +17,6 @@ typedef sequence <PerformanceEntry> PerformanceEntryList;
interface Performance { interface Performance {
[DependsOn=DeviceState, Affects=Nothing] [DependsOn=DeviceState, Affects=Nothing]
DOMHighResTimeStamp now(); DOMHighResTimeStamp now();
[Throws]
DOMHighResTimeStamp translateTime(DOMHighResTimeStamp time, (Window or Worker or SharedWorker or ServiceWorker) timeSource);
}; };
[Exposed=Window] [Exposed=Window]

View File

@ -750,6 +750,7 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
'MozNetworkStatsAlarm.webidl', 'MozNetworkStatsAlarm.webidl',
'MozNetworkStatsData.webidl', 'MozNetworkStatsData.webidl',
'MozNetworkStatsInterface.webidl', 'MozNetworkStatsInterface.webidl',
'MozNetworkStatsManager.webidl',
'MozSpeakerManager.webidl', 'MozSpeakerManager.webidl',
'MozWifiCapabilities.webidl', 'MozWifiCapabilities.webidl',
'MozWifiManager.webidl', 'MozWifiManager.webidl',

View File

@ -32,7 +32,7 @@ DOMHighResTimeStamp
Performance::Now() const Performance::Now() const
{ {
TimeDuration duration = TimeDuration duration =
TimeStamp::Now() - mWorkerPrivate->CreationTimeStamp(); TimeStamp::Now() - mWorkerPrivate->NowBaseTimeStamp();
return RoundTime(duration.ToMilliseconds()); return RoundTime(duration.ToMilliseconds());
} }
@ -52,7 +52,7 @@ Performance::GetPerformanceTimingFromString(const nsAString& aProperty)
} }
if (aProperty.EqualsLiteral("navigationStart")) { if (aProperty.EqualsLiteral("navigationStart")) {
return mWorkerPrivate->CreationTime(); return mWorkerPrivate->NowBaseTime();
} }
MOZ_CRASH("IsPerformanceTimingAttribute and GetPerformanceTimingFromString are out of sync"); MOZ_CRASH("IsPerformanceTimingAttribute and GetPerformanceTimingFromString are out of sync");
@ -77,13 +77,13 @@ Performance::InsertUserEntry(PerformanceEntry* aEntry)
TimeStamp TimeStamp
Performance::CreationTimeStamp() const Performance::CreationTimeStamp() const
{ {
return mWorkerPrivate->CreationTimeStamp(); return mWorkerPrivate->NowBaseTimeStamp();
} }
DOMHighResTimeStamp DOMHighResTimeStamp
Performance::CreationTime() const Performance::CreationTime() const
{ {
return mWorkerPrivate->CreationTime(); return mWorkerPrivate->NowBaseTime();
} }
void void

View File

@ -101,13 +101,6 @@ ServiceWorker::PostMessage(JSContext* aCx, JS::Handle<JS::Value> aMessage,
aRv = workerPrivate->SendMessageEvent(aCx, aMessage, aTransferable, Move(clientInfo)); aRv = workerPrivate->SendMessageEvent(aCx, aMessage, aTransferable, Move(clientInfo));
} }
WorkerPrivate*
ServiceWorker::GetWorkerPrivate() const
{
ServiceWorkerPrivate* workerPrivate = mInfo->WorkerPrivate();
return workerPrivate->GetWorkerPrivate();
}
} // namespace workers } // namespace workers
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla

View File

@ -67,9 +67,6 @@ public:
const Optional<Sequence<JS::Value>>& aTransferable, const Optional<Sequence<JS::Value>>& aTransferable,
ErrorResult& aRv); ErrorResult& aRv);
WorkerPrivate*
GetWorkerPrivate() const;
private: private:
// This class can only be created from the ServiceWorkerManager. // This class can only be created from the ServiceWorkerManager.
ServiceWorker(nsPIDOMWindowInner* aWindow, ServiceWorkerInfo* aInfo); ServiceWorker(nsPIDOMWindowInner* aWindow, ServiceWorkerInfo* aInfo);

View File

@ -126,12 +126,6 @@ public:
void void
NoteStoppedControllingDocuments(); NoteStoppedControllingDocuments();
WorkerPrivate*
GetWorkerPrivate() const
{
return mWorkerPrivate;
}
void void
Activated(); Activated();

View File

@ -2223,11 +2223,25 @@ WorkerPrivateParent<Derived>::WorkerPrivateParent(
aParent->CopyJSSettings(mJSSettings); aParent->CopyJSSettings(mJSSettings);
MOZ_ASSERT(IsDedicatedWorker()); MOZ_ASSERT(IsDedicatedWorker());
mNowBaseTimeStamp = aParent->NowBaseTimeStamp();
mNowBaseTimeHighRes = aParent->NowBaseTime();
} }
else { else {
AssertIsOnMainThread(); AssertIsOnMainThread();
RuntimeService::GetDefaultJSSettings(mJSSettings); RuntimeService::GetDefaultJSSettings(mJSSettings);
if (IsDedicatedWorker() && mLoadInfo.mWindow &&
mLoadInfo.mWindow->GetPerformance()) {
mNowBaseTimeStamp = mLoadInfo.mWindow->GetPerformance()->GetDOMTiming()->
GetNavigationStartTimeStamp();
mNowBaseTimeHighRes =
mLoadInfo.mWindow->GetPerformance()->GetDOMTiming()->
GetNavigationStartHighRes();
} else {
mNowBaseTimeStamp = CreationTimeStamp();
mNowBaseTimeHighRes = CreationTime();
}
} }
} }

View File

@ -192,6 +192,8 @@ private:
WorkerType mWorkerType; WorkerType mWorkerType;
TimeStamp mCreationTimeStamp; TimeStamp mCreationTimeStamp;
DOMHighResTimeStamp mCreationTimeHighRes; DOMHighResTimeStamp mCreationTimeHighRes;
TimeStamp mNowBaseTimeStamp;
DOMHighResTimeStamp mNowBaseTimeHighRes;
protected: protected:
// The worker is owned by its thread, which is represented here. This is set // The worker is owned by its thread, which is represented here. This is set
@ -553,6 +555,16 @@ public:
return mCreationTimeHighRes; return mCreationTimeHighRes;
} }
TimeStamp NowBaseTimeStamp() const
{
return mNowBaseTimeStamp;
}
DOMHighResTimeStamp NowBaseTime() const
{
return mNowBaseTimeHighRes;
}
nsIPrincipal* nsIPrincipal*
GetPrincipal() const GetPrincipal() const
{ {

View File

@ -437,8 +437,12 @@ DedicatedWorkerGlobalScope::WrapGlobalObject(JSContext* aCx,
behaviors.setDiscardSource(discardSource) behaviors.setDiscardSource(discardSource)
.extraWarningsOverride().set(extraWarnings); .extraWarningsOverride().set(extraWarnings);
const bool inCertifiedApp = mWorkerPrivate->IsInCertifiedApp();
const bool sharedMemoryEnabled = xpc::SharedMemoryEnabled();
JS::CompartmentCreationOptions& creationOptions = options.creationOptions(); JS::CompartmentCreationOptions& creationOptions = options.creationOptions();
creationOptions.setSharedMemoryAndAtomicsEnabled(xpc::SharedMemoryEnabled()); creationOptions.setSharedMemoryAndAtomicsEnabled(sharedMemoryEnabled)
.setExperimentalDateTimeFormatFormatToPartsEnabled(inCertifiedApp);
return DedicatedWorkerGlobalScopeBinding_workers::Wrap(aCx, this, this, return DedicatedWorkerGlobalScopeBinding_workers::Wrap(aCx, this, this,
options, options,

View File

@ -17,8 +17,11 @@
#include "xptcall.h" #include "xptcall.h"
#include "txXPathObjectAdaptor.h" #include "txXPathObjectAdaptor.h"
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/UniquePtr.h"
#include "nsContentUtils.h"
#include "nsIClassInfo.h" #include "nsIClassInfo.h"
#include "nsIInterfaceInfo.h" #include "nsIInterfaceInfo.h"
#include "js/RootingAPI.h"
NS_IMPL_ISUPPORTS(txXPathObjectAdaptor, txIXPathObject) NS_IMPL_ISUPPORTS(txXPathObjectAdaptor, txIXPathObject)
@ -295,23 +298,38 @@ txXPCOMExtensionFunctionCall::GetParamType(const nsXPTParamInfo &aParam,
} }
} }
class txParamArrayHolder class txParamArrayHolder : public JS::Traceable
{ {
public: public:
txParamArrayHolder() txParamArrayHolder()
: mCount(0) : mCount(0)
{ {
} }
txParamArrayHolder(txParamArrayHolder&& rhs)
: mArray(mozilla::Move(rhs.mArray))
, mCount(rhs.mCount)
{
rhs.mCount = 0;
}
~txParamArrayHolder(); ~txParamArrayHolder();
bool Init(uint8_t aCount); bool Init(uint8_t aCount);
operator nsXPTCVariant*() const operator nsXPTCVariant*() const
{ {
return mArray; return mArray.get();
}
static void trace(txParamArrayHolder* holder, JSTracer* trc) { holder->trace(trc); }
void trace(JSTracer* trc) {
for (uint8_t i = 0; i < mCount; ++i) {
if (mArray[i].type == nsXPTType::T_JSVAL) {
JS::UnsafeTraceRoot(trc, &mArray[i].val.j, "txParam value");
}
}
} }
private: private:
nsAutoArrayPtr<nsXPTCVariant> mArray; mozilla::UniquePtr<nsXPTCVariant[]> mArray;
uint8_t mCount; uint8_t mCount;
}; };
@ -338,8 +356,12 @@ bool
txParamArrayHolder::Init(uint8_t aCount) txParamArrayHolder::Init(uint8_t aCount)
{ {
mCount = aCount; mCount = aCount;
mArray = new nsXPTCVariant[mCount]; mArray = mozilla::MakeUnique<nsXPTCVariant[]>(mCount);
memset(mArray, 0, mCount * sizeof(nsXPTCVariant)); if (!mArray) {
return false;
}
memset(mArray.get(), 0, mCount * sizeof(nsXPTCVariant));
return true; return true;
} }
@ -363,8 +385,8 @@ txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
uint8_t paramCount = methodInfo->GetParamCount(); uint8_t paramCount = methodInfo->GetParamCount();
uint8_t inArgs = paramCount - 1; uint8_t inArgs = paramCount - 1;
txParamArrayHolder invokeParams; JS::Rooted<txParamArrayHolder> invokeParams(nsContentUtils::RootingCxForThread());
if (!invokeParams.Init(paramCount)) { if (!invokeParams.get().Init(paramCount)) {
return NS_ERROR_OUT_OF_MEMORY; return NS_ERROR_OUT_OF_MEMORY;
} }
@ -385,7 +407,7 @@ txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
// Create context wrapper. // Create context wrapper.
context = new txFunctionEvaluationContext(aContext, mState); context = new txFunctionEvaluationContext(aContext, mState);
nsXPTCVariant &invokeParam = invokeParams[0]; nsXPTCVariant &invokeParam = invokeParams.get()[0];
invokeParam.type = paramInfo.GetType(); invokeParam.type = paramInfo.GetType();
invokeParam.SetValNeedsCleanup(); invokeParam.SetValNeedsCleanup();
NS_ADDREF((txIFunctionEvaluationContext*&)invokeParam.val.p = context); NS_ADDREF((txIFunctionEvaluationContext*&)invokeParam.val.p = context);
@ -412,7 +434,7 @@ txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
} }
nsXPTCVariant &invokeParam = invokeParams[i]; nsXPTCVariant &invokeParam = invokeParams.get()[i];
if (paramInfo.IsOut()) { if (paramInfo.IsOut()) {
// We don't support out values. // We don't support out values.
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
@ -500,7 +522,7 @@ txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
} }
nsXPTCVariant &returnParam = invokeParams[inArgs]; nsXPTCVariant &returnParam = invokeParams.get()[inArgs];
returnParam.type = returnInfo.GetType(); returnParam.type = returnInfo.GetType();
if (returnType == eSTRING) { if (returnType == eSTRING) {
nsString *value = new nsString(); nsString *value = new nsString();
@ -514,7 +536,7 @@ txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
} }
} }
rv = NS_InvokeByIndex(mHelper, mMethodIndex, paramCount, invokeParams); rv = NS_InvokeByIndex(mHelper, mMethodIndex, paramCount, invokeParams.get());
// In case someone is holding on to the txFunctionEvaluationContext which // In case someone is holding on to the txFunctionEvaluationContext which
// could thus stay alive longer than this function. // could thus stay alive longer than this function.

View File

@ -39,6 +39,7 @@
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/dom/Element.h" #include "mozilla/dom/Element.h"
#include "mozilla/dom/EncodingUtils.h" #include "mozilla/dom/EncodingUtils.h"
#include "mozilla/UniquePtr.h"
using namespace mozilla; using namespace mozilla;
using mozilla::dom::EncodingUtils; using mozilla::dom::EncodingUtils;
@ -523,9 +524,9 @@ handleNode(nsINode* aNode, txStylesheetCompiler* aCompiler)
dom::Element* element = aNode->AsElement(); dom::Element* element = aNode->AsElement();
uint32_t attsCount = element->GetAttrCount(); uint32_t attsCount = element->GetAttrCount();
nsAutoArrayPtr<txStylesheetAttr> atts; UniquePtr<txStylesheetAttr[]> atts;
if (attsCount > 0) { if (attsCount > 0) {
atts = new txStylesheetAttr[attsCount]; atts = MakeUnique<txStylesheetAttr[]>(attsCount);
uint32_t counter; uint32_t counter;
for (counter = 0; counter < attsCount; ++counter) { for (counter = 0; counter < attsCount; ++counter) {
txStylesheetAttr& att = atts[counter]; txStylesheetAttr& att = atts[counter];
@ -541,7 +542,7 @@ handleNode(nsINode* aNode, txStylesheetCompiler* aCompiler)
rv = aCompiler->startElement(ni->NamespaceID(), rv = aCompiler->startElement(ni->NamespaceID(),
ni->NameAtom(), ni->NameAtom(),
ni->GetPrefixAtom(), atts, ni->GetPrefixAtom(), atts.get(),
attsCount); attsCount);
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);

View File

@ -5,6 +5,7 @@
#include "mozilla/ArrayUtils.h" #include "mozilla/ArrayUtils.h"
#include "mozilla/Move.h" #include "mozilla/Move.h"
#include "mozilla/UniquePtr.h"
#include "txStylesheetCompiler.h" #include "txStylesheetCompiler.h"
#include "txStylesheetCompileHandlers.h" #include "txStylesheetCompileHandlers.h"
@ -124,9 +125,9 @@ txStylesheetCompiler::startElement(const char16_t *aName,
nsresult rv = flushCharacters(); nsresult rv = flushCharacters();
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);
nsAutoArrayPtr<txStylesheetAttr> atts; UniquePtr<txStylesheetAttr[]> atts;
if (aAttrCount > 0) { if (aAttrCount > 0) {
atts = new txStylesheetAttr[aAttrCount]; atts = MakeUnique<txStylesheetAttr[]>(aAttrCount);
} }
bool hasOwnNamespaceMap = false; bool hasOwnNamespaceMap = false;
@ -169,7 +170,7 @@ txStylesheetCompiler::startElement(const char16_t *aName,
getter_AddRefs(localname), &namespaceID); getter_AddRefs(localname), &namespaceID);
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);
return startElementInternal(namespaceID, localname, prefix, atts, return startElementInternal(namespaceID, localname, prefix, atts.get(),
aAttrCount); aAttrCount);
} }

View File

@ -1773,14 +1773,6 @@ nsPermissionManager::AddInternal(nsIPrincipal* aPrincipal,
// If requested, create the entry in the DB. // If requested, create the entry in the DB.
if (aDBOperation == eWriteToDB) { if (aDBOperation == eWriteToDB) {
uint32_t appId;
rv = aPrincipal->GetAppId(&appId);
NS_ENSURE_SUCCESS(rv, rv);
bool isInBrowserElement;
rv = aPrincipal->GetIsInBrowserElement(&isInBrowserElement);
NS_ENSURE_SUCCESS(rv, rv);
UpdateDB(eOperationAdding, mStmtInsert, id, origin, aType, aPermission, UpdateDB(eOperationAdding, mStmtInsert, id, origin, aType, aPermission,
aExpireType, aExpireTime, aModificationTime); aExpireType, aExpireTime, aModificationTime);
} }
@ -2948,4 +2940,3 @@ nsPermissionManager::FetchPermissions() {
} }
return NS_OK; return NS_OK;
} }

View File

@ -184,7 +184,7 @@ struct RectTyped :
{ {
*aOut = IntRectTyped<units>(int32_t(this->X()), int32_t(this->Y()), *aOut = IntRectTyped<units>(int32_t(this->X()), int32_t(this->Y()),
int32_t(this->Width()), int32_t(this->Height())); int32_t(this->Width()), int32_t(this->Height()));
return RectTyped<units>(F(aOut->x), F(aOut->y), return RectTyped<units, F>(F(aOut->x), F(aOut->y),
F(aOut->width), F(aOut->height)) F(aOut->width), F(aOut->height))
.IsEqualEdges(*this); .IsEqualEdges(*this);
} }

View File

@ -140,6 +140,15 @@ SharedSurface_EGLImage::ProducerReleaseImpl()
mGL->fFinish(); mGL->fFinish();
} }
void
SharedSurface_EGLImage::ProducerReadAcquireImpl()
{
// Wait on the fence, because presumably we're going to want to read this surface
if (mSync) {
mEGL->fClientWaitSync(Display(), mSync, 0, LOCAL_EGL_FOREVER);
}
}
EGLDisplay EGLDisplay
SharedSurface_EGLImage::Display() const SharedSurface_EGLImage::Display() const
{ {

View File

@ -71,6 +71,9 @@ public:
virtual void ProducerAcquireImpl() override {} virtual void ProducerAcquireImpl() override {}
virtual void ProducerReleaseImpl() override; virtual void ProducerReleaseImpl() override;
virtual void ProducerReadAcquireImpl() override;
virtual void ProducerReadReleaseImpl() override {};
virtual GLuint ProdTexture() override { virtual GLuint ProdTexture() override {
return mProdTex; return mProdTex;
} }

View File

@ -357,23 +357,44 @@ DecomposeIntoNoRepeatRects(const gfx::Rect& aRect,
gfx::IntRect gfx::IntRect
Compositor::ComputeBackdropCopyRect(const gfx::Rect& aRect, Compositor::ComputeBackdropCopyRect(const gfx::Rect& aRect,
const gfx::Rect& aClipRect, const gfx::Rect& aClipRect,
const gfx::Matrix4x4& aTransform) const gfx::Matrix4x4& aTransform,
gfx::Matrix4x4* aOutTransform,
gfx::Rect* aOutLayerQuad)
{ {
gfx::Rect renderBounds = mRenderBounds;
// Compute the clip. // Compute the clip.
gfx::IntPoint offset = GetCurrentRenderTarget()->GetOrigin(); gfx::IntPoint rtOffset = GetCurrentRenderTarget()->GetOrigin();
gfx::IntSize rtSize = GetCurrentRenderTarget()->GetSize();
gfx::Rect renderBounds(0, 0, rtSize.width, rtSize.height);
renderBounds.IntersectRect(renderBounds, aClipRect); renderBounds.IntersectRect(renderBounds, aClipRect);
renderBounds.MoveBy(offset); renderBounds.MoveBy(rtOffset);
// Apply the layer transform. // Apply the layer transform.
gfx::Rect dest = aTransform.TransformAndClipBounds(aRect, renderBounds); gfx::RectDouble dest = aTransform.TransformAndClipBounds(
dest -= offset; gfx::RectDouble(aRect.x, aRect.y, aRect.width, aRect.height),
gfx::RectDouble(renderBounds.x, renderBounds.y, renderBounds.width, renderBounds.height));
dest -= rtOffset;
// Ensure we don't round out to -1, which trips up Direct3D.
dest.IntersectRect(dest, gfx::RectDouble(0, 0, rtSize.width, rtSize.height));
if (aOutLayerQuad) {
*aOutLayerQuad = gfx::Rect(dest.x, dest.y, dest.width, dest.height);
}
// Round out to integer. // Round out to integer.
gfx::IntRect result; gfx::IntRect result;
dest.RoundOut(); dest.RoundOut();
dest.ToIntRect(&result); dest.ToIntRect(&result);
// Create a transform from adjusted clip space to render target space,
// translate it for the backdrop rect, then transform it into the backdrop's
// uv-space.
gfx::Matrix4x4 transform;
transform.PostScale(rtSize.width, rtSize.height, 1.0);
transform.PostTranslate(-result.x, -result.y, 0.0);
transform.PostScale(1 / float(result.width), 1 / float(result.height), 1.0);
*aOutTransform = transform;
return result; return result;
} }

View File

@ -518,11 +518,16 @@ protected:
* Given a layer rect, clip, and transform, compute the area of the backdrop that * Given a layer rect, clip, and transform, compute the area of the backdrop that
* needs to be copied for mix-blending. The output transform translates from 0..1 * needs to be copied for mix-blending. The output transform translates from 0..1
* space into the backdrop rect space. * space into the backdrop rect space.
*
* The transformed layer quad is also optionally returned - this is the same as
* the result rect, before rounding.
*/ */
gfx::IntRect ComputeBackdropCopyRect( gfx::IntRect ComputeBackdropCopyRect(
const gfx::Rect& aRect, const gfx::Rect& aRect,
const gfx::Rect& aClipRect, const gfx::Rect& aClipRect,
const gfx::Matrix4x4& aTransform); const gfx::Matrix4x4& aTransform,
gfx::Matrix4x4* aOutTransform,
gfx::Rect* aOutLayerQuad = nullptr);
/** /**
* Render time for the current composition. * Render time for the current composition.
@ -552,8 +557,6 @@ protected:
RefPtr<gfx::DrawTarget> mTarget; RefPtr<gfx::DrawTarget> mTarget;
gfx::IntRect mTargetBounds; gfx::IntRect mTargetBounds;
gfx::Rect mRenderBounds;
#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
FenceHandle mReleaseFenceHandle; FenceHandle mReleaseFenceHandle;
#endif #endif

View File

@ -3149,6 +3149,7 @@ AsyncPanZoomController::ReportCheckerboard(const TimeStamp& aSampleTime)
if (!mCheckerboardEvent && (recordTrace || forTelemetry)) { if (!mCheckerboardEvent && (recordTrace || forTelemetry)) {
mCheckerboardEvent = MakeUnique<CheckerboardEvent>(recordTrace); mCheckerboardEvent = MakeUnique<CheckerboardEvent>(recordTrace);
} }
mPotentialCheckerboardTracker.InTransform(IsTransformingState(mState));
if (magnitude) { if (magnitude) {
mPotentialCheckerboardTracker.CheckerboardSeen(); mPotentialCheckerboardTracker.CheckerboardSeen();
} }
@ -3634,7 +3635,6 @@ void AsyncPanZoomController::DispatchStateChangeNotification(PanZoomState aOldSt
if (RefPtr<GeckoContentController> controller = GetGeckoContentController()) { if (RefPtr<GeckoContentController> controller = GetGeckoContentController()) {
if (!IsTransformingState(aOldState) && IsTransformingState(aNewState)) { if (!IsTransformingState(aOldState) && IsTransformingState(aNewState)) {
mPotentialCheckerboardTracker.TransformStarted();
controller->NotifyAPZStateChange( controller->NotifyAPZStateChange(
GetGuid(), APZStateChange::TransformBegin); GetGuid(), APZStateChange::TransformBegin);
#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK) #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
@ -3645,7 +3645,6 @@ void AsyncPanZoomController::DispatchStateChangeNotification(PanZoomState aOldSt
} }
#endif #endif
} else if (IsTransformingState(aOldState) && !IsTransformingState(aNewState)) { } else if (IsTransformingState(aOldState) && !IsTransformingState(aNewState)) {
mPotentialCheckerboardTracker.TransformStopped();
controller->NotifyAPZStateChange( controller->NotifyAPZStateChange(
GetGuid(), APZStateChange::TransformEnd); GetGuid(), APZStateChange::TransformEnd);
#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK) #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)

View File

@ -40,21 +40,29 @@ PotentialCheckerboardDurationTracker::CheckerboardDone()
} }
void void
PotentialCheckerboardDurationTracker::TransformStarted() PotentialCheckerboardDurationTracker::InTransform(bool aInTransform)
{ {
MOZ_ASSERT(!mInTransform); if (aInTransform == mInTransform) {
if (!Tracking()) { // no-op
mCurrentPeriodStart = TimeStamp::Now(); return;
}
mInTransform = true;
} }
void
PotentialCheckerboardDurationTracker::TransformStopped()
{
MOZ_ASSERT(mInTransform);
mInTransform = false;
if (!Tracking()) { if (!Tracking()) {
// Because !Tracking(), mInTransform must be false, and so aInTransform
// must be true (or we would have early-exited this function already).
// Therefore, we are starting a potential checkerboard period.
mInTransform = aInTransform;
mCurrentPeriodStart = TimeStamp::Now();
return;
}
mInTransform = aInTransform;
if (!Tracking()) {
// Tracking() must have been true at the start of this function, or we
// would have taken the other !Tracking branch above. If it's false now,
// it means we just stopped tracking, so we are ending a potential
// checkerboard period.
mozilla::Telemetry::AccumulateTimeDelta( mozilla::Telemetry::AccumulateTimeDelta(
mozilla::Telemetry::CHECKERBOARD_POTENTIAL_DURATION, mozilla::Telemetry::CHECKERBOARD_POTENTIAL_DURATION,
mCurrentPeriodStart); mCurrentPeriodStart);

View File

@ -39,15 +39,10 @@ public:
void CheckerboardDone(); void CheckerboardDone();
/** /**
* This should be called when a transform is started. Calls to this must be * This should be called at composition time, to indicate if the APZC is in
* interleaved with calls to TransformStopped(). * a transforming state or not.
*/ */
void TransformStarted(); void InTransform(bool aInTransform);
/**
* This should be called when a transform is stopped. Calls to this must be
* interleaved with calls to TransformStarted().
*/
void TransformStopped();
private: private:
bool Tracking() const; bool Tracking() const;

View File

@ -118,6 +118,7 @@ public:
static already_AddRefed<gfxShmSharedReadLock> static already_AddRefed<gfxShmSharedReadLock>
Open(mozilla::layers::ISurfaceAllocator* aAllocator, const mozilla::layers::ShmemSection& aShmemSection) Open(mozilla::layers::ISurfaceAllocator* aAllocator, const mozilla::layers::ShmemSection& aShmemSection)
{ {
MOZ_RELEASE_ASSERT(aShmemSection.shmem().IsReadable());
RefPtr<gfxShmSharedReadLock> readLock = new gfxShmSharedReadLock(aAllocator, aShmemSection); RefPtr<gfxShmSharedReadLock> readLock = new gfxShmSharedReadLock(aAllocator, aShmemSection);
return readLock.forget(); return readLock.forget();
} }

View File

@ -522,6 +522,8 @@ BufferTextureHost::Upload(nsIntRegion *aRegion)
// We don't have a buffer; a possible cause is that the IPDL actor // We don't have a buffer; a possible cause is that the IPDL actor
// is already dead. This inevitably happens as IPDL actors can die // is already dead. This inevitably happens as IPDL actors can die
// at any time, so we want to silently return in this case. // at any time, so we want to silently return in this case.
// another possible cause is that IPDL failed to map the shmem when
// deserializing it.
return false; return false;
} }
if (!mCompositor) { if (!mCompositor) {
@ -651,9 +653,19 @@ ShmemTextureHost::ShmemTextureHost(const ipc::Shmem& aShmem,
ISurfaceAllocator* aDeallocator, ISurfaceAllocator* aDeallocator,
TextureFlags aFlags) TextureFlags aFlags)
: BufferTextureHost(aDesc, aFlags) : BufferTextureHost(aDesc, aFlags)
, mShmem(MakeUnique<ipc::Shmem>(aShmem))
, mDeallocator(aDeallocator) , mDeallocator(aDeallocator)
{ {
if (aShmem.IsReadable()) {
mShmem = MakeUnique<ipc::Shmem>(aShmem);
} else {
// This can happen if we failed to map the shmem on this process, perhaps
// because it was big and we didn't have enough contiguous address space
// available, even though we did on the child process.
// As a result this texture will be in an invalid state and Lock will
// always fail.
gfxCriticalError() << "Failed to create a valid ShmemTextureHost";
}
MOZ_COUNT_CTOR(ShmemTextureHost); MOZ_COUNT_CTOR(ShmemTextureHost);
} }

Some files were not shown because too many files have changed in this diff Show More