This commit is contained in:
Phil Ringnalda 2013-10-07 18:46:36 -07:00
Родитель 1e4f6fcad3 47924b5f72
Коммит 9c42b4def9
183 изменённых файлов: 2845 добавлений и 3642 удалений

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

@ -11,7 +11,6 @@ Cu.import('resource://gre/modules/AlarmService.jsm');
Cu.import('resource://gre/modules/ActivitiesService.jsm');
Cu.import('resource://gre/modules/PermissionPromptHelper.jsm');
Cu.import('resource://gre/modules/ObjectWrapper.jsm');
Cu.import('resource://gre/modules/NotificationDB.jsm');
Cu.import('resource://gre/modules/accessibility/AccessFu.jsm');
Cu.import('resource://gre/modules/Payment.jsm');
Cu.import("resource://gre/modules/AppsUtils.jsm");

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

@ -348,8 +348,6 @@
@BINPATH@/components/ContactManager.manifest
@BINPATH@/components/PhoneNumberService.js
@BINPATH@/components/PhoneNumberService.manifest
@BINPATH@/components/NotificationStorage.js
@BINPATH@/components/NotificationStorage.manifest
@BINPATH@/components/PermissionSettings.js
@BINPATH@/components/PermissionSettings.manifest
@BINPATH@/components/PermissionPromptService.js

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

@ -7,7 +7,6 @@ let Ci = Components.interfaces;
let Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/NotificationDB.jsm");
Cu.import("resource:///modules/RecentWindow.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",

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

@ -81,8 +81,8 @@ const PREF_PLUGINS_NOTIFYUSER = "plugins.update.notifyUser";
const PREF_PLUGINS_UPDATEURL = "plugins.update.url";
// We try to backup bookmarks at idle times, to avoid doing that at shutdown.
// Number of idle seconds before trying to backup bookmarks. 15 minutes.
const BOOKMARKS_BACKUP_IDLE_TIME = 15 * 60;
// Number of idle seconds before trying to backup bookmarks. 10 minutes.
const BOOKMARKS_BACKUP_IDLE_TIME = 10 * 60;
// Minimum interval in milliseconds between backups.
const BOOKMARKS_BACKUP_INTERVAL = 86400 * 1000;
// Maximum number of backups to create. Old ones will be purged.
@ -257,8 +257,7 @@ BrowserGlue.prototype = {
this._onPlacesShutdown();
break;
case "idle":
if ((this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000) &&
this._shouldBackupBookmarks())
if (this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000)
this._backupBookmarks();
break;
case "distribution-customization-complete":
@ -1049,8 +1048,7 @@ BrowserGlue.prototype = {
Services.prefs.getBoolPref("browser.bookmarks.restore_default_bookmarks");
if (restoreDefaultBookmarks) {
// Ensure that we already have a bookmarks backup for today.
if (this._shouldBackupBookmarks())
yield this._backupBookmarks();
yield this._backupBookmarks();
importBookmarks = true;
}
} catch(ex) {}
@ -1059,7 +1057,7 @@ BrowserGlue.prototype = {
// from bookmarks.html, we will try to restore from JSON
if (importBookmarks && !restoreDefaultBookmarks && !importBookmarksHTML) {
// get latest JSON backup
var bookmarksBackupFile = PlacesBackups.getMostRecent("json");
var bookmarksBackupFile = yield PlacesBackups.getMostRecent("json");
if (bookmarksBackupFile) {
// restore from JSON backup
yield BookmarkJSONUtils.importFromFile(bookmarksBackupFile, true);
@ -1183,22 +1181,19 @@ BrowserGlue.prototype = {
}
let waitingForBackupToComplete = true;
if (this._shouldBackupBookmarks()) {
waitingForBackupToComplete = false;
this._backupBookmarks().then(
function onSuccess() {
waitingForBackupToComplete = true;
},
function onFailure() {
Cu.reportError("Unable to backup bookmarks.");
waitingForBackupToComplete = true;
}
);
}
this._backupBookmarks().then(
function onSuccess() {
waitingForBackupToComplete = false;
},
function onFailure() {
Cu.reportError("Unable to backup bookmarks.");
waitingForBackupToComplete = false;
}
);
// Backup bookmarks to bookmarks.html to support apps that depend
// on the legacy format.
let waitingForHTMLExportToComplete = true;
let waitingForHTMLExportToComplete = false;
// If this fails to get the preference value, we don't export.
if (Services.prefs.getBoolPref("browser.bookmarks.autoExportHTML")) {
// Exceptionally, since this is a non-default setting and HTML format is
@ -1207,51 +1202,44 @@ BrowserGlue.prototype = {
// the event loop on shutdown until we include a watchdog to prevent
// potential hangs (bug 518683). The asynchronous shutdown operations
// will then be handled by a shutdown service (bug 435058).
waitingForHTMLExportToComplete = false;
waitingForHTMLExportToComplete = true;
BookmarkHTMLUtils.exportToFile(Services.dirsvc.get("BMarks", Ci.nsIFile)).then(
function onSuccess() {
waitingForHTMLExportToComplete = true;
waitingForHTMLExportToComplete = false;
},
function onFailure() {
Cu.reportError("Unable to auto export html.");
waitingForHTMLExportToComplete = true;
waitingForHTMLExportToComplete = false;
}
);
}
// The events loop should spin at least once because waitingForBackupToComplete
// is true before checking whether backup should be made.
let thread = Services.tm.currentThread;
while (!waitingForBackupToComplete || !waitingForHTMLExportToComplete) {
while (waitingForBackupToComplete || waitingForHTMLExportToComplete) {
thread.processNextEvent(true);
}
},
/**
* Determine whether to backup bookmarks or not.
* @return true if bookmarks should be backed up, false if not.
*/
_shouldBackupBookmarks: function BG__shouldBackupBookmarks() {
let lastBackupFile = PlacesBackups.getMostRecent();
// Should backup bookmarks if there are no backups or the maximum interval between
// backups elapsed.
return (!lastBackupFile ||
new Date() - PlacesBackups.getDateForFile(lastBackupFile) > BOOKMARKS_BACKUP_INTERVAL);
},
/**
* Backup bookmarks.
*/
_backupBookmarks: function BG__backupBookmarks() {
return Task.spawn(function() {
// Backup bookmarks if there are no backups or the maximum interval between
// backups elapsed.
let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS;
try {
maxBackups = Services.prefs.getIntPref("browser.bookmarks.max_backups");
}
catch(ex) { /* Use default. */ }
let lastBackupFile = yield PlacesBackups.getMostRecentBackup();
// Should backup bookmarks if there are no backups or the maximum
// interval between backups elapsed.
if (!lastBackupFile ||
new Date() - PlacesBackups.getDateForFile(lastBackupFile) > BOOKMARKS_BACKUP_INTERVAL) {
let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS;
try {
maxBackups = Services.prefs.getIntPref("browser.bookmarks.max_backups");
}
catch(ex) { /* Use default. */ }
yield PlacesBackups.create(maxBackups); // Don't force creation.
yield PlacesBackups.create(maxBackups); // Don't force creation.
}
});
},

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

@ -407,59 +407,64 @@ var PlacesOrganizer = {
while (restorePopup.childNodes.length > 1)
restorePopup.removeChild(restorePopup.firstChild);
let backupFiles = PlacesBackups.entries;
if (backupFiles.length == 0)
return;
Task.spawn(function() {
let backupFiles = yield PlacesBackups.getBackupFiles();
if (backupFiles.length == 0)
return;
// Populate menu with backups.
for (let i = 0; i < backupFiles.length; i++) {
let [size, unit] = DownloadUtils.convertByteUnits(backupFiles[i].fileSize);
let sizeString = PlacesUtils.getFormattedString("backupFileSizeText",
[size, unit]);
let sizeInfo;
let bookmarkCount = PlacesBackups.getBookmarkCountForFile(backupFiles[i]);
if (bookmarkCount != null) {
sizeInfo = " (" + sizeString + " - " +
PlacesUIUtils.getPluralString("detailsPane.itemsCountLabel",
bookmarkCount,
[bookmarkCount]) +
")";
} else {
sizeInfo = " (" + sizeString + ")";
// Populate menu with backups.
for (let i = 0; i < backupFiles.length; i++) {
let fileSize = (yield OS.File.stat(backupFiles[i])).size;
let [size, unit] = DownloadUtils.convertByteUnits(fileSize);
let sizeString = PlacesUtils.getFormattedString("backupFileSizeText",
[size, unit]);
let sizeInfo;
let bookmarkCount = PlacesBackups.getBookmarkCountForFile(backupFiles[i]);
if (bookmarkCount != null) {
sizeInfo = " (" + sizeString + " - " +
PlacesUIUtils.getPluralString("detailsPane.itemsCountLabel",
bookmarkCount,
[bookmarkCount]) +
")";
} else {
sizeInfo = " (" + sizeString + ")";
}
let backupDate = PlacesBackups.getDateForFile(backupFiles[i]);
let m = restorePopup.insertBefore(document.createElement("menuitem"),
document.getElementById("restoreFromFile"));
m.setAttribute("label",
dateSvc.FormatDate("",
Ci.nsIScriptableDateFormat.dateFormatLong,
backupDate.getFullYear(),
backupDate.getMonth() + 1,
backupDate.getDate()) +
sizeInfo);
m.setAttribute("value", OS.Path.basename(backupFiles[i]));
m.setAttribute("oncommand",
"PlacesOrganizer.onRestoreMenuItemClick(this);");
}
let backupDate = PlacesBackups.getDateForFile(backupFiles[i]);
let m = restorePopup.insertBefore(document.createElement("menuitem"),
document.getElementById("restoreFromFile"));
m.setAttribute("label",
dateSvc.FormatDate("",
Ci.nsIScriptableDateFormat.dateFormatLong,
backupDate.getFullYear(),
backupDate.getMonth() + 1,
backupDate.getDate()) +
sizeInfo);
m.setAttribute("value", backupFiles[i].leafName);
m.setAttribute("oncommand",
"PlacesOrganizer.onRestoreMenuItemClick(this);");
}
// Add the restoreFromFile item.
restorePopup.insertBefore(document.createElement("menuseparator"),
document.getElementById("restoreFromFile"));
// Add the restoreFromFile item.
restorePopup.insertBefore(document.createElement("menuseparator"),
document.getElementById("restoreFromFile"));
});
},
/**
* Called when a menuitem is selected from the restore menu.
*/
onRestoreMenuItemClick: function PO_onRestoreMenuItemClick(aMenuItem) {
let backupName = aMenuItem.getAttribute("value");
let backupFiles = PlacesBackups.entries;
for (let i = 0; i < backupFiles.length; i++) {
if (backupFiles[i].leafName == backupName) {
this.restoreBookmarksFromFile(backupFiles[i]);
break;
Task.spawn(function() {
let backupName = aMenuItem.getAttribute("value");
let backupFilePaths = yield PlacesBackups.getBackupFiles();
for (let backupFilePath of backupFilePaths) {
if (OS.Path.basename(backupFilePath) == backupName) {
PlacesOrganizer.restoreBookmarksFromFile(new FileUtils.File(backupFilePath));
break;
}
}
}
});
},
/**

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

@ -319,20 +319,25 @@ function run_test() {
let bg = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver);
// Initialize Places.
PlacesUtils.history;
// Observes Places initialisation complete.
Services.obs.addObserver(function waitPlaceInitComplete() {
Services.obs.removeObserver(waitPlaceInitComplete, "places-browser-init-complete");
// Ensure preferences status.
do_check_false(Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML));
do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
try {
do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
do_throw("importBookmarksHTML pref should not exist");
}
catch(ex) {}
waitForImportAndSmartBookmarks(next_test);
}, "places-browser-init-complete", false);
// Usually places init would async notify to glue, but we want to avoid
// randomness here, thus we fire the notification synchronously.
bg.observe(null, "places-init-complete", null);
// Ensure preferences status.
do_check_false(Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML));
do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
try {
do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
do_throw("importBookmarksHTML pref should not exist");
}
catch(ex) {}
waitForImportAndSmartBookmarks(next_test);
}
function waitForImportAndSmartBookmarks(aCallback) {

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

@ -528,8 +528,6 @@
@BINPATH@/components/ContactManager.manifest
@BINPATH@/components/PhoneNumberService.js
@BINPATH@/components/PhoneNumberService.manifest
@BINPATH@/components/NotificationStorage.js
@BINPATH@/components/NotificationStorage.manifest
@BINPATH@/components/AlarmsManager.js
@BINPATH@/components/AlarmsManager.manifest
@BINPATH@/components/Push.js

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

@ -106,8 +106,8 @@ BoxBlur(const uint8_t *aInput, uint8_t *aOutput,
int32_t aLeftLobe, int32_t aRightLobe, bool aAlphaOnly)
{
int32_t boxSize = aLeftLobe + aRightLobe + 1;
int32_t scaledDivisor = ComputeScaledDivisor(boxSize);
int32_t sums[4] = {0, 0, 0, 0};
uint32_t scaledDivisor = ComputeScaledDivisor(boxSize);
uint32_t sums[4] = {0, 0, 0, 0};
for (int32_t i=0; i < boxSize; i++) {
int32_t pos = aStartMinor - aLeftLobe + i;
@ -119,7 +119,7 @@ BoxBlur(const uint8_t *aInput, uint8_t *aOutput,
}
aOutput += aStrideMinor*aStartMinor;
if (aStartMinor + int32_t(boxSize) <= aEndMinor) {
if (aStartMinor + boxSize <= aEndMinor) {
const uint8_t *lastInput = aInput + aStartMinor*aStrideMinor;
const uint8_t *nextInput = aInput + (aStartMinor + aRightLobe + 1)*aStrideMinor;
#define OUTPUT(j) aOutput[j] = (sums[j]*scaledDivisor) >> 24;

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

@ -118,10 +118,6 @@ DOMInterfaces = {
'resultNotAddRefed': [ 'playbackRate' ],
},
'Notification' : {
'nativeType': 'mozilla::dom::Notification'
},
'AudioNode' : {
'concrete': False,
'binaryNames': {

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

@ -147,9 +147,11 @@ this.DataStore.prototype = {
let pendingIds = aIds.length;
let indexPos = 0;
let self = this;
function getInternalSuccess(aEvent, aPos) {
debug("GetInternal success. Record: " + aEvent.target.result);
results[aPos] = aEvent.target.result;
results[aPos] = ObjectWrapper.wrap(aEvent.target.result, self._window);
if (!--pendingIds) {
aCallback(results);
return;

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

@ -0,0 +1,77 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test for bug 924104</title>
</head>
<body>
<div id="container"></div>
<script type="application/javascript;version=1.7">
var gStore;
function is(a, b, msg) {
alert((a === b ? 'OK' : 'KO') + ' ' + msg)
}
function ok(a, msg) {
alert((a ? 'OK' : 'KO')+ ' ' + msg)
}
function cbError() {
alert('KO error');
}
function finish() {
alert('DONE');
}
function testGetDataStores() {
navigator.getDataStores('foo').then(function(stores) {
gStore = stores[0];
runTest();
}, cbError);
}
function testBug924104() {
gStore
.add({})
.then(
function(index) {
ok(index, "store.add() created item" + index);
return gStore.get(index);
},
cbError)
.then(
function(obj) {
ok(true, "store.get() works");
var status = false;
try {
obj['foobar'] = 42;
status = true;
} catch(e) {}
ok(status, "Object is editable");
runTest();
},
cbError);
}
var tests = [
testGetDataStores,
testBug924104
];
function runTest() {
if (!tests.length) {
finish();
return;
}
var test = tests.shift();
test();
}
runTest();
</script>
</body>
</html>

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

@ -11,6 +11,7 @@ support-files =
file_app2.template.webapp
file_arrays.html
file_sync.html
file_bug924104.html
[test_app_install.html]
[test_readonly.html]
@ -20,3 +21,4 @@ support-files =
[test_arrays.html]
[test_oop.html]
[test_sync.html]
[test_bug924104.html]

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

@ -0,0 +1,129 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test bug 924104</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<div id="container"></div>
<script type="application/javascript;version=1.7">
var gHostedManifestURL = 'http://test/tests/dom/datastore/tests/file_app.sjs?testToken=file_bug924104.html';
var gApp;
function cbError() {
ok(false, "Error callback invoked");
finish();
}
function installApp() {
var request = navigator.mozApps.install(gHostedManifestURL);
request.onerror = cbError;
request.onsuccess = function() {
gApp = request.result;
runTest();
}
}
function uninstallApp() {
// Uninstall the app.
var request = navigator.mozApps.mgmt.uninstall(gApp);
request.onerror = cbError;
request.onsuccess = function() {
// All done.
info("All done");
runTest();
}
}
function testApp() {
var ifr = document.createElement('iframe');
ifr.setAttribute('mozbrowser', 'true');
ifr.setAttribute('mozapp', gApp.manifestURL);
ifr.setAttribute('src', gApp.manifest.launch_path);
var domParent = document.getElementById('container');
// Set us up to listen for messages from the app.
var listener = function(e) {
var message = e.detail.message;
if (/^OK/.exec(message)) {
ok(true, "Message from app: " + message);
} else if (/KO/.exec(message)) {
ok(false, "Message from app: " + message);
} else if (/DONE/.exec(message)) {
ok(true, "Messaging from app complete");
ifr.removeEventListener('mozbrowsershowmodalprompt', listener);
domParent.removeChild(ifr);
runTest();
}
}
// This event is triggered when the app calls "alert".
ifr.addEventListener('mozbrowsershowmodalprompt', listener, false);
domParent.appendChild(ifr);
}
var tests = [
// Permissions
function() {
SpecialPowers.pushPermissions(
[{ "type": "browser", "allow": 1, "context": document },
{ "type": "embed-apps", "allow": 1, "context": document },
{ "type": "webapps-manage", "allow": 1, "context": document }], runTest);
},
// Preferences
function() {
SpecialPowers.pushPrefEnv({"set": [["dom.promise.enabled", true]]}, runTest);
},
function() {
SpecialPowers.pushPrefEnv({"set": [["dom.datastore.enabled", true]]}, runTest);
},
function() {
SpecialPowers.setAllAppsLaunchable(true);
SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
runTest();
},
// No confirmation needed when an app is installed
function() {
SpecialPowers.autoConfirmAppInstall(runTest);
},
// Installing the app
installApp,
// Run tests in app
testApp,
// Uninstall the app
uninstallApp
];
function runTest() {
if (!tests.length) {
finish();
return;
}
var test = tests.shift();
test();
}
function finish() {
SimpleTest.finish();
}
if (SpecialPowers.isMainProcess()) {
SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
}
SimpleTest.waitForExplicitFinish();
runTest();
</script>
</body>
</html>

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

@ -6,7 +6,6 @@
XPIDL_SOURCES += [
'nsIDOMDesktopNotification.idl',
'nsINotificationStorage.idl',
]
XPIDL_MODULE = 'dom_notification'

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

@ -1,92 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "domstubs.idl"
[scriptable, uuid(fb089720-1c5c-11e3-b773-0800200c9a66)]
interface nsINotificationStorageCallback : nsISupports
{
/**
* Callback function used to pass single notification back
* into C++ land for Notification.get return data.
*
* @param id: a uuid for this notification
* @param title: the notification title
* @param dir: the notification direction,
* possible values are "ltr", "rtl", "auto"
* @param lang: the notification language
* @param body: the notification body
* @param tag: the notification tag
*/
[implicit_jscontext]
void handle(in DOMString id,
in DOMString title,
in DOMString dir,
in DOMString lang,
in DOMString body,
in DOMString tag,
in DOMString icon);
/**
* Callback function used to notify C++ the we have returned
* all notification objects for this Notification.get call.
*/
[implicit_jscontext]
void done();
};
/**
* Interface for notification persistence layer.
*/
[scriptable, uuid(b177b080-2a23-11e3-8224-0800200c9a66)]
interface nsINotificationStorage : nsISupports
{
/**
* Add/replace a notification to the persistence layer.
*
* @param origin: the origin/app of this notification
* @param id: a uuid for this notification
* @param title: the notification title
* @param dir: the notification direction,
* possible values are "ltr", "rtl", "auto"
* @param lang: the notification language
* @param body: the notification body
* @param tag: notification tag, will replace any existing
* notifications with same origin/tag pair
*/
void put(in DOMString origin,
in DOMString id,
in DOMString title,
in DOMString dir,
in DOMString lang,
in DOMString body,
in DOMString tag,
in DOMString icon);
/**
* Retrieve a list of notifications.
*
* @param origin: the origin/app for which to fetch notifications from
* @param tag: used to fetch only a specific tag
* @param callback: nsINotificationStorageCallback, used for
* returning notifications objects
*/
void get(in DOMString origin,
in DOMString tag,
in nsINotificationStorageCallback aCallback);
/**
* Remove a notification from storage.
*
* @param origin: the origin/app to delete the notification from
* @param id: the uuid for the notification to delete
*/
void delete(in DOMString origin,
in DOMString id);
};
%{C++
#define NS_NOTIFICATION_STORAGE_CONTRACTID "@mozilla.org/notificationStorage;1"
%}

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

@ -189,20 +189,6 @@ Promise::EnabledForScope(JSContext* aCx, JSObject* /* unused */)
prin->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED;
}
void
Promise::MaybeResolve(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue)
{
MaybeResolveInternal(aCx, aValue);
}
void
Promise::MaybeReject(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue)
{
MaybeRejectInternal(aCx, aValue);
}
static void
EnterCompartment(Maybe<JSAutoCompartment>& aAc, JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue)
@ -243,9 +229,9 @@ Promise::JSCallback(JSContext *aCx, unsigned aArgc, JS::Value *aVp)
PromiseCallback::Task task = static_cast<PromiseCallback::Task>(v.toInt32());
if (task == PromiseCallback::Resolve) {
promise->MaybeResolveInternal(aCx, value);
promise->MaybeResolve(aCx, value);
} else {
promise->MaybeRejectInternal(aCx, value);
promise->MaybeReject(aCx, value);
}
return true;
@ -314,7 +300,7 @@ Promise::Constructor(const GlobalObject& aGlobal,
Maybe<JSAutoCompartment> ac;
EnterCompartment(ac, cx, value);
promise->MaybeRejectInternal(cx, value);
promise->MaybeReject(cx, value);
}
return promise.forget();
@ -333,7 +319,7 @@ Promise::Resolve(const GlobalObject& aGlobal, JSContext* aCx,
nsRefPtr<Promise> promise = new Promise(window);
Optional<JS::Handle<JS::Value> > value(aCx, aValue);
promise->MaybeResolveInternal(aCx, value);
promise->MaybeResolve(aCx, value);
return promise.forget();
}
@ -350,7 +336,7 @@ Promise::Reject(const GlobalObject& aGlobal, JSContext* aCx,
nsRefPtr<Promise> promise = new Promise(window);
Optional<JS::Handle<JS::Value> > value(aCx, aValue);
promise->MaybeRejectInternal(aCx, value);
promise->MaybeReject(aCx, value);
return promise.forget();
}
@ -455,9 +441,9 @@ Promise::MaybeReportRejected()
}
void
Promise::MaybeResolveInternal(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aAsynchronous)
Promise::MaybeResolve(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aAsynchronous)
{
if (mResolvePending) {
return;
@ -467,9 +453,9 @@ Promise::MaybeResolveInternal(JSContext* aCx,
}
void
Promise::MaybeRejectInternal(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aAsynchronous)
Promise::MaybeReject(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aAsynchronous)
{
if (mResolvePending) {
return;

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

@ -43,11 +43,6 @@ public:
static bool PrefEnabled();
static bool EnabledForScope(JSContext* aCx, JSObject* /* unused */);
void MaybeResolve(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue);
void MaybeReject(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue);
// WebIDL
nsPIDOMWindow* GetParentObject() const
@ -119,12 +114,12 @@ private:
// report it to the error console.
void MaybeReportRejected();
void MaybeResolveInternal(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aSync = AsyncTask);
void MaybeRejectInternal(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aSync = AsyncTask);
void MaybeResolve(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aSync = AsyncTask);
void MaybeReject(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,
PromiseTaskSync aSync = AsyncTask);
void ResolveInternal(JSContext* aCx,
const Optional<JS::Handle<JS::Value> >& aValue,

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

@ -5,7 +5,6 @@
#include "PCOMContentPermissionRequestChild.h"
#include "mozilla/dom/Notification.h"
#include "mozilla/dom/OwningNonNull.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/Preferences.h"
#include "TabChild.h"
#include "nsContentUtils.h"
@ -13,135 +12,20 @@
#include "nsIAlertsService.h"
#include "nsIContentPermissionPrompt.h"
#include "nsIDocument.h"
#include "nsINotificationStorage.h"
#include "nsIPermissionManager.h"
#include "nsIUUIDGenerator.h"
#include "nsServiceManagerUtils.h"
#include "nsToolkitCompsCID.h"
#include "nsGlobalWindow.h"
#include "nsDOMJSUtils.h"
#include "nsIScriptSecurityManager.h"
#include "nsIAppsService.h"
#ifdef MOZ_B2G
#include "nsIDOMDesktopNotification.h"
#include "nsIAppsService.h"
#endif
namespace mozilla {
namespace dom {
class NotificationStorageCallback MOZ_FINAL : public nsINotificationStorageCallback
{
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(NotificationStorageCallback)
NotificationStorageCallback(const GlobalObject& aGlobal, nsPIDOMWindow* aWindow, Promise* aPromise)
: mCount(0),
mGlobal(aGlobal.Get()),
mWindow(aWindow),
mPromise(aPromise)
{
MOZ_ASSERT(aWindow);
MOZ_ASSERT(aPromise);
JSContext* cx = aGlobal.GetContext();
mNotifications = JS_NewArrayObject(cx, 0, nullptr);
HoldData();
}
NS_IMETHOD Handle(const nsAString& aID,
const nsAString& aTitle,
const nsAString& aDir,
const nsAString& aLang,
const nsAString& aBody,
const nsAString& aTag,
const nsAString& aIcon,
JSContext* aCx)
{
MOZ_ASSERT(!aID.IsEmpty());
MOZ_ASSERT(!aTitle.IsEmpty());
NotificationOptions options;
options.mDir = Notification::StringToDirection(nsString(aDir));
options.mLang = aLang;
options.mBody = aBody;
options.mTag = aTag;
options.mIcon = aIcon;
nsRefPtr<Notification> notification = Notification::CreateInternal(mWindow,
aID,
aTitle,
options);
JSAutoCompartment ac(aCx, mGlobal);
JS::RootedObject scope(aCx, mGlobal);
JS::RootedObject element(aCx, notification->WrapObject(aCx, scope));
NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
if (!JS_DefineElement(aCx, mNotifications, mCount++,
JS::ObjectValue(*element), nullptr, nullptr, 0)) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHOD Done(JSContext* aCx)
{
JSAutoCompartment ac(aCx, mGlobal);
Optional<JS::HandleValue> result(aCx, JS::ObjectValue(*mNotifications));
mPromise->MaybeResolve(aCx, result);
return NS_OK;
}
private:
~NotificationStorageCallback()
{
DropData();
}
void HoldData()
{
mozilla::HoldJSObjects(this);
}
void DropData()
{
mGlobal = nullptr;
mNotifications = nullptr;
mozilla::DropJSObjects(this);
}
uint32_t mCount;
JS::Heap<JSObject *> mGlobal;
nsCOMPtr<nsPIDOMWindow> mWindow;
nsRefPtr<Promise> mPromise;
JS::Heap<JSObject *> mNotifications;
};
NS_IMPL_CYCLE_COLLECTING_ADDREF(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION_CLASS(NotificationStorageCallback)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NotificationStorageCallback)
NS_INTERFACE_MAP_ENTRY(nsINotificationStorageCallback)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mGlobal)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mNotifications)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPromise)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPromise)
tmp->DropData();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
class NotificationPermissionRequest : public nsIContentPermissionRequest,
public PCOMContentPermissionRequestChild,
public nsIRunnable
@ -372,15 +256,12 @@ NotificationTask::Run()
{
switch (mAction) {
case eShow:
mNotification->ShowInternal();
break;
return mNotification->ShowInternal();
case eClose:
mNotification->CloseInternal();
break;
return mNotification->CloseInternal();
default:
MOZ_CRASH("Unexpected action for NotificationTask.");
}
return NS_OK;
}
NS_IMPL_ISUPPORTS1(NotificationObserver, nsIObserver)
@ -401,103 +282,50 @@ NotificationObserver::Observe(nsISupports* aSubject, const char* aTopic,
return NS_OK;
}
Notification::Notification(const nsAString& aID, const nsAString& aTitle, const nsAString& aBody,
Notification::Notification(const nsAString& aTitle, const nsAString& aBody,
NotificationDirection aDir, const nsAString& aLang,
const nsAString& aTag, const nsAString& aIconUrl)
: mID(aID), mTitle(aTitle), mBody(aBody), mDir(aDir), mLang(aLang),
: mTitle(aTitle), mBody(aBody), mDir(aDir), mLang(aLang),
mTag(aTag), mIconUrl(aIconUrl), mIsClosed(false)
{
SetIsDOMBinding();
}
// static
already_AddRefed<Notification>
Notification::Constructor(const GlobalObject& aGlobal,
const nsAString& aTitle,
const NotificationOptions& aOptions,
ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread());
nsString tag;
if (aOptions.mTag.WasPassed()) {
tag.Append(NS_LITERAL_STRING("tag:"));
tag.Append(aOptions.mTag.Value());
} else {
tag.Append(NS_LITERAL_STRING("notag:"));
tag.AppendInt(sCount++);
}
nsRefPtr<Notification> notification = new Notification(aTitle,
aOptions.mBody,
aOptions.mDir,
aOptions.mLang,
tag,
aOptions.mIcon);
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal.GetAsSupports());
MOZ_ASSERT(window, "Window should not be null.");
nsRefPtr<Notification> notification = CreateInternal(window,
EmptyString(),
aTitle,
aOptions);
notification->BindToOwner(window);
// Queue a task to show the notification.
nsCOMPtr<nsIRunnable> showNotificationTask =
new NotificationTask(notification, NotificationTask::eShow);
NS_DispatchToCurrentThread(showNotificationTask);
// Persist the notification.
nsresult rv;
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return nullptr;
}
nsString origin;
aRv = GetOrigin(window, origin);
if (aRv.Failed()) {
return nullptr;
}
nsString id;
notification->GetID(id);
aRv = notificationStorage->Put(origin,
id,
aTitle,
DirectionToString(aOptions.mDir),
aOptions.mLang,
aOptions.mBody,
aOptions.mTag,
aOptions.mIcon);
if (aRv.Failed()) {
return nullptr;
}
NS_DispatchToMainThread(showNotificationTask);
return notification.forget();
}
already_AddRefed<Notification>
Notification::CreateInternal(nsPIDOMWindow* aWindow,
const nsAString& aID,
const nsAString& aTitle,
const NotificationOptions& aOptions)
{
nsString id;
if (!aID.IsEmpty()) {
id = aID;
} else {
nsCOMPtr<nsIUUIDGenerator> uuidgen =
do_GetService("@mozilla.org/uuid-generator;1");
NS_ENSURE_TRUE(uuidgen, nullptr);
nsID uuid;
nsresult rv = uuidgen->GenerateUUIDInPlace(&uuid);
NS_ENSURE_SUCCESS(rv, nullptr);
char buffer[NSID_LENGTH];
uuid.ToProvidedString(buffer);
NS_ConvertASCIItoUTF16 convertedID(buffer);
id = convertedID;
}
nsRefPtr<Notification> notification = new Notification(id,
aTitle,
aOptions.mBody,
aOptions.mDir,
aOptions.mLang,
aOptions.mTag,
aOptions.mIcon);
notification->BindToOwner(aWindow);
return notification.forget();
}
void
nsresult
Notification::ShowInternal()
{
nsCOMPtr<nsIAlertsService> alertService =
@ -508,8 +336,7 @@ Notification::ShowInternal()
NotificationPermission::Granted || !alertService) {
// We do not have permission to show a notification or alert service
// is not available.
DispatchTrustedEvent(NS_LITERAL_STRING("error"));
return;
return DispatchTrustedEvent(NS_LITERAL_STRING("error"));
}
nsresult rv;
@ -517,18 +344,17 @@ Notification::ShowInternal()
if (mIconUrl.Length() > 0) {
// Resolve image URL against document base URI.
nsIDocument* doc = GetOwner()->GetExtantDoc();
if (doc) {
nsCOMPtr<nsIURI> baseUri = doc->GetBaseURI();
if (baseUri) {
nsCOMPtr<nsIURI> srcUri;
rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(srcUri),
mIconUrl, doc, baseUri);
if (NS_SUCCEEDED(rv)) {
nsAutoCString src;
srcUri->GetSpec(src);
absoluteUrl = NS_ConvertUTF8toUTF16(src);
}
}
NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIURI> baseUri = doc->GetBaseURI();
NS_ENSURE_TRUE(baseUri, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIURI> srcUri;
rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(srcUri),
mIconUrl, doc, baseUri);
NS_ENSURE_SUCCESS(rv, rv);
if (srcUri) {
nsAutoCString src;
srcUri->GetSpec(src);
absoluteUrl = NS_ConvertUTF8toUTF16(src);
}
}
@ -536,7 +362,7 @@ Notification::ShowInternal()
nsString alertName;
rv = GetAlertName(alertName);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_SUCCESS(rv, rv);
#ifdef MOZ_B2G
nsCOMPtr<nsIAppNotificationService> appNotifier =
@ -548,15 +374,12 @@ Notification::ShowInternal()
if (appId != nsIScriptSecurityManager::UNKNOWN_APP_ID) {
nsCOMPtr<nsIAppsService> appsService = do_GetService("@mozilla.org/AppsService;1");
nsString manifestUrl = EmptyString();
rv = appsService->GetManifestURLByLocalId(appId, manifestUrl);
if (NS_SUCCEEDED(rv)) {
appNotifier->ShowAppNotification(mIconUrl, mTitle, mBody,
true,
manifestUrl,
observer,
alertName);
return;
}
appsService->GetManifestURLByLocalId(appId, manifestUrl);
return appNotifier->ShowAppNotification(mIconUrl, mTitle, mBody,
true,
manifestUrl,
observer,
alertName);
}
}
#endif
@ -565,9 +388,9 @@ Notification::ShowInternal()
// nsIObserver. Thus the cookie must be unique to differentiate observers.
nsString uniqueCookie = NS_LITERAL_STRING("notification:");
uniqueCookie.AppendInt(sCount++);
alertService->ShowAlertNotification(absoluteUrl, mTitle, mBody, true,
uniqueCookie, observer, alertName,
DirectionToString(mDir), mLang);
return alertService->ShowAlertNotification(absoluteUrl, mTitle, mBody, true,
uniqueCookie, observer, alertName,
DirectionToString(mDir), mLang);
}
void
@ -655,47 +478,6 @@ Notification::GetPermissionInternal(nsISupports* aGlobal, ErrorResult& aRv)
}
}
already_AddRefed<Promise>
Notification::Get(const GlobalObject& aGlobal,
const GetNotificationOptions& aFilter,
ErrorResult& aRv)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal.GetAsSupports());
MOZ_ASSERT(window);
nsIDocument* doc = window->GetExtantDoc();
if (!doc) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsString origin;
aRv = GetOrigin(window, origin);
if (aRv.Failed()) {
return nullptr;
}
nsresult rv;
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return nullptr;
}
nsRefPtr<Promise> promise = new Promise(window);
nsCOMPtr<nsINotificationStorageCallback> callback =
new NotificationStorageCallback(aGlobal, window, promise);
nsString tag = aFilter.mTag.WasPassed() ?
aFilter.mTag.Value() :
EmptyString();
aRv = notificationStorage->Get(origin, tag, callback);
if (aRv.Failed()) {
return nullptr;
}
return promise.forget();
}
bool
Notification::PrefEnabled()
{
@ -717,61 +499,22 @@ Notification::Close()
NS_DispatchToMainThread(showNotificationTask);
}
void
nsresult
Notification::CloseInternal()
{
if (!mIsClosed) {
nsresult rv;
// Don't bail out if notification storage fails, since we still
// want to send the close event through the alert service.
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID);
if (notificationStorage) {
nsString origin;
rv = GetOrigin(GetOwner(), origin);
if (NS_SUCCEEDED(rv)) {
notificationStorage->Delete(origin, mID);
}
}
nsCOMPtr<nsIAlertsService> alertService =
do_GetService(NS_ALERTSERVICE_CONTRACTID);
if (alertService) {
nsString alertName;
rv = GetAlertName(alertName);
if (NS_SUCCEEDED(rv)) {
alertService->CloseAlert(alertName);
}
nsresult rv = GetAlertName(alertName);
NS_ENSURE_SUCCESS(rv, rv);
rv = alertService->CloseAlert(alertName);
NS_ENSURE_SUCCESS(rv, rv);
}
}
}
nsresult
Notification::GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin)
{
MOZ_ASSERT(aWindow);
nsresult rv;
nsIDocument* doc = aWindow->GetExtantDoc();
NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
nsIPrincipal* principal = doc->NodePrincipal();
NS_ENSURE_TRUE(principal, NS_ERROR_UNEXPECTED);
uint16_t appStatus = principal->GetAppStatus();
uint32_t appId = principal->GetAppId();
if (appStatus == nsIPrincipal::APP_STATUS_NOT_INSTALLED ||
appId == nsIScriptSecurityManager::NO_APP_ID ||
appId == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
rv = nsContentUtils::GetUTFOrigin(principal, aOrigin);
NS_ENSURE_SUCCESS(rv, rv);
} else {
// If we are in "app code", use manifest URL as unique origin since
// multiple apps can share the same origin but not same notifications.
nsCOMPtr<nsIAppsService> appsService =
do_GetService("@mozilla.org/AppsService;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
appsService->GetManifestURLByLocalId(appId, aOrigin);
}
return NS_OK;
}
@ -779,12 +522,20 @@ Notification::GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin)
nsresult
Notification::GetAlertName(nsString& aAlertName)
{
// Get the notification name that is unique per origin + ID.
// The name of the alert is of the form origin#ID.
nsresult rv = GetOrigin(GetOwner(), aAlertName);
// Get the notification name that is unique per origin + tag.
// The name of the alert is of the form origin#tag
nsPIDOMWindow* owner = GetOwner();
NS_ENSURE_TRUE(owner, NS_ERROR_UNEXPECTED);
nsIDocument* doc = owner->GetExtantDoc();
NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
nsresult rv = nsContentUtils::GetUTFOrigin(doc->NodePrincipal(),
aAlertName);
NS_ENSURE_SUCCESS(rv, rv);
aAlertName.AppendLiteral("#");
aAlertName.Append(mID);
aAlertName.Append(mTag);
return NS_OK;
}

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

@ -10,37 +10,31 @@
#include "nsDOMEventTargetHelper.h"
#include "nsIObserver.h"
#include "nsCycleCollectionParticipant.h"
namespace mozilla {
namespace dom {
class NotificationObserver;
class Promise;
class Notification : public nsDOMEventTargetHelper
{
friend class NotificationTask;
friend class NotificationPermissionRequest;
friend class NotificationObserver;
friend class NotificationStorageCallback;
public:
IMPL_EVENT_HANDLER(click)
IMPL_EVENT_HANDLER(show)
IMPL_EVENT_HANDLER(error)
IMPL_EVENT_HANDLER(close)
Notification(const nsAString& aTitle, const nsAString& aBody,
NotificationDirection aDir, const nsAString& aLang,
const nsAString& aTag, const nsAString& aIconUrl);
static already_AddRefed<Notification> Constructor(const GlobalObject& aGlobal,
const nsAString& aTitle,
const NotificationOptions& aOption,
ErrorResult& aRv);
void GetID(nsAString& aRetval) {
aRetval = mID;
}
void GetTitle(nsAString& aRetval)
void GetTitle(nsString& aRetval)
{
aRetval = mTitle;
}
@ -50,22 +44,24 @@ public:
return mDir;
}
void GetLang(nsAString& aRetval)
void GetLang(nsString& aRetval)
{
aRetval = mLang;
}
void GetBody(nsAString& aRetval)
void GetBody(nsString& aRetval)
{
aRetval = mBody;
}
void GetTag(nsAString& aRetval)
void GetTag(nsString& aRetval)
{
aRetval = mTag;
if (StringBeginsWith(mTag, NS_LITERAL_STRING("tag:"))) {
aRetval = Substring(mTag, 4);
}
}
void GetIcon(nsAString& aRetval)
void GetIcon(nsString& aRetval)
{
aRetval = mIconUrl;
}
@ -77,10 +73,6 @@ public:
static NotificationPermission GetPermission(const GlobalObject& aGlobal,
ErrorResult& aRv);
static already_AddRefed<Promise> Get(const GlobalObject& aGlobal,
const GetNotificationOptions& aFilter,
ErrorResult& aRv);
void Close();
static bool PrefEnabled();
@ -93,17 +85,8 @@ public:
virtual JSObject* WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
protected:
Notification(const nsAString& aID, const nsAString& aTitle, const nsAString& aBody,
NotificationDirection aDir, const nsAString& aLang,
const nsAString& aTag, const nsAString& aIconUrl);
static already_AddRefed<Notification> CreateInternal(nsPIDOMWindow* aWindow,
const nsAString& aID,
const nsAString& aTitle,
const NotificationOptions& aOptions);
void ShowInternal();
void CloseInternal();
nsresult ShowInternal();
nsresult CloseInternal();
static NotificationPermission GetPermissionInternal(nsISupports* aGlobal,
ErrorResult& rv);
@ -120,22 +103,8 @@ protected:
}
}
static const NotificationDirection StringToDirection(const nsAString& aDirection)
{
if (aDirection.EqualsLiteral("ltr")) {
return NotificationDirection::Ltr;
}
if (aDirection.EqualsLiteral("rtl")) {
return NotificationDirection::Rtl;
}
return NotificationDirection::Auto;
}
static nsresult GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin);
nsresult GetAlertName(nsString& aAlertName);
nsString mID;
nsString mTitle;
nsString mBody;
NotificationDirection mDir;

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

@ -1,270 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = [];
const DEBUG = false;
function debug(s) { dump("-*- NotificationDB component: " + s + "\n"); }
const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
"@mozilla.org/parentprocessmessagemanager;1",
"nsIMessageListenerManager");
XPCOMUtils.defineLazyGetter(this, "gEncoder", function() {
return new TextEncoder();
});
XPCOMUtils.defineLazyGetter(this, "gDecoder", function() {
return new TextDecoder();
});
const NOTIFICATION_STORE_DIR = OS.Constants.Path.profileDir;
const NOTIFICATION_STORE_PATH =
OS.Path.join(NOTIFICATION_STORE_DIR, "notificationstore.json");
let NotificationDB = {
init: function() {
this.notifications = {};
this.byTag = {};
this.loaded = false;
this.tasks = []; // read/write operation queue
this.runningTask = false;
ppmm.addMessageListener("Notification:Save", this);
ppmm.addMessageListener("Notification:Delete", this);
ppmm.addMessageListener("Notification:GetAll", this);
},
// Attempt to read notification file, if it's not there we will create it.
load: function(callback) {
var promise = OS.File.read(NOTIFICATION_STORE_PATH);
promise.then(
function onSuccess(data) {
try {
this.notifications = JSON.parse(gDecoder.decode(data));
} catch (e) {
if (DEBUG) { debug("Unable to parse file data " + e); }
}
this.loaded = true;
callback && callback();
}.bind(this),
// If read failed, we assume we have no notifications to load.
function onFailure(reason) {
this.loaded = true;
this.createStore(callback);
}.bind(this)
);
},
// Creates the notification directory.
createStore: function(callback) {
var promise = OS.File.makeDir(NOTIFICATION_STORE_DIR, {
ignoreExisting: true
});
promise.then(
function onSuccess() {
this.createFile(callback);
}.bind(this),
function onFailure(reason) {
if (DEBUG) { debug("Directory creation failed:" + reason); }
callback && callback();
}
);
},
// Creates the notification file once the directory is created.
createFile: function(callback) {
var promise = OS.File.open(NOTIFICATION_STORE_PATH, {create: true});
promise.then(
function onSuccess(handle) {
callback && callback();
},
function onFailure(reason) {
if (DEBUG) { debug("File creation failed:" + reason); }
callback && callback();
}
);
},
// Save current notifications to the file.
save: function(callback) {
var data = gEncoder.encode(JSON.stringify(this.notifications));
var promise = OS.File.writeAtomic(NOTIFICATION_STORE_PATH, data);
promise.then(
function onSuccess() {
callback && callback();
},
function onFailure(reason) {
if (DEBUG) { debug("Save failed:" + reason); }
callback && callback();
}
);
},
// Helper function: callback will be called once file exists and/or is loaded.
ensureLoaded: function(callback) {
if (!this.loaded) {
this.load(callback);
} else {
callback();
}
},
receiveMessage: function(message) {
if (DEBUG) { debug("Received message:" + message.name); }
switch (message.name) {
case "Notification:GetAll":
this.queueTask("getall", message.data, function(notifications) {
message.target.sendAsyncMessage("Notification:GetAll:Return:OK", {
requestID: message.data.requestID,
notifications: notifications
});
});
break;
case "Notification:Save":
this.queueTask("save", message.data, function() {
message.target.sendAsyncMessage("Notification:Save:Return:OK", {
requestID: message.data.requestID
});
});
break;
case "Notification:Delete":
this.queueTask("delete", message.data, function() {
message.target.sendAsyncMessage("Notification:Delete:Return:OK", {
requestID: message.data.requestID
});
});
break;
default:
if (DEBUG) { debug("Invalid message name" + message.name); }
}
},
// We need to make sure any read/write operations are atomic,
// so use a queue to run each operation sequentially.
queueTask: function(operation, data, callback) {
if (DEBUG) { debug("Queueing task: " + operation); }
this.tasks.push({
operation: operation,
data: data,
callback: callback
});
// Only run immediately if we aren't currently running another task.
if (!this.runningTask) {
if (DEBUG) { dump("Task queue was not running, starting now..."); }
this.runNextTask();
}
},
runNextTask: function() {
if (this.tasks.length === 0) {
if (DEBUG) { dump("No more tasks to run, queue depleted"); }
this.runningTask = false;
return;
}
this.runningTask = true;
// Always make sure we are loaded before performing any read/write tasks.
this.ensureLoaded(function() {
var task = this.tasks.shift();
// Wrap the task callback to make sure we immediately
// run the next task after running the original callback.
var wrappedCallback = function() {
if (DEBUG) { debug("Finishing task: " + task.operation); }
task.callback.apply(this, arguments);
this.runNextTask();
}.bind(this);
switch (task.operation) {
case "getall":
this.taskGetAll(task.data, wrappedCallback);
break;
case "save":
this.taskSave(task.data, wrappedCallback);
break;
case "delete":
this.taskDelete(task.data, wrappedCallback);
break;
}
}.bind(this));
},
taskGetAll: function(data, callback) {
if (DEBUG) { debug("Task, getting all"); }
var origin = data.origin;
var notifications = [];
// Grab only the notifications for specified origin.
for (var i in this.notifications[origin]) {
notifications.push(this.notifications[origin][i]);
}
callback(notifications);
},
taskSave: function(data, callback) {
if (DEBUG) { debug("Task, saving"); }
var origin = data.origin;
var notification = data.notification;
if (!this.notifications[origin]) {
this.notifications[origin] = {};
this.byTag[origin] = {};
}
// We might have existing notification with this tag,
// if so we need to remove it before saving the new one.
if (notification.tag && this.byTag[origin][notification.tag]) {
var oldNotification = this.byTag[origin][notification.tag];
delete this.notifications[origin][oldNotification.id];
this.byTag[origin][notification.tag] = notification;
}
this.notifications[origin][notification.id] = notification;
this.save(callback);
},
taskDelete: function(data, callback) {
if (DEBUG) { debug("Task, deleting"); }
var origin = data.origin;
var id = data.id;
if (!this.notifications[origin]) {
if (DEBUG) { debug("No notifications found for origin: " + origin); }
return;
}
// Make sure we can find the notification to delete.
var oldNotification = this.notifications[origin][id];
if (!oldNotification) {
if (DEBUG) { debug("No notification found with id: " + id); }
return;
}
if (oldNotification.tag) {
delete this.byTag[origin][oldNotification.tag];
}
delete this.notifications[origin][id];
this.save(callback);
}
};
NotificationDB.init();

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

@ -1,174 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const DEBUG = false;
function debug(s) { dump("-*- NotificationStorage.js: " + s + "\n"); }
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const NOTIFICATIONSTORAGE_CID = "{37f819b0-0b5c-11e3-8ffd-0800200c9a66}";
const NOTIFICATIONSTORAGE_CONTRACTID = "@mozilla.org/notificationStorage;1";
XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
"@mozilla.org/childprocessmessagemanager;1",
"nsIMessageSender");
function NotificationStorage() {
// cache objects
this._notifications = {};
this._byTag = {};
this._cached = false;
this._requests = {};
this._requestCount = 0;
// Register for message listeners.
cpmm.addMessageListener("Notification:GetAll:Return:OK", this);
}
NotificationStorage.prototype = {
put: function(origin, id, title, dir, lang, body, tag, icon) {
if (DEBUG) { debug("PUT: " + id + ": " + title); }
var notification = {
id: id,
title: title,
dir: dir,
lang: lang,
body: body,
tag: tag,
icon: icon
};
this._notifications[id] = notification;
if (tag) {
// We might have existing notification with this tag,
// if so we need to remove it from our cache.
if (this._byTag[tag]) {
var oldNotification = this._byTag[tag];
delete this._notifications[oldNotification.id];
}
this._byTag[tag] = notification;
};
cpmm.sendAsyncMessage("Notification:Save", {
origin: origin,
notification: notification
});
},
get: function(origin, tag, callback) {
if (DEBUG) { debug("GET: " + tag); }
if (this._cached) {
this._fetchFromCache(tag, callback);
} else {
this._fetchFromDB(origin, tag, callback);
}
},
delete: function(origin, id) {
if (DEBUG) { debug("DELETE: " + id); }
var notification = this._notifications[id];
if (notification) {
if (notification.tag) {
delete this._byTag[notification.tag];
}
delete this._notifications[id];
}
cpmm.sendAsyncMessage("Notification:Delete", {
origin: origin,
id: id
});
},
receiveMessage: function(message) {
switch (message.name) {
case "Notification:GetAll:Return:OK":
var request = this._requests[message.data.requestID];
delete this._requests[message.data.requestID];
this._populateCache(message.data.notifications);
this._fetchFromCache(request.tag, request.callback);
break;
default:
if (DEBUG) debug("Unrecognized message: " + message.name);
break;
}
},
_fetchFromDB: function(origin, tag, callback) {
var request = {
origin: origin,
tag: tag,
callback: callback
};
var requestID = this._requestCount++;
this._requests[requestID] = request;
cpmm.sendAsyncMessage("Notification:GetAll", {
origin: origin,
requestID: requestID
});
},
_fetchFromCache: function(tag, callback) {
var notifications = [];
// If a tag was specified and we have a notification
// with this tag, return that. If no tag was specified
// simple return all stored notifications.
if (tag && this._byTag[tag]) {
notifications.push(this._byTag[tag]);
} else if (!tag) {
for (var id in this._notifications) {
notifications.push(this._notifications[id]);
}
}
// Pass each notification back separately.
notifications.forEach(function(notification) {
try {
callback.handle(notification.id,
notification.title,
notification.dir,
notification.lang,
notification.body,
notification.tag,
notification.icon);
} catch (e) {
if (DEBUG) { debug("Error calling callback handle: " + e); }
}
});
try {
callback.done();
} catch (e) {
if (DEBUG) { debug("Error calling callback done: " + e); }
}
},
_populateCache: function(notifications) {
notifications.forEach(function(notification) {
this._notifications[notification.id] = notification;
if (notification.tag) {
this._byTag[notification.tag] = notification;
}
}.bind(this));
this._cached = true;
},
classID : Components.ID(NOTIFICATIONSTORAGE_CID),
contractID : NOTIFICATIONSTORAGE_CONTRACTID,
QueryInterface: XPCOMUtils.generateQI([Ci.nsINotificationStorage,
Ci.nsIMessageListener]),
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NotificationStorage]);

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

@ -1,3 +0,0 @@
# NotificationStorage.js
component {37f819b0-0b5c-11e3-8ffd-0800200c9a66} NotificationStorage.js
contract @mozilla.org/notificationStorage;1 {37f819b0-0b5c-11e3-8ffd-0800200c9a66}

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

@ -6,15 +6,6 @@
MODULE = 'dom'
EXTRA_COMPONENTS += [
'NotificationStorage.js',
'NotificationStorage.manifest',
]
EXTRA_JS_MODULES += [
'NotificationDB.jsm'
]
EXPORTS.mozilla.dom += [
'DesktopNotification.h',
'Notification.h',

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

@ -75,12 +75,12 @@ NS_IMETHODIMP_(void) DOMStorageCacheBridge::Release(void)
// DOMStorageCache
DOMStorageCache::DOMStorageCache(const nsACString* aScope)
: mManager(nullptr)
, mScope(*aScope)
: mScope(*aScope)
, mMonitor("DOMStorageCache")
, mLoaded(false)
, mLoadResult(NS_OK)
, mInitialized(false)
, mPersistent(false)
, mSessionOnlyDataSetActive(false)
, mPreloadTelemetryRecorded(false)
{
@ -128,15 +128,17 @@ DOMStorageCache::Init(DOMStorageManager* aManager,
return;
}
mManager = aManager;
mInitialized = true;
mPrincipal = aPrincipal;
mPersistent = aPersistent;
mQuotaScope = aQuotaScope.IsEmpty() ? mScope : aQuotaScope;
if (mPersistent) {
mManager = aManager;
Preload();
}
mUsage = aManager->GetScopeUsage(mQuotaScope);
}
inline bool
@ -208,12 +210,8 @@ DOMStorageCache::ProcessUsageDelta(uint32_t aGetDataSetIndex, const int64_t aDel
}
// Now check eTLD+1 limit
GetDatabase();
if (sDatabase) {
DOMStorageUsage* usage = sDatabase->GetScopeUsage(mQuotaScope);
if (!usage->CheckAndSetETLD1UsageDelta(aGetDataSetIndex, aDelta)) {
return false;
}
if (mUsage && !mUsage->CheckAndSetETLD1UsageDelta(aGetDataSetIndex, aDelta)) {
return false;
}
// Update size in our data set
@ -235,7 +233,6 @@ DOMStorageCache::Preload()
}
sDatabase->AsyncPreload(this);
sDatabase->GetScopeUsage(mQuotaScope);
}
namespace { // anon

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

@ -20,6 +20,7 @@ namespace mozilla {
namespace dom {
class DOMStorage;
class DOMStorageUsage;
class DOMStorageManager;
class DOMStorageDBBridge;
@ -170,6 +171,10 @@ private:
// Cache could potentially overlive the manager, hence the hard ref.
nsRefPtr<DOMStorageManager> mManager;
// Reference to the usage counter object we check on for eTLD+1 quota limit.
// Obtained from the manager during initialization (Init method).
nsRefPtr<DOMStorageUsage> mUsage;
// Timer that holds this cache alive for a while after it has been preloaded.
nsCOMPtr<nsITimer> mKeepAliveTimer;
@ -227,6 +232,8 @@ private:
class DOMStorageUsageBridge
{
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DOMStorageUsageBridge)
virtual ~DOMStorageUsageBridge() {}
virtual const nsCString& Scope() = 0;

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

@ -37,21 +37,6 @@ DOMStorageDBBridge::DOMStorageDBBridge()
{
}
DOMStorageUsage*
DOMStorageDBBridge::GetScopeUsage(const nsACString& aScope)
{
DOMStorageUsage* usage;
if (mUsages.Get(aScope, &usage)) {
return usage;
}
usage = new DOMStorageUsage(aScope);
AsyncGetUsage(usage);
mUsages.Put(aScope, usage);
return usage;
}
DOMStorageDBThread::DOMStorageDBThread()
: mThread(nullptr)

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

@ -81,13 +81,6 @@ public:
// Get the complete list of scopes having data
virtual void GetScopesHavingData(InfallibleTArray<nsCString>* aScopes) = 0;
// Returns object keeping usage cache for the scope.
DOMStorageUsage* GetScopeUsage(const nsACString& aScope);
protected:
// Keeps usage cache objects for eTLD+1 scopes we have touched.
nsClassHashtable<nsCStringHashKey, DOMStorageUsage> mUsages;
};
// The implementation of the the database engine, this directly works
@ -157,7 +150,7 @@ public:
friend class PendingOperations;
OperationType mType;
nsRefPtr<DOMStorageCacheBridge> mCache;
DOMStorageUsageBridge* mUsage;
nsRefPtr<DOMStorageUsageBridge> mUsage;
nsString mKey;
nsString mValue;
nsCString mScope;

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

@ -253,12 +253,7 @@ DOMStorageDBChild::RecvLoadDone(const nsCString& aScope, const nsresult& aRv)
bool
DOMStorageDBChild::RecvLoadUsage(const nsCString& aScope, const int64_t& aUsage)
{
DOMStorageDBBridge* db = DOMStorageCache::GetDatabase();
if (!db) {
return false;
}
DOMStorageUsageBridge* scopeUsage = db->GetScopeUsage(aScope);
nsRefPtr<DOMStorageUsageBridge> scopeUsage = mManager->GetScopeUsage(aScope);
scopeUsage->LoadUsage(aUsage);
return true;
}
@ -404,7 +399,7 @@ DOMStorageDBParent::RecvAsyncGetUsage(const nsCString& aScope)
}
// The object releases it self in LoadUsage method
UsageParentBridge* usage = new UsageParentBridge(this, aScope);
nsRefPtr<UsageParentBridge> usage = new UsageParentBridge(this, aScope);
db->AsyncGetUsage(usage);
return true;
}
@ -733,7 +728,6 @@ DOMStorageDBParent::UsageParentBridge::LoadUsage(const int64_t aUsage)
{
nsRefPtr<UsageRunnable> r = new UsageRunnable(mParent, mScope, aUsage);
NS_DispatchToMainThread(r);
delete this;
}
} // ::dom

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

@ -269,6 +269,28 @@ DOMStorageManager::GetCache(const nsACString& aScope) const
return entry->cache();
}
already_AddRefed<DOMStorageUsage>
DOMStorageManager::GetScopeUsage(const nsACString& aScope)
{
nsRefPtr<DOMStorageUsage> usage;
if (mUsages.Get(aScope, &usage)) {
return usage.forget();
}
usage = new DOMStorageUsage(aScope);
if (mType == LocalStorage) {
DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
if (db) {
db->AsyncGetUsage(usage);
}
}
mUsages.Put(aScope, usage);
return usage.forget();
}
already_AddRefed<DOMStorageCache>
DOMStorageManager::PutCache(const nsACString& aScope,
nsIPrincipal* aPrincipal)
@ -283,7 +305,7 @@ DOMStorageManager::PutCache(const nsACString& aScope,
case SessionStorage:
// Lifetime handled by the manager, don't persist
entry->HardRef();
cache->Init(nullptr, false, aPrincipal, quotaScope);
cache->Init(this, false, aPrincipal, quotaScope);
break;
case LocalStorage:

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

@ -13,6 +13,8 @@
#include "DOMStorageCache.h"
#include "nsTHashtable.h"
#include "nsDataHashtable.h"
#include "nsHashKeys.h"
namespace mozilla {
namespace dom {
@ -35,6 +37,8 @@ public:
static uint32_t GetQuota();
// Gets (but not ensures) cache for the given scope
DOMStorageCache* GetCache(const nsACString& aScope) const;
// Returns object keeping usage cache for the scope.
already_AddRefed<DOMStorageUsage> GetScopeUsage(const nsACString& aScope);
protected:
DOMStorageManager(nsPIDOMStorage::StorageType aType);
@ -97,6 +101,9 @@ private:
void* aClosure);
protected:
// Keeps usage cache objects for eTLD+1 scopes we have touched.
nsDataHashtable<nsCStringHashKey, nsRefPtr<DOMStorageUsage> > mUsages;
friend class DOMStorageCache;
// Releases cache since it is no longer referrered by any DOMStorage object.
virtual void DropCache(DOMStorageCache* aCache);

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

@ -29,3 +29,7 @@ DIRS += [
if CONFIG['MOZ_GAMEPAD']:
DIRS += ['gamepad']
#needs IPC support, also tests do not run successfully in Firefox for now
#if CONFIG['MOZ_BUILD_APP'] != 'mobile':
# DIRS += ['notification']

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

@ -1,81 +0,0 @@
var MockServices = (function () {
"use strict";
const MOCK_ALERTS_CID = SpecialPowers.wrap(SpecialPowers.Components)
.ID("{48068bc2-40ab-4904-8afd-4cdfb3a385f3}");
const ALERTS_SERVICE_CONTRACT_ID = "@mozilla.org/alerts-service;1";
const MOCK_SYSTEM_ALERTS_CID = SpecialPowers.wrap(SpecialPowers.Components)
.ID("{e86d888c-e41b-4b78-9104-2f2742a532de}");
const SYSTEM_ALERTS_SERVICE_CONTRACT_ID = "@mozilla.org/system-alerts-service;1";
var registrar = SpecialPowers.wrap(SpecialPowers.Components).manager
.QueryInterface(SpecialPowers.Ci.nsIComponentRegistrar);
var activeNotifications = Object.create(null);
var mockAlertsService = {
showAlertNotification: function(imageUrl, title, text, textClickable,
cookie, alertListener, name) {
var listener = SpecialPowers.wrap(alertListener);
activeNotifications[name] = {
listener: listener,
cookie: cookie
};
// fake async alert show event
setTimeout(function () {
listener.observe(null, "alertshow", cookie);
}, 100);
// ?? SpecialPowers.wrap(alertListener).observe(null, "alertclickcallback", cookie);
},
showAppNotification: function(imageUrl, title, text, textClickable,
manifestURL, alertListener, name) {
this.showAlertNotification(imageUrl, title, text, textClickable, "", alertListener, name);
},
closeAlert: function(name) {
var notification = activeNotifications[name];
if (notification) {
notification.listener.observe(null, "alertfinished", notification.cookie);
delete activeNotifications[name];
}
},
QueryInterface: function(aIID) {
if (SpecialPowers.wrap(aIID).equals(SpecialPowers.Ci.nsISupports) ||
SpecialPowers.wrap(aIID).equals(SpecialPowers.Ci.nsIAlertsService)) {
return this;
}
throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE;
},
createInstance: function(aOuter, aIID) {
if (aOuter != null) {
throw SpecialPowers.Components.results.NS_ERROR_NO_AGGREGATION;
}
return this.QueryInterface(aIID);
}
};
mockAlertsService = SpecialPowers.wrapCallbackObject(mockAlertsService);
// MockServices API
return {
register: function () {
registrar.registerFactory(MOCK_ALERTS_CID, "alerts service",
ALERTS_SERVICE_CONTRACT_ID,
mockAlertsService);
registrar.registerFactory(MOCK_SYSTEM_ALERTS_CID, "system alerts service",
SYSTEM_ALERTS_SERVICE_CONTRACT_ID,
mockAlertsService);
},
unregister: function () {
registrar.unregisterFactory(MOCK_ALERTS_CID, mockAlertsService);
registrar.unregisterFactory(MOCK_SYSTEM_ALERTS_CID, mockAlertsService);
},
};
})();

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

@ -1,73 +0,0 @@
var NotificationTest = (function () {
"use strict";
function info(msg, name) {
SimpleTest.info("::Notification Tests::" + (name || ""), msg);
}
function setup_testing_env() {
SimpleTest.waitForExplicitFinish();
// turn on testing pref (used by notification.cpp, and mock the alerts
SpecialPowers.setBoolPref("notification.prompt.testing", true);
}
function teardown_testing_env() {
SimpleTest.finish();
}
function executeTests(tests, callback) {
// context is `this` object in test functions
// it can be used to track data between tests
var context = {};
(function executeRemainingTests(remainingTests) {
if (!remainingTests.length) {
return callback();
}
var nextTest = remainingTests.shift();
var finishTest = executeRemainingTests.bind(null, remainingTests);
var startTest = nextTest.call.bind(nextTest, context, finishTest);
try {
startTest();
// if no callback was defined for test function,
// we must manually invoke finish to continue
if (nextTest.length === 0) {
finishTest();
}
} catch (e) {
ok(false, "Test threw exception!");
finishTest();
}
})(tests);
}
// NotificationTest API
return {
run: function (tests, callback) {
setup_testing_env();
addLoadEvent(function () {
executeTests(tests, function () {
teardown_testing_env();
callback && callback();
});
});
},
allowNotifications: function () {
SpecialPowers.setBoolPref("notification.prompt.testing.allow", true);
},
denyNotifications: function () {
SpecialPowers.setBoolPref("notification.prompt.testing.allow", false);
},
clickNotification: function (notification) {
// TODO: how??
},
info: info
};
})();

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

@ -1,6 +0,0 @@
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

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

@ -1,7 +1,10 @@
[DEFAULT]
support-files =
MockServices.js
NotificationTest.js
create_notification.html
notification_common.js
[test_notification_basics.html]
[test_notification_storage.html]
[test_basic_notification.html]
[test_basic_notification_click.html]
[test_leak_windowClose.html]
[test_notification_tag.html]
[test_web_notifications.html]

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

@ -1,115 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Notification Basics</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="MockServices.js"></script>
<script type="text/javascript" src="NotificationTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test"></pre>
<script type="text/javascript">
var info = NotificationTest.info;
var steps = [
function () {
info("Test notification spec");
ok(Notification, "Notification constructor exists");
ok(Notification.permission, "Notification.permission exists");
ok(Notification.requestPermission, "Notification.requestPermission exists");
ok(Notification.get, "Notification.get exists");
},
function () {
info("Test blank requestPermission");
Notification.requestPermission();
},
function (done) {
info("Test requestPermission deny");
NotificationTest.denyNotifications();
Notification.requestPermission(function(perm) {
is(perm, "denied", "Permission should be denied.");
is(Notification.permission, "denied", "Permission should be denied.");
done();
});
},
function (done) {
info("Test requestPermission grant");
NotificationTest.allowNotifications();
Notification.requestPermission(function (perm) {
is(perm, "granted", "Permission should be granted.");
is(Notification.permission, "granted", "Permission should be granted");
done();
});
},
function () {
info("Test invalid requestPermission");
try {
Notification.requestPermission({});
ok(false, "Non callable arg to requestPermission should throw");
} catch (e) {
ok(true, "Non callable arg to requestPermission should throw");
}
},
function (done) {
info("Test create notification");
var options = {
dir: "auto",
lang: "",
body: "This is a notification body",
tag: "sometag",
icon: "icon.png"
};
var notification = new Notification("This is a title", options);
ok(notification, "Notification exists");
is(notification.onclick, null, "onclick() should be null");
is(notification.onshow, null, "onshow() should be null");
is(notification.onerror, null, "onerror() should be null");
is(notification.onclose, null, "onclose() should be null");
is(typeof notification.close, "function", "close() should exist");
is(notification.dir, options.dir, "auto should get set");
is(notification.lang, options.lang, "lang should get set");
is(notification.body, options.body, "body should get set");
is(notification.tag, options.tag, "tag should get set");
is(notification.icon, options.icon, "icon should get set");
// store notification in test context
this.notification = notification;
notification.onshow = function () {
ok(true, "onshow handler should be called");
done();
};
},
function (done) {
info("Test closing a notification");
var notification = this.notification;
notification.onclose = function () {
ok(true, "onclose handler should be called");
done();
};
notification.close();
},
];
MockServices.register();
NotificationTest.run(steps, function () {
MockServices.unregister();
});
</script>
</body>
</html>

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

@ -1,132 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Notification Basics</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="MockServices.js"></script>
<script type="text/javascript" src="NotificationTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test"></pre>
<script type="text/javascript">
function deleteAllNotifications() {
var promise = Notification.get();
promise.then(function (notifications) {
notifications.forEach(function(notification) {
notification.close();
});
});
}
var info = NotificationTest.info;
var steps = [
function (done) {
info("Test that Notifcation.get fulfills the promise");
var promise = Notification.get();
ok(promise.then, "should return a promise");
// Create a new notification to make sure
// Notification.get() works while creating
var notification = new Notification("this is a test");
promise.then(function () {
ok(true, "promise should be fulfilled");
done();
});
},
deleteAllNotifications,
function (done) {
info("Test adding a notification, and making sure get returns it");
NotificationTest.allowNotifications();
var options = {
dir: "auto",
lang: "",
body: "This is a notification body",
tag: "sometag",
icon: "icon.png"
};
var notification = new Notification("This is a title", options);
var promise = Notification.get();
promise.then(function (notifications) {
ok(notifications.length, "should return notifications");
for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i];
if (notification.tag === options.tag) {
ok(true, "should contain newly created notification");
for (var key in options) {
is(notification[key], options[key], key + " property should match");
}
notification.close();
return;
}
}
ok(false, "should contain newly created notification");
notification.close();
});
notification.onclose = done;
},
function (done) {
info("Testing fetching notification by tag filter");
var n1 = new Notification("title1", {tag: "tag1"});
var n2 = new Notification("title2", {tag: "tag2"});
var n3 = new Notification("title3", {tag: "tag3"});
var promise = Notification.get({tag: "tag3"});
promise.then(function (notifications) {
var notification = notifications[0];
is(notifications.length, 1, "should return 1 notification");
is(notifications[0].title, "title3", "titles should match");
is(notifications[0].tag, "tag3", "tags should match");
var closeCount = 0;
var waitForAll = function () {
if (++closeCount >= 3) {
done();
}
};
n1.onclose = waitForAll;
n2.onclose = waitForAll;
n3.onclose = waitForAll;
n1.close();
n2.close();
n3.close();
});
},
deleteAllNotifications,
function (done) {
info("Testing fetching no notifications");
var promise = Notification.get();
promise.then(function (notifications) {
is(notifications.length, 0, "should return 0 notifications");
done();
});
},
function (done) {
info("Testing fetching multiple notifications");
var n1 = new Notification("title1");
var n2 = new Notification("title2");
var n3 = new Notification("title3");
var promise = Notification.get();
promise.then(function (notifications) {
is(notifications.length, 3, "should return 2 notifications");
done();
});
}
];
MockServices.register();
NotificationTest.run(steps, function () {
MockServices.unregister();
});
</script>
</body>
</html>

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

@ -0,0 +1,100 @@
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=782211
-->
<head>
<title>Bug 782211</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="notification_common.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=782211">Bug 782211</a>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
</pre>
<script type="text/javascript">
if (window.Notification) {
SimpleTest.waitForExplicitFinish();
function showNotifications() {
// Make sure callback is called.
Notification.requestPermission(function(perm) {
is(perm, "granted", "Permission should be granted.");
is(Notification.permission, "granted", "Permission should be granted.");
callbackCalled();
});
// Make sure nothing bad happens when requestPermission is called without a callback.
Notification.requestPermission();
try {
Notification.requestPermission({});
ok(false, "Non callable arugment to request permission should throw exception.");
} catch (ex) {
ok(true, "Non callable arugment to request permission should throw exception.");
}
var title = "This is a title";
var notification = new Notification(title);
is(notification.title, title, "Title should be set");
is(notification.dir, "auto", "Dir should default to 'auto'");
is(notification.lang, "", "Lang should not be set");
is(notification.body, "", "Body should not be set");
is(notification.tag, "", "Tag should not be set");
var options = {
dir: "auto",
lang: "",
body: "This is a notification body",
tag: "sometag"
};
var notification = new Notification(title, options);
is(notification.title, title, "Title should be set");
is(notification.dir, options.dir, "Dir should be set");
is(notification.lang, options.lang, "Lang should be set");
is(notification.body, options.body, "Body should be set");
is(notification.tag, options.tag, "Tag should be set");
notification.onclose = function() {
ok(true, "Notification should be closed.");
callbackCalled();
};
notification.onshow = function() {
ok(true, "Notification should be shown.");
notification.close();
callbackCalled();
};
notification.onerror = function() {
ok(false, "Failed to show notification.");
reset_notifications();
SimpleTest.finish();
};
var numCallbacksCalled = 0;
function callbackCalled() {
numCallbacksCalled++;
if (numCallbacksCalled == 3) {
reset_notifications();
SimpleTest.finish();
}
}
}
setup_notifications(true, true, showNotifications);
} else {
ok(true, "Notifications are not enabled on the platform.");
}
</script>
</body>
</html>

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

@ -19,9 +19,6 @@ interface Notification : EventTarget {
[Throws]
static void requestPermission(optional NotificationPermissionCallback permissionCallback);
[Throws]
static Promise get(optional GetNotificationOptions filter);
attribute EventHandler onclick;
attribute EventHandler onshow;
@ -55,12 +52,8 @@ dictionary NotificationOptions {
NotificationDirection dir = "auto";
DOMString lang = "";
DOMString body = "";
DOMString tag = "";
DOMString icon = "";
};
dictionary GetNotificationOptions {
DOMString tag;
DOMString icon = "";
};
enum NotificationPermission {

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

@ -458,26 +458,20 @@ MacIOSurface::CGLTexImageIOSurface2D(void *c)
}
CGColorSpaceRef CreateSystemColorSpace() {
CMProfileRef system_profile = nullptr;
CGColorSpaceRef cspace = nullptr;
if (::CMGetSystemProfile(&system_profile) == noErr) {
// Create a colorspace with the systems profile
cspace = ::CGColorSpaceCreateWithPlatformColorSpace(system_profile);
::CMCloseProfile(system_profile);
} else {
// Default to generic
cspace = ::CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
}
return cspace;
CGColorSpaceRef cspace = ::CGDisplayCopyColorSpace(::CGMainDisplayID());
if (!cspace) {
cspace = ::CGColorSpaceCreateDeviceRGB();
}
return cspace;
}
CGContextRef MacIOSurface::CreateIOSurfaceContext() {
CGColorSpaceRef cspace = CreateSystemColorSpace();
CGContextRef ref = MacIOSurfaceLib::IOSurfaceContextCreate(mIOSurfacePtr,
GetDevicePixelWidth(),
GetDevicePixelHeight(),
8, 32, CreateSystemColorSpace(), 0x2002);
8, 32, cspace, 0x2002);
::CGColorSpaceRelease(cspace);
return ref;
}
@ -639,9 +633,7 @@ nsresult nsCARenderer::SetupRenderer(void *aCALayer, int aWidth, int aHeight,
dataProvider, nullptr, true, kCGRenderingIntentDefault);
::CGDataProviderRelease(dataProvider);
if (colorSpace) {
::CGColorSpaceRelease(colorSpace);
}
::CGColorSpaceRelease(colorSpace);
if (!mCGImage) {
mUnsupportedWidth = aWidth;
mUnsupportedHeight = aHeight;

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

@ -90,17 +90,17 @@ const char* const TraceLogging::typeName[] = {
"e,b", // engine baseline
"e,o" // engine ionmonkey
};
TraceLogging* TraceLogging::loggers[] = {NULL, NULL, NULL};
TraceLogging* TraceLogging::loggers[] = {nullptr, nullptr, nullptr};
bool TraceLogging::atexitSet = false;
uint64_t TraceLogging::startupTime = 0;
TraceLogging::TraceLogging(Logger id)
: nextTextId(1),
entries(NULL),
entries(nullptr),
curEntry(0),
numEntries(1000000),
fileno(0),
out(NULL),
out(nullptr),
id(id)
{
textMap.init();
@ -111,12 +111,12 @@ TraceLogging::~TraceLogging()
if (entries) {
flush();
free(entries);
entries = NULL;
entries = nullptr;
}
if (out) {
fclose(out);
out = NULL;
out = nullptr;
}
}
@ -137,7 +137,7 @@ TraceLogging::grow()
}
void
TraceLogging::log(Type type, const char* text /* = NULL */, unsigned int number /* = 0 */)
TraceLogging::log(Type type, const char* text /* = nullptr */, unsigned int number /* = 0 */)
{
uint64_t now = rdtsc() - startupTime;
@ -149,7 +149,7 @@ TraceLogging::log(Type type, const char* text /* = NULL */, unsigned int number
}
uint32_t textId = 0;
char *text_ = NULL;
char *text_ = nullptr;
if (text) {
TextHashMap::AddPtr p = textMap.lookupForAdd(text);
@ -248,9 +248,9 @@ TraceLogging::flush()
exit(-1);
}
if (entries[i].text() != NULL) {
if (entries[i].text() != nullptr) {
free(entries[i].text());
entries[i].text_ = NULL;
entries[i].text_ = nullptr;
}
}
curEntry = 0;
@ -279,7 +279,7 @@ TraceLogging::releaseLoggers()
continue;
delete loggers[i];
loggers[i] = NULL;
loggers[i] = nullptr;
}
}

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

@ -102,7 +102,7 @@ class TraceLogging
TraceLogging(Logger id);
~TraceLogging();
void log(Type type, const char* text = NULL, unsigned int number = 0);
void log(Type type, const char* text = nullptr, unsigned int number = 0);
void log(Type type, const JS::CompileOptions &options);
void log(Type type, JSScript* script);
void log(const char* log);

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

@ -830,7 +830,7 @@ DumpHeapComplete(JSContext *cx, unsigned argc, jsval *vp)
CallArgs args = CallArgsFromVp(argc, vp);
DumpHeapNurseryBehaviour nurseryBehaviour = js::IgnoreNurseryObjects;
FILE *dumpFile = NULL;
FILE *dumpFile = nullptr;
unsigned i = 0;
if (argc > i) {

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

@ -97,6 +97,9 @@ js::Nursery::allocate(size_t size)
{
JS_ASSERT(!runtime()->isHeapBusy());
/* Ensure there's enough space to replace the contents with a RelocationOverlay. */
JS_ASSERT(size >= sizeof(RelocationOverlay));
if (position() + size > currentEnd()) {
if (currentChunk_ + 1 == numActiveChunks_)
return nullptr;

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

@ -0,0 +1,3 @@
if (getpda) {
getpda();
}

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

@ -5081,7 +5081,7 @@ class ParallelCompilationGuard
{
WorkerThreadState *parallelState_;
public:
ParallelCompilationGuard() : parallelState_(NULL) {}
ParallelCompilationGuard() : parallelState_(nullptr) {}
~ParallelCompilationGuard() {
if (parallelState_) {
JS_ASSERT(parallelState_->asmJSCompilationInProgress == true);

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

@ -7777,7 +7777,7 @@ IonBuilder::freezePropTypeSets(types::TemporaryTypeSet *types,
continue;
// Walk the prototype chain. Everyone has to have the property, since we
// just checked, so propSet cannot be NULL.
// just checked, so propSet cannot be nullptr.
while (true) {
types::HeapTypeSetKey property = type->property(NameToId(name));
JS_ALWAYS_TRUE(!property.notEmpty(constraints()));

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

@ -687,7 +687,7 @@ class IonBuilder : public MIRGenerator
}
bool isInlineBuilder() const {
return callerBuilder_ != NULL;
return callerBuilder_ != nullptr;
}
private:

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

@ -273,8 +273,8 @@ class Range : public TempObject {
// Construct a range from the given raw values.
Range(int32_t l, bool lb, int32_t h, bool hb, bool f, uint16_t e)
: symbolicLower_(NULL),
symbolicUpper_(NULL)
: symbolicLower_(nullptr),
symbolicUpper_(nullptr)
{
rawInitialize(l, lb, h, hb, f, e);
}

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

@ -53,14 +53,14 @@ class TempAllocPolicy
void *malloc_(size_t bytes) {
void *p = js_malloc(bytes);
if (JS_UNLIKELY(!p))
p = onOutOfMemory(NULL, bytes);
p = onOutOfMemory(nullptr, bytes);
return p;
}
void *calloc_(size_t bytes) {
void *p = js_calloc(bytes);
if (JS_UNLIKELY(!p))
p = onOutOfMemory(NULL, bytes);
p = onOutOfMemory(nullptr, bytes);
return p;
}

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

@ -440,7 +440,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx)
}
unsigned savedCount = 0;
LoopAnalysis *loop = NULL;
LoopAnalysis *loop = nullptr;
uint32_t offset = script_->length - 1;
while (offset < script_->length) {
@ -525,7 +525,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx)
setOOM(cx);
return;
}
var.saved = NULL;
var.saved = nullptr;
saved[i--] = saved[--savedCount];
}
savedCount = 0;
@ -617,7 +617,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx)
setOOM(cx);
return;
}
var.saved = NULL;
var.saved = nullptr;
saved[i--] = saved[--savedCount];
} else if (loop && !var.savedEnd) {
/*
@ -680,7 +680,7 @@ ScriptAnalysis::addVariable(JSContext *cx, LifetimeVariable &var, unsigned offse
setOOM(cx);
return;
}
var.saved = NULL;
var.saved = nullptr;
}
}
@ -730,7 +730,7 @@ ScriptAnalysis::killVariable(JSContext *cx, LifetimeVariable &var, unsigned offs
} else {
var.saved = var.lifetime;
var.savedEnd = 0;
var.lifetime = NULL;
var.lifetime = nullptr;
saved[savedCount++] = &var;
}
@ -1510,7 +1510,7 @@ ScriptAnalysis::freezeNewValues(JSContext *cx, uint32_t offset)
Bytecode &code = getCode(offset);
Vector<SlotValue> *pending = code.pendingValues;
code.pendingValues = NULL;
code.pendingValues = nullptr;
unsigned count = pending->length();
if (count == 0) {

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

@ -336,7 +336,7 @@ struct LifetimeVariable
return segment;
segment = segment->next;
}
return NULL;
return nullptr;
}
/*

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

@ -21,7 +21,7 @@ END_TEST(selfTest_NaNsAreSame)
BEGIN_TEST(selfTest_globalHasNoParent)
{
CHECK(JS_GetParent(global) == NULL);
CHECK(JS_GetParent(global) == nullptr);
return true;
}
END_TEST(selfTest_globalHasNoParent)

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

@ -33,13 +33,13 @@ const JSClass addPropertyClass = {
BEGIN_TEST(testAddPropertyHook)
{
JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
CHECK(obj);
JS::RootedValue proto(cx, OBJECT_TO_JSVAL(obj));
JS_InitClass(cx, global, obj, &addPropertyClass, NULL, 0, NULL, NULL, NULL,
NULL);
JS_InitClass(cx, global, obj, &addPropertyClass, nullptr, 0, nullptr, nullptr, nullptr,
nullptr);
obj = JS_NewArrayObject(cx, 0, NULL);
obj = JS_NewArrayObject(cx, 0, nullptr);
CHECK(obj);
JS::RootedValue arr(cx, OBJECT_TO_JSVAL(obj));
@ -48,7 +48,7 @@ BEGIN_TEST(testAddPropertyHook)
JSPROP_ENUMERATE));
for (int i = 0; i < expectedCount; ++i) {
obj = JS_NewObject(cx, &addPropertyClass, NULL, NULL);
obj = JS_NewObject(cx, &addPropertyClass, nullptr, nullptr);
CHECK(obj);
JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj));
JS::RootedObject arrObj(cx, JSVAL_TO_OBJECT(arr));

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

@ -46,7 +46,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal)
// Modifying the underlying data should update the value returned through the view
uint8_t *data = JS_GetArrayBufferData(obj);
CHECK(data != NULL);
CHECK(data != nullptr);
*reinterpret_cast<uint32_t*>(data) = MAGIC_VALUE_2;
CHECK(JS_GetElement(cx, view, 0, &v));
CHECK_SAME(v, INT_TO_JSVAL(MAGIC_VALUE_2));
@ -54,8 +54,8 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal)
// Steal the contents
void *contents;
CHECK(JS_StealArrayBufferContents(cx, obj, &contents, &data));
CHECK(contents != NULL);
CHECK(data != NULL);
CHECK(contents != nullptr);
CHECK(data != nullptr);
// Check that the original ArrayBuffer is neutered
CHECK_EQUAL(JS_GetArrayBufferByteLength(obj), 0);
@ -78,11 +78,11 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal)
data = JS_GetArrayBufferData(obj);
JS::RootedObject dstview(cx, JS_NewInt32ArrayWithBuffer(cx, dst, 0, -1));
CHECK(dstview != NULL);
CHECK(dstview != nullptr);
CHECK_EQUAL(JS_GetArrayBufferByteLength(dst), size);
data = JS_GetArrayBufferData(dst);
CHECK(data != NULL);
CHECK(data != nullptr);
CHECK_EQUAL(*reinterpret_cast<uint32_t*>(data), MAGIC_VALUE_2);
CHECK(JS_GetElement(cx, dstview, 0, &v));
CHECK_SAME(v, INT_TO_JSVAL(MAGIC_VALUE_2));
@ -105,7 +105,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList)
// No views
buffer = JS_NewArrayBuffer(cx, 2000);
buffer = NULL;
buffer = nullptr;
GC(cx);
// One view.
@ -115,15 +115,15 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList)
void *contents;
uint8_t *data;
CHECK(JS_StealArrayBufferContents(cx, buffer, &contents, &data));
CHECK(contents != NULL);
CHECK(data != NULL);
JS_free(NULL, contents);
CHECK(contents != nullptr);
CHECK(data != nullptr);
JS_free(nullptr, contents);
GC(cx);
CHECK(isNeutered(view));
CHECK(isNeutered(buffer));
view = NULL;
view = nullptr;
GC(cx);
buffer = NULL;
buffer = nullptr;
GC(cx);
}
@ -135,7 +135,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList)
JS::RootedObject view2(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200));
// Remove, re-add a view
view2 = NULL;
view2 = nullptr;
GC(cx);
view2 = JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200);
@ -143,19 +143,19 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList)
void *contents;
uint8_t *data;
CHECK(JS_StealArrayBufferContents(cx, buffer, &contents, &data));
CHECK(contents != NULL);
CHECK(data != NULL);
JS_free(NULL, contents);
CHECK(contents != nullptr);
CHECK(data != nullptr);
JS_free(nullptr, contents);
CHECK(isNeutered(view1));
CHECK(isNeutered(view2));
CHECK(isNeutered(buffer));
view1 = NULL;
view1 = nullptr;
GC(cx);
view2 = NULL;
view2 = nullptr;
GC(cx);
buffer = NULL;
buffer = nullptr;
GC(cx);
}

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

@ -20,7 +20,8 @@ BEGIN_TEST(test_BindCallable)
CHECK(newCallable);
JS::RootedValue retval(cx);
bool called = JS_CallFunctionValue(cx, NULL, OBJECT_TO_JSVAL(newCallable), 0, NULL, retval.address());
bool called = JS_CallFunctionValue(cx, nullptr, OBJECT_TO_JSVAL(newCallable), 0, nullptr,
retval.address());
CHECK(called);
CHECK(JSVAL_IS_INT(retval));

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

@ -38,7 +38,7 @@ wrap(JSContext *cx, JS::HandleObject toWrap, JS::HandleObject target)
JSAutoCompartment ac(cx, target);
JS::RootedObject wrapper(cx, toWrap);
if (!JS_WrapObject(cx, wrapper.address()))
return NULL;
return nullptr;
return wrapper;
}
@ -67,9 +67,9 @@ BEGIN_TEST(testBug604087)
{
JS::RootedObject outerObj(cx, js::Wrapper::New(cx, global, global->getProto(), global,
&OuterWrapper::singleton));
JS::RootedObject compartment2(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject compartment3(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject compartment4(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject compartment2(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
JS::RootedObject compartment3(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
JS::RootedObject compartment4(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
JS::RootedObject c2wrapper(cx, wrap(cx, outerObj, compartment2));
CHECK(c2wrapper);
@ -82,7 +82,7 @@ BEGIN_TEST(testBug604087)
JS::RootedObject c4wrapper(cx, wrap(cx, outerObj, compartment4));
CHECK(c4wrapper);
c4wrapper->as<js::ProxyObject>().setExtra(0, js::Int32Value(4));
compartment4 = c4wrapper = NULL;
compartment4 = c4wrapper = nullptr;
JS::RootedObject next(cx);
{

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

@ -44,10 +44,10 @@ CustomMethod(JSContext *cx, unsigned argc, Value *vp)
BEGIN_TEST(test_CallNonGenericMethodOnProxy)
{
// Create the first global object and compartment
JS::RootedObject globalA(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject globalA(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
CHECK(globalA);
JS::RootedObject customA(cx, JS_NewObject(cx, &CustomClass, NULL, NULL));
JS::RootedObject customA(cx, JS_NewObject(cx, &CustomClass, nullptr, nullptr));
CHECK(customA);
JS_SetReservedSlot(customA, CUSTOM_SLOT, Int32Value(17));
@ -55,17 +55,17 @@ BEGIN_TEST(test_CallNonGenericMethodOnProxy)
CHECK(customMethodA);
JS::RootedValue rval(cx);
CHECK(JS_CallFunction(cx, customA, customMethodA, 0, NULL, rval.address()));
CHECK(JS_CallFunction(cx, customA, customMethodA, 0, nullptr, rval.address()));
CHECK_SAME(rval, Int32Value(17));
// Now create the second global object and compartment...
{
JS::RootedObject globalB(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject globalB(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
CHECK(globalB);
// ...and enter it.
JSAutoCompartment enter(cx, globalB);
JS::RootedObject customB(cx, JS_NewObject(cx, &CustomClass, NULL, NULL));
JS::RootedObject customB(cx, JS_NewObject(cx, &CustomClass, nullptr, nullptr));
CHECK(customB);
JS_SetReservedSlot(customB, CUSTOM_SLOT, Int32Value(42));
@ -73,14 +73,14 @@ BEGIN_TEST(test_CallNonGenericMethodOnProxy)
CHECK(customMethodB);
JS::RootedValue rval(cx);
CHECK(JS_CallFunction(cx, customB, customMethodB, 0, NULL, rval.address()));
CHECK(JS_CallFunction(cx, customB, customMethodB, 0, nullptr, rval.address()));
CHECK_SAME(rval, Int32Value(42));
JS::RootedObject wrappedCustomA(cx, customA);
CHECK(JS_WrapObject(cx, wrappedCustomA.address()));
JS::RootedValue rval2(cx);
CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, 0, NULL, rval2.address()));
CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, 0, nullptr, rval2.address()));
CHECK_SAME(rval, Int32Value(42));
}

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

@ -22,8 +22,8 @@ const JSClass global_class = {
JS_ConvertStub
};
JSObject *trusted_glob = NULL;
JSObject *trusted_fun = NULL;
JSObject *trusted_glob = nullptr;
JSObject *trusted_fun = nullptr;
bool
CallTrusted(JSContext *cx, unsigned argc, jsval *vp)
@ -34,8 +34,8 @@ CallTrusted(JSContext *cx, unsigned argc, jsval *vp)
bool ok = false;
{
JSAutoCompartment ac(cx, trusted_glob);
ok = JS_CallFunctionValue(cx, NULL, JS::ObjectValue(*trusted_fun),
0, NULL, vp);
ok = JS_CallFunctionValue(cx, nullptr, JS::ObjectValue(*trusted_fun),
0, nullptr, vp);
}
JS_RestoreFrameChain(cx);
return ok;
@ -89,7 +89,7 @@ BEGIN_TEST(testChromeBuffer)
bytes, strlen(bytes), "", 0));
JS::RootedValue rval(cx);
CHECK(JS_CallFunction(cx, NULL, fun, 1, v.address(), rval.address()));
CHECK(JS_CallFunction(cx, nullptr, fun, 1, v.address(), rval.address()));
CHECK(JSVAL_TO_INT(rval) == 100);
}
@ -126,7 +126,7 @@ BEGIN_TEST(testChromeBuffer)
bytes, strlen(bytes), "", 0));
JS::RootedValue rval(cx);
CHECK(JS_CallFunction(cx, NULL, fun, 1, v.address(), rval.address()));
CHECK(JS_CallFunction(cx, nullptr, fun, 1, v.address(), rval.address()));
bool match;
CHECK(JS_StringEqualsAscii(cx, JSVAL_TO_STRING(rval), "From trusted: InternalError: too much recursion", &match));
CHECK(match);
@ -142,8 +142,8 @@ BEGIN_TEST(testChromeBuffer)
const char *bytes = "return 42";
JS::HandleObject global = JS::HandleObject::fromMarkedLocation(&trusted_glob);
CHECK(fun = JS_CompileFunctionForPrincipals(cx, global, &system_principals,
"trusted", 0, NULL, bytes, strlen(bytes),
"", 0));
"trusted", 0, nullptr,
bytes, strlen(bytes), "", 0));
trusted_fun = JS_GetFunctionObject(fun);
}
@ -161,7 +161,7 @@ BEGIN_TEST(testChromeBuffer)
JS::RootedValue arg(cx, JS::ObjectValue(*callTrusted));
JS::RootedValue rval(cx);
CHECK(JS_CallFunction(cx, NULL, fun, 1, arg.address(), rval.address()));
CHECK(JS_CallFunction(cx, nullptr, fun, 1, arg.address(), rval.address()));
CHECK(JSVAL_TO_INT(rval) == 42);
}

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

@ -56,14 +56,14 @@ static const JSFunctionSpec ptestFunctions[] = {
BEGIN_TEST(testClassGetter_isCalled)
{
CHECK(JS_InitClass(cx, global, NULL, &ptestClass, PTest, 0,
NULL, ptestFunctions, NULL, NULL));
CHECK(JS_InitClass(cx, global, nullptr, &ptestClass, PTest, 0,
nullptr, ptestFunctions, nullptr, nullptr));
EXEC("function check() { var o = new PTest(); o.test_fn(); o.test_value1; o.test_value2; o.test_value1; }");
for (int i = 1; i < 9; i++) {
JS::RootedValue rval(cx);
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK_SAME(INT_TO_JSVAL(called_test_fn), INT_TO_JSVAL(i));
CHECK_SAME(INT_TO_JSVAL(called_test_prop_get), INT_TO_JSVAL(4 * i));
}

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

@ -33,7 +33,8 @@ BEGIN_TEST(test_cloneScript)
{
JSAutoCompartment a(cx, A);
JSFunction *fun;
CHECK(fun = JS_CompileFunction(cx, A, "f", 0, NULL, source, strlen(source), __FILE__, 1));
CHECK(fun = JS_CompileFunction(cx, A, "f", 0, nullptr, source, strlen(source),
__FILE__, 1));
CHECK(obj = JS_GetFunctionObject(fun));
}

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

@ -72,7 +72,7 @@ BEGIN_TEST(testDerivedValues)
JS::Anchor<JSString *> str_anchor(str);
static const jschar expected[] = { 'o', 'n', 'c', 'e' };
const jschar *ch = JS_GetStringCharsZ(cx, str);
str = NULL;
str = nullptr;
/* Do a lot of allocation and collection. */
for (int i = 0; i < 3; i++) {

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

@ -19,11 +19,11 @@ IterNext(JSContext *cx, unsigned argc, jsval *vp)
static JSObject *
IterHook(JSContext *cx, JS::HandleObject obj, bool keysonly)
{
JS::RootedObject iterObj(cx, JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject iterObj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
if (!iterObj)
return NULL;
return nullptr;
if (!JS_DefineFunction(cx, iterObj, "next", IterNext, 0, 0))
return NULL;
return nullptr;
return iterObj;
}
@ -37,15 +37,15 @@ const js::Class HasCustomIterClass = {
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL,
NULL, /* checkAccess */
NULL, /* call */
NULL, /* hasInstance */
NULL, /* construct */
NULL, /* mark */
nullptr,
nullptr, /* checkAccess */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
nullptr, /* mark */
{
NULL, /* outerObject */
NULL, /* innerObject */
nullptr, /* outerObject */
nullptr, /* innerObject */
IterHook,
false /* isWrappedNative */
}
@ -63,8 +63,8 @@ IterClassConstructor(JSContext *cx, unsigned argc, jsval *vp)
BEGIN_TEST(testCustomIterator_bug612523)
{
CHECK(JS_InitClass(cx, global, NULL, Jsvalify(&HasCustomIterClass),
IterClassConstructor, 0, NULL, NULL, NULL, NULL));
CHECK(JS_InitClass(cx, global, nullptr, Jsvalify(&HasCustomIterClass),
IterClassConstructor, 0, nullptr, nullptr, nullptr, nullptr));
JS::RootedValue result(cx);
EVAL("var o = new HasCustomIter(); \n"

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

@ -27,7 +27,7 @@ callCountHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, bool
BEGIN_TEST(testDebugger_bug519719)
{
CHECK(JS_SetDebugMode(cx, true));
JS_SetCallHook(rt, callCountHook, NULL);
JS_SetCallHook(rt, callCountHook, nullptr);
EXEC("function call(fn) { fn(0); }\n"
"function f(g) { for (var i = 0; i < 9; i++) call(g); }\n"
"f(Math.sin);\n" // record loop, starting in f
@ -48,7 +48,7 @@ nonStrictThisHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing,
frame.getThisValue(cx, &thisv);
*allWrapped = *allWrapped && !JSVAL_IS_PRIMITIVE(thisv);
}
return NULL;
return nullptr;
}
BEGIN_TEST(testDebugger_getThisNonStrict)
@ -87,7 +87,7 @@ strictThisHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, boo
frame.getThisValue(cx, &thisv);
*anyWrapped = *anyWrapped || !JSVAL_IS_PRIMITIVE(thisv);
}
return NULL;
return nullptr;
}
BEGIN_TEST(testDebugger_getThisStrict)
@ -132,7 +132,7 @@ ThrowHook(JSContext *cx, JSScript *, jsbytecode *, jsval *rval, void *closure)
BEGIN_TEST(testDebugger_throwHook)
{
CHECK(JS_SetDebugMode(cx, true));
CHECK(JS_SetThrowHook(rt, ThrowHook, NULL));
CHECK(JS_SetThrowHook(rt, ThrowHook, nullptr));
EXEC("function foo() { throw 3 };\n"
"for (var i = 0; i < 10; ++i) { \n"
" var x = {}\n"
@ -141,7 +141,7 @@ BEGIN_TEST(testDebugger_throwHook)
" } catch(e) {}\n"
"}\n");
CHECK(called);
CHECK(JS_SetThrowHook(rt, NULL, NULL));
CHECK(JS_SetThrowHook(rt, nullptr, nullptr));
return true;
}
END_TEST(testDebugger_throwHook)
@ -149,7 +149,7 @@ END_TEST(testDebugger_throwHook)
BEGIN_TEST(testDebugger_debuggerObjectVsDebugMode)
{
CHECK(JS_DefineDebuggerObject(cx, global));
JS::RootedObject debuggee(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject debuggee(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
CHECK(debuggee);
{
@ -189,7 +189,7 @@ BEGIN_TEST(testDebugger_newScriptHook)
{
// Test that top-level indirect eval fires the newScript hook.
CHECK(JS_DefineDebuggerObject(cx, global));
JS::RootedObject g(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook));
JS::RootedObject g(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
CHECK(g);
{
JSAutoCompartment ae(cx, g);
@ -240,7 +240,7 @@ END_TEST(testDebugger_newScriptHook)
BEGIN_TEST(testDebugger_singleStepThrow)
{
CHECK(JS_SetDebugModeForCompartment(cx, cx->compartment(), true));
CHECK(JS_SetInterrupt(rt, onStep, NULL));
CHECK(JS_SetInterrupt(rt, onStep, nullptr));
CHECK(JS_DefineFunction(cx, global, "setStepMode", setStepMode, 0, 0));
EXEC("var e;\n"
@ -255,7 +255,7 @@ BEGIN_TEST(testDebugger_singleStepThrow)
setStepMode(JSContext *cx, unsigned argc, jsval *vp)
{
JS::RootedScript script(cx);
JS_DescribeScriptedCaller(cx, &script, NULL);
JS_DescribeScriptedCaller(cx, &script, nullptr);
JS_ASSERT(script);
if (!JS_SetSingleStepMode(cx, script, true))

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

@ -18,16 +18,16 @@ static const char PROPERTY_NAME[] = "foo";
BEGIN_TEST(testDefineGetterSetterNonEnumerable)
{
JS::RootedValue vobj(cx);
JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
CHECK(obj);
vobj = OBJECT_TO_JSVAL(obj);
JSFunction *funGet = JS_NewFunction(cx, native, 0, 0, NULL, "get");
JSFunction *funGet = JS_NewFunction(cx, native, 0, 0, nullptr, "get");
CHECK(funGet);
JS::RootedObject funGetObj(cx, JS_GetFunctionObject(funGet));
JS::RootedValue vget(cx, OBJECT_TO_JSVAL(funGetObj));
JSFunction *funSet = JS_NewFunction(cx, native, 1, 0, NULL, "set");
JSFunction *funSet = JS_NewFunction(cx, native, 1, 0, nullptr, "set");
CHECK(funSet);
JS::RootedObject funSetObj(cx, JS_GetFunctionObject(funSet));
JS::RootedValue vset(cx, OBJECT_TO_JSVAL(funSetObj));

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

@ -17,7 +17,7 @@ BEGIN_TEST(testDefineProperty_bug564344)
JS::RootedObject obj(cx, JSVAL_TO_OBJECT(x));
for (int i = 0; i < 2; i++)
CHECK(JS_DefineProperty(cx, obj, "q", JSVAL_VOID, NULL, NULL, JSPROP_SHARED));
CHECK(JS_DefineProperty(cx, obj, "q", JSVAL_VOID, nullptr, nullptr, JSPROP_SHARED));
return true;
}
END_TEST(testDefineProperty_bug564344)

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

@ -14,7 +14,7 @@
using namespace js;
JSScript *found = NULL;
JSScript *found = nullptr;
bool
CheckEnclosing(JSContext *cx, unsigned argc, Value *vp)
@ -32,24 +32,27 @@ BEGIN_TEST(test_enclosingFunction)
CHECK(JS_DefineFunction(cx, global, "checkEnclosing", CheckEnclosing, 0, 0));
EXEC("checkEnclosing()");
CHECK(found == NULL);
CHECK(found == nullptr);
RootedFunction fun(cx);
const char s1chars[] = "checkEnclosing()";
fun = JS_CompileFunction(cx, global, "s1", 0, NULL, s1chars, strlen(s1chars), __FILE__, __LINE__);
fun = JS_CompileFunction(cx, global, "s1", 0, nullptr, s1chars, strlen(s1chars),
__FILE__, __LINE__);
CHECK(fun);
EXEC("s1()");
CHECK(found == JS_GetFunctionScript(cx, fun));
const char s2chars[] = "return function() { checkEnclosing() }";
fun = JS_CompileFunction(cx, global, "s2", 0, NULL, s2chars, strlen(s2chars), __FILE__, __LINE__);
fun = JS_CompileFunction(cx, global, "s2", 0, nullptr, s2chars, strlen(s2chars),
__FILE__, __LINE__);
CHECK(fun);
EXEC("s2()()");
CHECK(found == JS_GetFunctionScript(cx, fun));
const char s3chars[] = "return function() { let (x) { function g() { checkEnclosing() } return g() } }";
fun = JS_CompileFunction(cx, global, "s3", 0, NULL, s3chars, strlen(s3chars), __FILE__, __LINE__);
fun = JS_CompileFunction(cx, global, "s3", 0, nullptr, s3chars, strlen(s3chars),
__FILE__, __LINE__);
CHECK(fun);
EXEC("s3()()");
CHECK(found == JS_GetFunctionScript(cx, fun));

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

@ -26,7 +26,7 @@ BEGIN_TEST(testErrorCopying_columnCopied)
JS::RootedValue rval(cx);
JS_SetErrorReporter(cx, my_ErrorReporter);
CHECK(!JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(!JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(column == 27);
return true;
}

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

@ -135,7 +135,7 @@ void setup(unsigned count)
vertex_count = count;
for (unsigned i = 0; i < MaxVertices; ++i) {
TestNode &v = Vertex[i];
v.gcNextGraphNode = NULL;
v.gcNextGraphNode = nullptr;
v.index = i;
memset(&v.hasEdge, 0, sizeof(v.hasEdge));
}
@ -161,14 +161,14 @@ bool group(int vertex, ...)
va_list ap;
va_start(ap, vertex);
while (vertex != -1) {
CHECK(v != NULL);
CHECK(v != nullptr);
CHECK(v->index == unsigned(vertex));
v = v->nextNodeInGroup();
vertex = va_arg(ap, int);
}
va_end(ap);
CHECK(v == NULL);
CHECK(v == nullptr);
resultsList = resultsList->nextGroup();
return true;
}
@ -180,24 +180,24 @@ bool remaining(int vertex, ...)
va_list ap;
va_start(ap, vertex);
while (vertex != -1) {
CHECK(v != NULL);
CHECK(v != nullptr);
CHECK(v->index == unsigned(vertex));
v = (TestNode *)v->gcNextGraphNode;
vertex = va_arg(ap, int);
}
va_end(ap);
CHECK(v == NULL);
resultsList = NULL;
CHECK(v == nullptr);
resultsList = nullptr;
return true;
}
bool end()
{
CHECK(resultsList == NULL);
CHECK(resultsList == nullptr);
delete finder;
finder = NULL;
finder = nullptr;
return true;
}
END_TEST(testFindSCCs)
@ -207,7 +207,7 @@ struct TestNode2 : public GraphNodeBase<TestNode2>
TestNode2 *edge;
TestNode2() :
edge(NULL)
edge(nullptr)
{
}

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

@ -36,7 +36,7 @@ funcTransition2(const JSFunction *, const JSScript*, const JSContext*, int)
}
static int overlays = 0;
static JSFunctionCallback innerCallback = NULL;
static JSFunctionCallback innerCallback = nullptr;
static void
funcTransitionOverlay(const JSFunction *fun,
const JSScript *script,
@ -78,7 +78,7 @@ BEGIN_TEST(testFuncCallback_bug507012)
CHECK_EQUAL(enters, 777);
// Check whether we can turn off function tracing
JS_SetFunctionCallback(cx, NULL);
JS_SetFunctionCallback(cx, nullptr);
EXEC("f(1)");
CHECK_EQUAL(enters, 777);
interpreted = enters = leaves = depth = 0;

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

@ -9,14 +9,14 @@
BEGIN_TEST(testGCExactRooting)
{
JS::RootedObject rootCx(cx, JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject rootRt(cx->runtime(), JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject rootCx(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
JS::RootedObject rootRt(cx->runtime(), JS_NewObject(cx, nullptr, nullptr, nullptr));
JS_GC(cx->runtime());
/* Use the objects we just created to ensure that they are still alive. */
JS_DefineProperty(cx, rootCx, "foo", JS::DoubleValue(0), NULL, NULL, 0);
JS_DefineProperty(cx, rootRt, "foo", JS::DoubleValue(0), NULL, NULL, 0);
JS_DefineProperty(cx, rootCx, "foo", JS::DoubleValue(0), nullptr, nullptr, 0);
JS_DefineProperty(cx, rootRt, "foo", JS::DoubleValue(0), nullptr, nullptr, 0);
return true;
}

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

@ -126,7 +126,7 @@ BEGIN_TEST(testGCFinalizeCallback)
CHECK(JS_IsGlobalObject(global2));
CHECK(JS_IsGlobalObject(global3));
JS_SetFinalizeCallback(rt, NULL);
JS_SetFinalizeCallback(rt, nullptr);
return true;
}

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

@ -55,7 +55,7 @@ BEGIN_TEST(testGCOutOfMemory)
virtual JSRuntime * createRuntime() {
JSRuntime *rt = JS_NewRuntime(768 * 1024, JS_USE_HELPER_THREADS);
if (!rt)
return NULL;
return nullptr;
setNativeStackQuota(rt);
return rt;
}

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

@ -97,7 +97,7 @@ BEGIN_TEST(testStringToPropertyName)
JSFlatString *hiStr = NewString(cx, hiChars);
CHECK(hiStr);
CHECK(!hiStr->isIndex(&index));
CHECK(hiStr->toPropertyName(cx) != NULL);
CHECK(hiStr->toPropertyName(cx) != nullptr);
static const jschar maxChars[] = { '4', '2', '9', '4', '9', '6', '7', '2', '9', '5' };
JSFlatString *maxStr = NewString(cx, maxChars);
@ -109,7 +109,7 @@ BEGIN_TEST(testStringToPropertyName)
JSFlatString *maxPlusOneStr = NewString(cx, maxPlusOneChars);
CHECK(maxPlusOneStr);
CHECK(!maxPlusOneStr->isIndex(&index));
CHECK(maxPlusOneStr->toPropertyName(cx) != NULL);
CHECK(maxPlusOneStr->toPropertyName(cx) != nullptr);
return true;
}

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

@ -6,7 +6,7 @@
BEGIN_TEST(testJSEvaluateScript)
{
JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, global));
JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, global));
CHECK(obj);
uint32_t options = JS_GetOptions(cx);

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

@ -63,16 +63,17 @@ document_resolve(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned
if (!flatStr)
return false;
if (JS_FlatStringEqualsAscii(flatStr, "all")) {
JS::Rooted<JSObject*> docAll(cx, JS_NewObject(cx, &DocumentAllClass, NULL, NULL));
JS::Rooted<JSObject*> docAll(cx,
JS_NewObject(cx, &DocumentAllClass, nullptr, nullptr));
if (!docAll)
return false;
JS::Rooted<JS::Value> allValue(cx, ObjectValue(*docAll));
bool ok = JS_DefinePropertyById(cx, obj, id, allValue, NULL, NULL, 0);
objp.set(ok ? obj.get() : NULL);
bool ok = JS_DefinePropertyById(cx, obj, id, allValue, nullptr, nullptr, 0);
objp.set(ok ? obj.get() : nullptr);
return ok;
}
}
objp.set(NULL);
objp.set(nullptr);
return true;
}
@ -84,9 +85,9 @@ static const JSClass document_class = {
BEGIN_TEST(testLookup_bug570195)
{
JS::RootedObject obj(cx, JS_NewObject(cx, &document_class, NULL, NULL));
JS::RootedObject obj(cx, JS_NewObject(cx, &document_class, nullptr, nullptr));
CHECK(obj);
CHECK(JS_DefineProperty(cx, global, "document", OBJECT_TO_JSVAL(obj), NULL, NULL, 0));
CHECK(JS_DefineProperty(cx, global, "document", OBJECT_TO_JSVAL(obj), nullptr, nullptr, 0));
JS::RootedValue v(cx);
EVAL("document.all ? true : false", v.address());
CHECK_SAME(v, JSVAL_FALSE);

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

@ -17,7 +17,7 @@ constructHook(JSContext *cx, unsigned argc, jsval *vp)
// Check that arguments were passed properly from JS_New.
JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), NULL, NULL));
JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), nullptr, nullptr));
if (!obj) {
JS_ReportError(cx, "test failed, could not construct object");
return false;
@ -66,7 +66,7 @@ BEGIN_TEST(testNewObject_1)
JS::RootedObject Array(cx, JSVAL_TO_OBJECT(v));
// With no arguments.
JS::RootedObject obj(cx, JS_New(cx, Array, 0, NULL));
JS::RootedObject obj(cx, JS_New(cx, Array, 0, nullptr));
CHECK(obj);
JS::RootedValue rt(cx, OBJECT_TO_JSVAL(obj));
CHECK(JS_IsArrayObject(cx, obj));
@ -100,10 +100,10 @@ BEGIN_TEST(testNewObject_1)
"testNewObject_1",
0,
JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, NULL,
NULL, NULL, NULL, constructHook
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr,
nullptr, nullptr, nullptr, constructHook
};
JS::RootedObject ctor(cx, JS_NewObject(cx, &cls, NULL, NULL));
JS::RootedObject ctor(cx, JS_NewObject(cx, &cls, nullptr, nullptr));
CHECK(ctor);
JS::RootedValue rt2(cx, OBJECT_TO_JSVAL(ctor));
obj = JS_New(cx, ctor, 3, argv);

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

@ -18,7 +18,7 @@ virtual JSRuntime * createRuntime()
{
JSRuntime *rt = JS_NewRuntime(0, JS_USE_HELPER_THREADS);
if (!rt)
return NULL;
return nullptr;
JS_SetGCParameter(rt, JSGC_MAX_BYTES, (uint32_t)-1);
setNativeStackQuota(rt);
return rt;

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

@ -28,8 +28,9 @@ ObjectEmulatingUndefinedConstructor(JSContext *cx, unsigned argc, jsval *vp)
BEGIN_TEST(testObjectEmulatingUndefined_truthy)
{
CHECK(JS_InitClass(cx, global, NULL, &ObjectEmulatingUndefinedClass,
ObjectEmulatingUndefinedConstructor, 0, NULL, NULL, NULL, NULL));
CHECK(JS_InitClass(cx, global, nullptr, &ObjectEmulatingUndefinedClass,
ObjectEmulatingUndefinedConstructor, 0,
nullptr, nullptr, nullptr, nullptr));
JS::RootedValue result(cx);
@ -53,8 +54,9 @@ END_TEST(testObjectEmulatingUndefined_truthy)
BEGIN_TEST(testObjectEmulatingUndefined_equal)
{
CHECK(JS_InitClass(cx, global, NULL, &ObjectEmulatingUndefinedClass,
ObjectEmulatingUndefinedConstructor, 0, NULL, NULL, NULL, NULL));
CHECK(JS_InitClass(cx, global, nullptr, &ObjectEmulatingUndefinedClass,
ObjectEmulatingUndefinedConstructor, 0,
nullptr, nullptr, nullptr, nullptr));
JS::RootedValue result(cx);

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

@ -33,7 +33,7 @@ createMyObject(JSContext* context, unsigned argc, jsval *vp)
//JS_GC(context); //<- if we make GC here, all is ok
JSObject* myObject = JS_NewObject(context, &myClass, NULL, NULL);
JSObject* myObject = JS_NewObject(context, &myClass, nullptr, nullptr);
*vp = OBJECT_TO_JSVAL(myObject);
JS_EndRequest(context);
@ -55,7 +55,7 @@ BEGIN_TEST(testOps_bug559006)
for (int i = 0; i < 9; i++) {
JS::RootedValue rval(cx);
CHECK(JS_CallFunctionName(cx, global, "main", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "main", 0, nullptr, rval.address()));
CHECK_SAME(rval, INT_TO_JSVAL(123));
}
return true;

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

@ -5,7 +5,7 @@
#include "js/OldDebugAPI.h"
#include "jsapi-tests/tests.h"
JSPrincipals *sOriginPrincipalsInErrorReporter = NULL;
JSPrincipals *sOriginPrincipalsInErrorReporter = nullptr;
static void
ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)

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

@ -19,7 +19,7 @@ class AutoInflatedString {
size_t length_;
public:
AutoInflatedString(JSContext *cx) : cx(cx), chars_(NULL), length_(0) { }
AutoInflatedString(JSContext *cx) : cx(cx), chars_(nullptr), length_(0) { }
~AutoInflatedString() {
JS_free(cx, chars_);
}
@ -190,7 +190,7 @@ Error(JSContext *cx, const char (&input)[N])
JSErrorReporter old = JS_SetErrorReporter(cx, reportJSONEror);
bool ok = JS_ParseJSON(cx, str.chars(), str.length(), &dummy);
JS_SetErrorReporter(cx, old);
JS_SetContextPrivate(cx, NULL);
JS_SetContextPrivate(cx, nullptr);
CHECK(!ok);
CHECK(!p.unexpectedErrorCount);

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

@ -42,7 +42,7 @@ test_fn2(JSContext *cx, unsigned argc, jsval *vp)
{
jsval r;
JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
return JS_CallFunctionName(cx, global, "d", 0, NULL, &r);
return JS_CallFunctionName(cx, global, "d", 0, nullptr, &r);
}
static bool
@ -82,8 +82,8 @@ initialize(JSContext *cx)
{
js::SetRuntimeProfilingStack(cx->runtime(), pstack, &psize, 10);
JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
return JS_InitClass(cx, global, NULL, &ptestClass, Prof, 0,
NULL, ptestFunctions, NULL, NULL);
return JS_InitClass(cx, global, nullptr, &ptestClass, Prof, 0,
nullptr, ptestFunctions, nullptr, nullptr);
}
BEGIN_TEST(testProfileStrings_isCalledWithInterpreter)
@ -104,13 +104,13 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter)
{
JS::RootedValue rval(cx);
/* Make sure the stack resets and we have an entry for each stack */
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(psize == 0);
CHECK(max_stack >= 8);
CHECK(cx->runtime()->spsProfiler.stringsCount() == 8);
/* Make sure the stack resets and we added no new entries */
max_stack = 0;
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(psize == 0);
CHECK(max_stack >= 8);
CHECK(cx->runtime()->spsProfiler.stringsCount() == 8);
@ -118,7 +118,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter)
reset(cx);
{
JS::RootedValue rval(cx);
CHECK(JS_CallFunctionName(cx, global, "check2", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check2", 0, nullptr, rval.address()));
CHECK(cx->runtime()->spsProfiler.stringsCount() == 5);
CHECK(max_stack >= 6);
CHECK(psize == 0);
@ -129,7 +129,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter)
{
JS::RootedValue rval(cx);
pstack[3].setLabel((char*) 1234);
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK((size_t) pstack[3].label() == 1234);
CHECK(max_stack >= 8);
CHECK(psize == 0);
@ -157,14 +157,14 @@ BEGIN_TEST(testProfileStrings_isCalledWithJIT)
{
JS::RootedValue rval(cx);
/* Make sure the stack resets and we have an entry for each stack */
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(psize == 0);
CHECK(max_stack >= 8);
/* Make sure the stack resets and we added no new entries */
uint32_t cnt = cx->runtime()->spsProfiler.stringsCount();
max_stack = 0;
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(psize == 0);
CHECK(cx->runtime()->spsProfiler.stringsCount() == cnt);
CHECK(max_stack >= 8);
@ -177,7 +177,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithJIT)
/* Limit the size of the stack and make sure we don't overflow */
JS::RootedValue rval(cx);
pstack[3].setLabel((char*) 1234);
CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address()));
CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
CHECK(psize == 0);
CHECK(max_stack >= 8);
CHECK((size_t) pstack[3].label() == 1234);
@ -198,7 +198,7 @@ BEGIN_TEST(testProfileStrings_isCalledWhenError)
{
JS::RootedValue rval(cx);
/* Make sure the stack resets and we have an entry for each stack */
bool ok = JS_CallFunctionName(cx, global, "check2", 0, NULL, rval.address());
bool ok = JS_CallFunctionName(cx, global, "check2", 0, nullptr, rval.address());
CHECK(!ok);
CHECK(psize == 0);
CHECK(cx->runtime()->spsProfiler.stringsCount() == 1);
@ -221,7 +221,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
{
/* enable it in the middle of JS and make sure things check out */
JS::RootedValue rval(cx);
JS_CallFunctionName(cx, global, "a", 0, NULL, rval.address());
JS_CallFunctionName(cx, global, "a", 0, nullptr, rval.address());
CHECK(psize == 0);
CHECK(max_stack >= 1);
CHECK(cx->runtime()->spsProfiler.stringsCount() == 1);
@ -233,7 +233,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
{
/* now disable in the middle of js */
JS::RootedValue rval(cx);
JS_CallFunctionName(cx, global, "c", 0, NULL, rval.address());
JS_CallFunctionName(cx, global, "c", 0, nullptr, rval.address());
CHECK(psize == 0);
}
@ -242,7 +242,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
{
/* now disable in the middle of js, but re-enable before final exit */
JS::RootedValue rval(cx);
JS_CallFunctionName(cx, global, "e", 0, NULL, rval.address());
JS_CallFunctionName(cx, global, "e", 0, nullptr, rval.address());
CHECK(psize == 0);
CHECK(max_stack >= 3);
}
@ -256,7 +256,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
JS::RootedValue rval(cx);
/* disable, and make sure that if we try to re-enter the JIT the pop
* will still happen */
JS_CallFunctionName(cx, global, "f", 0, NULL, rval.address());
JS_CallFunctionName(cx, global, "f", 0, nullptr, rval.address());
CHECK(psize == 0);
}
return true;

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

@ -27,7 +27,7 @@ BEGIN_TEST(testPropCache_bug505798)
{
g_counter = 0;
EXEC("var x = {};");
CHECK(JS_DefineObject(cx, global, "y", &CounterClass, NULL, JSPROP_ENUMERATE));
CHECK(JS_DefineObject(cx, global, "y", &CounterClass, nullptr, JSPROP_ENUMERATE));
EXEC("var arr = [x, y];\n"
"for (var i = 0; i < arr.length; i++)\n"
" arr[i].p = 1;\n");

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

@ -23,7 +23,7 @@ BEGIN_TEST(testRegExpInstanceProperties)
JS_GC(cx);
CHECK_EQUAL(regexpProto->compartment()->initialRegExpShape, NULL);
CHECK_EQUAL(regexpProto->compartment()->initialRegExpShape, nullptr);
jsval regexp;
EVAL("/foopy/", &regexp);

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

@ -27,19 +27,19 @@ BEGIN_TEST(testResolveRecursion)
JS_ConvertStub
};
obj1 = obj2 = NULL;
obj1 = obj2 = nullptr;
JS_AddObjectRoot(cx, &obj1);
JS_AddObjectRoot(cx, &obj2);
obj1 = JS_NewObject(cx, &my_resolve_class, NULL, NULL);
obj1 = JS_NewObject(cx, &my_resolve_class, nullptr, nullptr);
CHECK(obj1);
obj2 = JS_NewObject(cx, &my_resolve_class, NULL, NULL);
obj2 = JS_NewObject(cx, &my_resolve_class, nullptr, nullptr);
CHECK(obj2);
JS_SetPrivate(obj1, this);
JS_SetPrivate(obj2, this);
CHECK(JS_DefineProperty(cx, global, "obj1", OBJECT_TO_JSVAL(obj1), NULL, NULL, 0));
CHECK(JS_DefineProperty(cx, global, "obj2", OBJECT_TO_JSVAL(obj2), NULL, NULL, 0));
CHECK(JS_DefineProperty(cx, global, "obj1", OBJECT_TO_JSVAL(obj1), nullptr, nullptr, 0));
CHECK(JS_DefineProperty(cx, global, "obj2", OBJECT_TO_JSVAL(obj2), nullptr, nullptr, 0));
resolveEntryCount = 0;
resolveExitCount = 0;
@ -92,19 +92,19 @@ doResolve(JS::HandleObject obj, JS::HandleId id, unsigned flags, JS::MutableHand
CHECK_EQUAL(resolveEntryCount, 1);
EVAL("obj2.y = true", v.address());
CHECK_SAME(v, JSVAL_TRUE);
CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_FALSE, NULL, NULL, 0));
CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_FALSE, nullptr, nullptr, 0));
objp.set(obj);
return true;
}
if (obj == obj2) {
CHECK_EQUAL(resolveEntryCount, 4);
objp.set(NULL);
objp.set(nullptr);
return true;
}
} else if (JS_FlatStringEqualsAscii(str, "y")) {
if (obj == obj2) {
CHECK_EQUAL(resolveEntryCount, 2);
CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_NULL, NULL, NULL, 0));
CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_NULL, nullptr, nullptr, 0));
EVAL("obj1.x", v.address());
CHECK(JSVAL_IS_VOID(v));
EVAL("obj1.y", v.address());

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

@ -54,7 +54,7 @@ END_FIXTURE_TEST(ScriptObjectFixture, bug438633_CompileScript_empty)
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_CompileScriptForPrincipals)
{
return tryScript(global, JS_CompileScriptForPrincipals(cx, global, NULL,
return tryScript(global, JS_CompileScriptForPrincipals(cx, global, nullptr,
code, code_size,
__FILE__, __LINE__));
}
@ -78,7 +78,7 @@ END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript_empty)
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScriptForPrincipals)
{
return tryScript(global, JS_CompileUCScriptForPrincipals(cx, global, NULL,
return tryScript(global, JS_CompileUCScriptForPrincipals(cx, global, nullptr,
uc_code, code_size,
__FILE__, __LINE__));
}
@ -145,7 +145,7 @@ BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandleForPrincip
CHECK(fseek(script_stream, 0, SEEK_SET) != EOF);
JS::CompileOptions options(cx);
options.setFileAndLine("temporary file", 1)
.setPrincipals(NULL);
.setPrincipals(nullptr);
return tryScript(global, JS::Compile(cx, global, options, script_stream));
}
END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandleForPrincipals)

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

@ -16,7 +16,7 @@ nativeGet(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandl
BEGIN_TEST(testSetProperty_NativeGetterStubSetter)
{
JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL));
JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
CHECK(obj);
JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj));
@ -73,7 +73,7 @@ BEGIN_TEST(testSetProperty_InheritedGlobalSetter)
// shell can't.
JS_ASSERT(JS_GetClass(global)->resolve == &JS_ResolveStub);
CHECK(JS_DefineProperty(cx, global, "HOTLOOP", INT_TO_JSVAL(8), NULL, NULL, 0));
CHECK(JS_DefineProperty(cx, global, "HOTLOOP", INT_TO_JSVAL(8), nullptr, nullptr, 0));
EXEC("var n = 0;\n"
"var global = this;\n"
"function f() { n++; }\n"

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

@ -16,8 +16,8 @@ BEGIN_TEST(testBug795104)
s[0] = '"';
memset(s + 1, 'x', strLen - 2);
s[strLen - 1] = '"';
CHECK(JS::Evaluate(cx, global, opts, s, strLen, NULL));
CHECK(JS::CompileFunction(cx, global, opts, "f", 0, NULL, s, strLen));
CHECK(JS::Evaluate(cx, global, opts, s, strLen, nullptr));
CHECK(JS::CompileFunction(cx, global, opts, "f", 0, nullptr, s, strLen));
JS_free(cx, s);
return true;
@ -39,9 +39,9 @@ BEGIN_TEST(testScriptSourceReentrant)
JS::CompileOptions opts(cx);
bool match = false;
JS_SetNewScriptHook(rt, newScriptHook, &match);
CHECK(JS::Evaluate(cx, global, opts, simpleSource, strlen(simpleSource), NULL));
CHECK(JS::Evaluate(cx, global, opts, simpleSource, strlen(simpleSource), nullptr));
CHECK(match);
JS_SetNewScriptHook(rt, NULL, NULL);
JS_SetNewScriptHook(rt, nullptr, nullptr);
return true;
}

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

@ -19,7 +19,7 @@ BEGIN_TEST(testStructuredClone_object)
JSAutoCompartment ac(cx, g1);
JS::RootedValue prop(cx, JS::Int32Value(1337));
v1 = JS::ObjectOrNullValue(JS_NewObject(cx, NULL, NULL, NULL));
v1 = JS::ObjectOrNullValue(JS_NewObject(cx, nullptr, nullptr, nullptr));
CHECK(v1.isObject());
CHECK(JS_SetProperty(cx, &v1.toObject(), "prop", prop));
}
@ -28,7 +28,7 @@ BEGIN_TEST(testStructuredClone_object)
JSAutoCompartment ac(cx, g2);
JS::RootedValue v2(cx);
CHECK(JS_StructuredClone(cx, v1, v2.address(), NULL, NULL));
CHECK(JS_StructuredClone(cx, v1, v2.address(), nullptr, nullptr));
CHECK(v2.isObject());
JS::RootedValue prop(cx);
@ -64,7 +64,7 @@ BEGIN_TEST(testStructuredClone_string)
JSAutoCompartment ac(cx, g2);
JS::RootedValue v2(cx);
CHECK(JS_StructuredClone(cx, v1, v2.address(), NULL, NULL));
CHECK(JS_StructuredClone(cx, v1, v2.address(), nullptr, nullptr));
CHECK(v2.isString());
CHECK(v2.toString());

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

@ -31,7 +31,7 @@ BEGIN_TEST(testValueABI_retparam)
{
JS::RootedObject obj(cx, JS::CurrentGlobalOrNull(cx));
jsval v = OBJECT_TO_JSVAL(obj);
obj = NULL;
obj = nullptr;
CHECK(C_ValueToObject(cx, v, obj.address()));
bool equal;
CHECK(JS_StrictlyEqual(cx, v, OBJECT_TO_JSVAL(obj), &equal));

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

@ -20,11 +20,11 @@ CompileScriptForPrincipalsVersionOrigin(JSContext *cx, JS::HandleObject obj,
JSVersion version)
{
size_t nchars;
if (!JS_DecodeBytes(cx, bytes, nbytes, NULL, &nchars))
return NULL;
if (!JS_DecodeBytes(cx, bytes, nbytes, nullptr, &nchars))
return nullptr;
jschar *chars = static_cast<jschar *>(JS_malloc(cx, nchars * sizeof(jschar)));
if (!chars)
return NULL;
return nullptr;
JS_ALWAYS_TRUE(JS_DecodeBytes(cx, bytes, nbytes, chars, &nchars));
JS::CompileOptions options(cx);
options.setPrincipals(principals)
@ -43,7 +43,7 @@ FreezeThaw(JSContext *cx, JS::HandleScript script)
uint32_t nbytes;
void *memory = JS_EncodeScript(cx, script, &nbytes);
if (!memory)
return NULL;
return nullptr;
// thaw
JSScript *script2 = JS_DecodeScript(cx, memory, nbytes,
@ -65,7 +65,7 @@ FreezeThaw(JSContext *cx, JS::HandleObject funobj)
uint32_t nbytes;
void *memory = JS_EncodeInterpretedFunction(cx, funobj, &nbytes);
if (!memory)
return NULL;
return nullptr;
// thaw
JSScript *script = GetScript(cx, funobj);
@ -89,7 +89,7 @@ BEGIN_TEST(testXDR_principals)
// Appease the new JSAPI assertions. The stuff being tested here is
// going away anyway.
JS_SetCompartmentPrincipals(compartment, &testPrincipals[0]);
script = createScriptViaXDR(&testPrincipals[0], NULL, i);
script = createScriptViaXDR(&testPrincipals[0], nullptr, i);
CHECK(script);
CHECK(JS_GetScriptPrincipals(script) == &testPrincipals[0]);
CHECK(JS_GetScriptOriginPrincipals(script) == &testPrincipals[0]);
@ -127,12 +127,12 @@ JSScript *createScriptViaXDR(JSPrincipals *prin, JSPrincipals *orig, int testCas
src, strlen(src), "test", 1,
JSVERSION_DEFAULT));
if (!script)
return NULL;
return nullptr;
if (testCase == TEST_SCRIPT || testCase == TEST_SERIALIZED_FUNCTION) {
script = FreezeThaw(cx, script);
if (!script)
return NULL;
return nullptr;
if (testCase == TEST_SCRIPT)
return script;
}
@ -140,12 +140,12 @@ JSScript *createScriptViaXDR(JSPrincipals *prin, JSPrincipals *orig, int testCas
JS::RootedValue v(cx);
bool ok = JS_ExecuteScript(cx, global, script, v.address());
if (!ok || !v.isObject())
return NULL;
return nullptr;
JS::RootedObject funobj(cx, &v.toObject());
if (testCase == TEST_FUNCTION) {
funobj = FreezeThaw(cx, funobj);
if (!funobj)
return NULL;
return nullptr;
}
return GetScript(cx, funobj);
}
@ -194,7 +194,7 @@ BEGIN_TEST(testXDR_bug516827)
CHECK(script);
// execute with null result meaning no result wanted
CHECK(JS_ExecuteScript(cx, global, script, NULL));
CHECK(JS_ExecuteScript(cx, global, script, nullptr));
return true;
}
END_TEST(testXDR_bug516827)
@ -205,7 +205,7 @@ BEGIN_TEST(testXDR_source)
// This can't possibly fail to compress well, can it?
"function f(x) { return x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x }",
"short",
NULL
nullptr
};
for (const char **s = samples; *s; s++) {
JS::RootedScript script(cx, JS_CompileScript(cx, global, *s, strlen(*s), __FILE__, __LINE__));
@ -227,7 +227,7 @@ BEGIN_TEST(testXDR_sourceMap)
const char *sourceMaps[] = {
"http://example.com/source-map.json",
"file:///var/source-map.json",
NULL
nullptr
};
JS::RootedScript script(cx);
for (const char **sm = sourceMaps; *sm; sm++) {

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

@ -56,7 +56,7 @@ JSObject * JSAPITest::createGlobal(JSPrincipals *principals)
options.setVersion(JSVERSION_LATEST);
global = JS_NewGlobalObject(cx, getGlobalClass(), principals, JS::FireOnNewGlobalHook, options);
if (!global)
return NULL;
return nullptr;
JS_AddNamedObjectRoot(cx, &global, "test-global");
JS::HandleObject globalHandle = JS::HandleObject::fromMarkedLocation(&global);
@ -65,7 +65,7 @@ JSObject * JSAPITest::createGlobal(JSPrincipals *principals)
/* Populate the global object with the standard globals, like Object and
Array. */
if (!JS_InitStandardClasses(cx, globalHandle))
return NULL;
return nullptr;
return global;
}
@ -73,7 +73,7 @@ int main(int argc, char *argv[])
{
int total = 0;
int failures = 0;
const char *filter = (argc == 2) ? argv[1] : NULL;
const char *filter = (argc == 2) ? argv[1] : nullptr;
if (!JS_Init()) {
printf("TEST-UNEXPECTED-FAIL | jsapi-tests | JS_Init() failed.\n");
@ -82,7 +82,7 @@ int main(int argc, char *argv[])
for (JSAPITest *test = JSAPITest::list; test; test = test->next) {
const char *name = test->name();
if (filter && strstr(name, filter) == NULL)
if (filter && strstr(name, filter) == nullptr)
continue;
total += 1;

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше