author | Doug Turner <dougt@dougt.org> |
Thu, 17 Nov 2011 15:49:43 -0800 | |
changeset 81890 | b92c1975156dcf27617f7badc7dbfcc5a41f8fa5 |
parent 81889 | f034ceedf46e1cbc571c584d3dc93347c491b784 (current diff) |
parent 80377 | b62e6ee5ba9b3031b72faf30587bc7a195166467 (diff) |
child 81891 | 3ab7cf4bfd76e0508c94eb7f24ccc704b15e8525 |
push id | 21573 |
push user | blassey@mozilla.com |
push date | Tue, 06 Dec 2011 18:57:07 +0000 |
treeherder | mozilla-central@0e397568c71e [default view] [failures only] |
perfherder | [talos] [build metrics] [platform microbench] (compared to previous push) |
milestone | 11.0a1 |
first release with | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
last release without | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
Makefile.in | file | annotate | diff | comparison | revisions | |
configure.in | file | annotate | diff | comparison | revisions | |
content/base/src/nsFrameLoader.cpp | file | annotate | diff | comparison | revisions | |
dom/base/nsGlobalWindow.cpp | file | annotate | diff | comparison | revisions | |
gfx/2d/Blur.cpp | file | annotate | diff | comparison | revisions | |
gfx/2d/Blur.h | file | annotate | diff | comparison | revisions | |
layout/generic/nsFrame.cpp | file | annotate | diff | comparison | revisions | |
toolkit/mozapps/installer/packager.mk | file | annotate | diff | comparison | revisions |
--- a/Makefile.in +++ b/Makefile.in @@ -161,17 +161,21 @@ EXTRA_BUILDID := -$(MOZ_SYMBOLS_EXTRA_BU endif SYMBOL_INDEX_NAME = \ $(MOZ_APP_NAME)-$(MOZ_APP_VERSION)-$(OS_TARGET)-$(BUILDID)$(EXTRA_BUILDID)-symbols.txt buildsymbols: ifdef MOZ_CRASHREPORTER ifdef USE_ELF_HACK - $(MAKE) -C $(MOZ_BUILD_APP)/installer elfhack + ifeq (mobile,$(MOZ_BUILD_APP)) + $(MAKE) -C mobile/xul/installer elfhack + else + $(MAKE) -C $(MOZ_BUILD_APP)/installer elfhack + endif endif echo building symbol store $(RM) -r $(DIST)/crashreporter-symbols $(RM) "$(DIST)/$(SYMBOL_ARCHIVE_BASENAME).zip" $(NSINSTALL) -D $(DIST)/crashreporter-symbols OBJCOPY="$(OBJCOPY)" \ $(PYTHON) $(topsrcdir)/toolkit/crashreporter/tools/symbolstore.py \ $(MAKE_SYM_STORE_ARGS) \
--- a/accessible/src/base/AccGroupInfo.cpp +++ b/accessible/src/base/AccGroupInfo.cpp @@ -45,16 +45,22 @@ AccGroupInfo::AccGroupInfo(nsAccessible* mPosInSet(0), mSetSize(0), mParent(nsnull) { MOZ_COUNT_CTOR(AccGroupInfo); nsAccessible* parent = aItem->Parent(); if (!parent) return; PRInt32 indexInParent = aItem->IndexInParent(); + PRInt32 siblingCount = parent->GetChildCount(); + if (siblingCount < indexInParent) { + NS_ERROR("Wrong index in parent! Tree invalidation problem."); + return; + } + PRInt32 level = nsAccUtils::GetARIAOrDefaultLevel(aItem); // Compute position in set. mPosInSet = 1; for (PRInt32 idx = indexInParent - 1; idx >=0 ; idx--) { nsAccessible* sibling = parent->GetChildAt(idx); PRUint32 siblingRole = sibling->Role(); @@ -90,17 +96,16 @@ AccGroupInfo::AccGroupInfo(nsAccessible* } mPosInSet++; } // Compute set size. mSetSize = mPosInSet; - PRInt32 siblingCount = parent->GetChildCount(); for (PRInt32 idx = indexInParent + 1; idx < siblingCount; idx++) { nsAccessible* sibling = parent->GetChildAt(idx); PRUint32 siblingRole = sibling->Role(); // If the sibling is separator then the group is ended. if (siblingRole == nsIAccessibleRole::ROLE_SEPARATOR) break;
--- a/accessible/src/base/NotificationController.cpp +++ b/accessible/src/base/NotificationController.cpp @@ -587,29 +587,29 @@ NotificationController::CoalesceSelChang } // Unpack the packed selection change event because we've got one // more selection add/remove. if (aThisEvent->mEventType == nsIAccessibleEvent::EVENT_SELECTION) { if (aThisEvent->mPackedEvent) { aThisEvent->mPackedEvent->mEventType = aThisEvent->mPackedEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd ? - nsIAccessibleEvent::EVENT_SELECTION_ADD : - nsIAccessibleEvent::EVENT_SELECTION_REMOVE; + static_cast<PRUint32>(nsIAccessibleEvent::EVENT_SELECTION_ADD) : + static_cast<PRUint32>(nsIAccessibleEvent::EVENT_SELECTION_REMOVE); aThisEvent->mPackedEvent->mEventRule = AccEvent::eCoalesceSelectionChange; aThisEvent->mPackedEvent = nsnull; } aThisEvent->mEventType = aThisEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd ? - nsIAccessibleEvent::EVENT_SELECTION_ADD : - nsIAccessibleEvent::EVENT_SELECTION_REMOVE; + static_cast<PRUint32>(nsIAccessibleEvent::EVENT_SELECTION_ADD) : + static_cast<PRUint32>(nsIAccessibleEvent::EVENT_SELECTION_REMOVE); return; } // Convert into selection add since control has single selection but other // selection events for this control are queued. if (aTailEvent->mEventType == nsIAccessibleEvent::EVENT_SELECTION) aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION_ADD;
--- a/accessible/src/msaa/nsAccessibleWrap.cpp +++ b/accessible/src/msaa/nsAccessibleWrap.cpp @@ -284,25 +284,22 @@ STDMETHODIMP nsAccessibleWrap::get_accNa *pszName = NULL; nsAccessible *xpAccessible = GetXPAccessibleFor(varChild); if (!xpAccessible) return E_FAIL; nsAutoString name; nsresult rv = xpAccessible->GetName(name); if (NS_FAILED(rv)) return GetHRESULT(rv); - - if (name.IsVoid()) { - // Valid return value for the name: - // The name was not provided, e.g. no alt attribute for an image. - // A screen reader may choose to invent its own accessible name, e.g. from - // an image src attribute. - // See nsHTMLImageAccessible::GetName() - return S_OK; - } + + // The name was not provided, e.g. no alt attribute for an image. A screen + // reader may choose to invent its own accessible name, e.g. from an image src + // attribute. Refer to NS_OK_EMPTY_NAME return value. + if (name.IsVoid()) + return S_FALSE; *pszName = ::SysAllocStringLen(name.get(), name.Length()); if (!*pszName) return E_OUTOFMEMORY; } __except(FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { } return S_OK;
--- a/browser/app/profile/firefox.js +++ b/browser/app/profile/firefox.js @@ -53,16 +53,20 @@ pref("browser.hiddenWindowChromeURL", "c // Enables some extra Extension System Logging (can reduce performance) pref("extensions.logging.enabled", false); // Enables strict compatibility. To be toggled in bug 698653, to make addons // compatibile by default. pref("extensions.strictCompatibility", true); +// Specifies a minimum maxVersion an addon needs to say it's compatible with +// for it to be compatible by default. +pref("extensions.minCompatibleAppVersion", "4.0"); + // Preferences for AMO integration pref("extensions.getAddons.cache.enabled", true); pref("extensions.getAddons.maxResults", 15); pref("extensions.getAddons.get.url", "https://services.addons.mozilla.org/%LOCALE%/firefox/api/%API_VERSION%/search/guid:%IDS%?src=firefox&appOS=%OS%&appVersion=%VERSION%"); pref("extensions.getAddons.search.browseURL", "https://addons.mozilla.org/%LOCALE%/firefox/search?q=%TERMS%"); pref("extensions.getAddons.search.url", "https://services.addons.mozilla.org/%LOCALE%/firefox/api/%API_VERSION%/search/%TERMS%/all/%MAX_RESULTS%/%OS%/%VERSION%?src=firefox"); pref("extensions.webservice.discoverURL", "https://services.addons.mozilla.org/%LOCALE%/firefox/discovery/pane/%VERSION%/%OS%");
--- a/browser/base/content/aboutSyncTabs.js +++ b/browser/base/content/aboutSyncTabs.js @@ -132,17 +132,16 @@ let RemoteTabViewer = { let uri = Weave.Utils.makeURI(item.getAttribute("url")); let title = item.getAttribute("title"); PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: uri , title: title , hiddenRows: [ "description" , "location" - , "folderPicker" , "loadInSidebar" , "keyword" ] }, window.top); }, bookmarkSelectedTabs: function() { let items = this._tabsList.selectedItems; let URIs = [];
--- a/browser/base/content/browser-places.js +++ b/browser/base/content/browser-places.js @@ -381,17 +381,16 @@ var PlacesCommandHook = { if (itemId == -1) { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: linkURI , title: aTitle , hiddenRows: [ "description" , "location" , "loadInSidebar" - , "folderPicker" , "keyword" ] }, window); } else { PlacesUIUtils.showBookmarkDialog({ action: "edit" , type: "bookmark" , itemId: itemId }, window);
--- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -3158,17 +3158,16 @@ var bookmarksButtonObserver = { try { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: makeURI(url) , title: name , hiddenRows: [ "description" , "location" , "loadInSidebar" - , "folderPicker" , "keyword" ] }, window); } catch(ex) { } }, onDragOver: function (aEvent) { browserDragAndDrop.dragOver(aEvent); @@ -5787,17 +5786,16 @@ function contentAreaClick(event, isPanel // the title that should be used for the sidebar panel. PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: makeURI(href) , title: linkNode.getAttribute("title") , loadBookmarkInSidebar: true , hiddenRows: [ "description" , "location" - , "folderPicker" , "keyword" ] }, window); event.preventDefault(); return true; } } handleLinkClick(event, href, linkNode); @@ -6834,18 +6832,19 @@ function AddKeywordForSearchField() { , type: "bookmark" , uri: makeURI(spec) , title: title , description: description , keyword: "" , postData: postData , charSet: charset , hiddenRows: [ "location" - , "loadInSidebar" - , "folderPicker" ] + , "description" + , "tags" + , "loadInSidebar" ] }, window); } function SwitchDocumentDirection(aWindow) { aWindow.document.dir = (aWindow.document.dir == "ltr" ? "rtl" : "ltr"); for (var run = 0; run < aWindow.frames.length; run++) SwitchDocumentDirection(aWindow.frames[run]); }
--- a/browser/base/content/nsContextMenu.js +++ b/browser/base/content/nsContextMenu.js @@ -1401,17 +1401,16 @@ nsContextMenu.prototype = { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: uri , title: title , description: description , hiddenRows: [ "description" , "location" , "loadInSidebar" - , "folderPicker" , "keyword" ] }, window.top); } else { PlacesUIUtils.showBookmarkDialog({ action: "edit" , type: "bookmark" , itemId: itemId }, window.top);
--- a/browser/components/places/content/bookmarkProperties.js +++ b/browser/components/places/content/bookmarkProperties.js @@ -259,18 +259,16 @@ var BookmarkPropertiesPanel = { if ("description" in dialogInfo) this._description = dialogInfo.description; } else { // edit NS_ASSERT("itemId" in dialogInfo); this._itemId = dialogInfo.itemId; this._title = PlacesUtils.bookmarks.getItemTitle(this._itemId); - // Don't show folderPicker when editing - this._hiddenRows.push("folderPicker"); this._readOnly = !!dialogInfo.readOnly; switch (dialogInfo.type) { case "bookmark": this._itemType = BOOKMARK_ITEM; this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId); // keyword
--- a/browser/components/places/content/controller.js +++ b/browser/components/places/content/controller.js @@ -304,17 +304,16 @@ PlacesController.prototype = { break; case "placesCmd_createBookmark": let node = this._view.selectedNode; PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , hiddenRows: [ "description" , "keyword" , "location" - , "folderPicker" , "loadInSidebar" ] , uri: NetUtil.newURI(node.uri) , title: node.title }, window.top); break; } }, @@ -716,16 +715,17 @@ PlacesController.prototype = { // the correct title for the node. itemId = concreteId; } PlacesUIUtils.showBookmarkDialog({ action: "edit" , type: itemType , itemId: itemId , readOnly: isRootItem + , hiddenRows: [ "folderPicker" ] }, window.top); }, /** * This method can be run on a URI parameter to ensure that it didn't * receive a string instead of an nsIURI object. */ _assertURINotString: function PC__assertURINotString(value) {
--- a/browser/components/places/src/PlacesUIUtils.jsm +++ b/browser/components/places/src/PlacesUIUtils.jsm @@ -335,39 +335,46 @@ var PlacesUIUtils = { /** * Shows the bookmark dialog corresponding to the specified info. * * @param aInfo * Describes the item to be edited/added in the dialog. * See documentation at the top of bookmarkProperties.js * @param aWindow * Owner window for the new dialog. - * @param aMinimalUI [optional] - * Whether to open the dialog in "minimal ui" mode. Do not pass this - * for new callers. It'll be removed in a future release. + * @param aResizable [optional] + * Whether the dialog is allowed to resize. Do not pass this for new + * callers since it's deprecated. It'll be removed in future releases. * * @see documentation at the top of bookmarkProperties.js * @return true if any transaction has been performed, false otherwise. */ showBookmarkDialog: - function PUIU_showBookmarkDialog(aInfo, aParentWindow, aMinimalUI) { + function PUIU_showBookmarkDialog(aInfo, aParentWindow, aResizable) { + // This is a compatibility shim for add-ons. It will warn in the Error + // Console when used. if (!aParentWindow) { aParentWindow = this._getWindow(null); } // Preserve size attributes differently based on the fact the dialog has - // a folder picker or not. - let minimalUI = "hiddenRows" in aInfo && - aInfo.hiddenRows.indexOf("folderPicker") != -1; - let dialogURL = aMinimalUI ? + // a folder picker or not. If the picker is visible, the dialog should + // be resizable since it may not show enough content for the folders + // hierarchy. + let hasFolderPicker = !("hiddenRows" in aInfo) || + aInfo.hiddenRows.indexOf("folderPicker") == -1; + let resizable = aResizable !== undefined ? aResizable : hasFolderPicker; + // Use a different chrome url, since this allows to persist different sizes, + // based on resizability of the dialog. + let dialogURL = resizable ? "chrome://browser/content/places/bookmarkProperties2.xul" : "chrome://browser/content/places/bookmarkProperties.xul"; let features = - "centerscreen,chrome,modal,resizable=" + (aMinimalUI ? "yes" : "no"); + "centerscreen,chrome,modal,resizable=" + (resizable ? "yes" : "no"); aParentWindow.openDialog(dialogURL, "", features, aInfo); return ("performed" in aInfo && aInfo.performed); }, _getTopBrowserWin: function PUIU__getTopBrowserWin() { return Services.wm.getMostRecentWindow("navigator:browser"); },
--- a/browser/components/sidebar/src/nsSidebar.js +++ b/browser/components/sidebar/src/nsSidebar.js @@ -105,19 +105,17 @@ function (aTitle, aContentURL, aCustomiz uri = Services.io.newURI(aContentURL, null, null); } catch(ex) { return; } win.PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , hiddenRows: [ "description" , "keyword" - , "location" - , "folderPicker" - , "loadInSidebar" ] + , "location" ] , uri: uri , title: aTitle , loadBookmarkInSidebar: true }, win); } nsSidebar.prototype.validateSearchEngine = function (engineURL, iconURL)
--- a/browser/devtools/scratchpad/scratchpad.js +++ b/browser/devtools/scratchpad/scratchpad.js @@ -151,32 +151,34 @@ var Scratchpad = { * An object with 3 properties: filename, text, and * executionContext. */ getState: function SP_getState() { return { filename: this.filename, text: this.getText(), - executionContext: this.executionContext + executionContext: this.executionContext, + saved: this.saved }; }, /** * Set the filename and execution context using the given state. Called * when scratchpad is being restored from a previous session. * * @param object aState * An object with filename and executionContext properties. */ setState: function SP_getState(aState) { if (aState.filename) { this.setFilename(aState.filename); } + this.saved = aState.saved; if (aState.executionContext == SCRATCHPAD_CONTEXT_BROWSER) { this.setBrowserContext(); } else { this.setContentContext(); } }, @@ -586,46 +588,46 @@ var Scratchpad = { openFile: function SP_openFile() { let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); fp.init(window, this.strings.GetStringFromName("openFile.title"), Ci.nsIFilePicker.modeOpen); fp.defaultString = ""; if (fp.show() != Ci.nsIFilePicker.returnCancel) { this.setFilename(fp.file.path); - this.importFromFile(fp.file); + this.importFromFile(fp.file, false, this.onTextSaved.bind(this)); } }, /** * Save the textbox content to the currently open file. */ saveFile: function SP_saveFile() { if (!this.filename) { return this.saveFileAs(); } let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); file.initWithPath(this.filename); - this.exportToFile(file, true); + this.exportToFile(file, true, false, this.onTextSaved.bind(this)); }, /** * Save the textbox content to a new file. */ saveFileAs: function SP_saveFileAs() { let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); fp.init(window, this.strings.GetStringFromName("saveFileAs"), Ci.nsIFilePicker.modeSave); fp.defaultString = "scratchpad.js"; if (fp.show() != Ci.nsIFilePicker.returnCancel) { - document.title = this.filename = fp.file.path; - this.exportToFile(fp.file, true); + this.setFilename(fp.file.path); + this.exportToFile(fp.file, true, false, this.onTextSaved.bind(this)); } }, /** * Open the Error Console. */ openErrorConsole: function SP_openErrorConsole() { @@ -754,16 +756,23 @@ var Scratchpad = { * editor initialization. */ onEditorLoad: function SP_onEditorLoad() { this.editor.addEventListener(SourceEditor.EVENTS.CONTEXT_MENU, this.onContextMenu); this.editor.focus(); this.editor.setCaretOffset(this.editor.getCharCount()); + + if (this.filename && !this.saved) { + this.onTextChanged(); + } + else if (this.filename && this.saved) { + this.onTextSaved(); + } }, /** * Insert text at the current caret location. * * @param string aText * The text you want to insert. */ @@ -819,16 +828,43 @@ var Scratchpad = { * Redo the previously undone action. */ redo: function SP_redo() { this.editor.redo(); }, /** + * This method adds a listener to the editor for text changes. Called when + * a scratchpad is saved, opened from file, or restored from a saved file. + */ + onTextSaved: function SP_onTextSaved(aStatus) + { + if (aStatus && !Components.isSuccessCode(aStatus)) { + return; + } + document.title = document.title.replace(/^\*/, ""); + this.saved = true; + this.editor.addEventListener(SourceEditor.EVENTS.TEXT_CHANGED, + this.onTextChanged); + }, + + /** + * The scratchpad handler for editor text change events. This handler + * indicates that there are unsaved changes in the UI. + */ + onTextChanged: function SP_onTextChanged() + { + document.title = "*" + document.title; + Scratchpad.saved = false; + Scratchpad.editor.removeEventListener(SourceEditor.EVENTS.TEXT_CHANGED, + Scratchpad.onTextChanged); + }, + + /** * The Scratchpad window unload event handler. This method unloads/destroys * the source editor. * * @param nsIDOMEvent aEvent */ onUnload: function SP_onUnload(aEvent) { if (aEvent.target != document) {
--- a/browser/devtools/scratchpad/test/Makefile.in +++ b/browser/devtools/scratchpad/test/Makefile.in @@ -52,11 +52,12 @@ include $(topsrcdir)/config/rules.mk browser_scratchpad_files.js \ browser_scratchpad_ui.js \ browser_scratchpad_bug_646070_chrome_context_pref.js \ browser_scratchpad_bug_660560_tab.js \ browser_scratchpad_open.js \ browser_scratchpad_restore.js \ browser_scratchpad_bug_679467_falsy.js \ browser_scratchpad_bug_699130_edit_ui_updates.js \ + browser_scratchpad_bug_669612_unsaved.js \ libs:: $(_BROWSER_TEST_FILES) $(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
new file mode 100644 --- /dev/null +++ b/browser/devtools/scratchpad/test/browser_scratchpad_bug_669612_unsaved.js @@ -0,0 +1,140 @@ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +// only finish() when correct number of tests are done +const expected = 5; +var count = 0; +function done() +{ + if (++count == expected) { + finish(); + } +} + +var ScratchpadManager = Scratchpad.ScratchpadManager; + + +function test() +{ + waitForExplicitFinish(); + + testListeners(); + testErrorStatus(); + testRestoreNotFromFile(); + testRestoreFromFileSaved(); + testRestoreFromFileUnsaved(); + + content.location = "data:text/html,<p>test star* UI for unsaved file changes"; +} + +function testListeners() +{ + let win = ScratchpadManager.openScratchpad(); + + win.addEventListener("load", function() { + let scratchpad = win.Scratchpad; + + scratchpad.setText("new text"); + ok(!isStar(win), "no star if scratchpad isn't from a file"); + + scratchpad.onTextSaved(); + ok(!isStar(win), "no star before changing text"); + + scratchpad.setText("new text2"); + ok(isStar(win), "shows star if scratchpad text changes"); + + scratchpad.onTextSaved(); + ok(!isStar(win), "no star if scratchpad was just saved"); + + scratchpad.undo(); + ok(isStar(win), "star if scratchpad undo"); + + win.close(); + done(); + }); +} + +function testErrorStatus() +{ + let win = ScratchpadManager.openScratchpad(); + + win.addEventListener("load", function() { + let scratchpad = win.Scratchpad; + + scratchpad.onTextSaved(Components.results.NS_ERROR_FAILURE); + scratchpad.setText("new text"); + ok(!isStar(win), "no star if file save failed"); + + win.close(); + done(); + }); +} + + +function testRestoreNotFromFile() +{ + let session = [{ + text: "test1", + executionContext: 1 + }]; + + let [win] = ScratchpadManager.restoreSession(session); + win.addEventListener("load", function() { + let scratchpad = win.Scratchpad; + + scratchpad.setText("new text"); + ok(!isStar(win), "no star if restored scratchpad isn't from a file"); + + win.close(); + done(); + }); +} + +function testRestoreFromFileSaved() +{ + let session = [{ + filename: "test.js", + text: "test1", + executionContext: 1, + saved: true + }]; + + let [win] = ScratchpadManager.restoreSession(session); + win.addEventListener("load", function() { + let scratchpad = win.Scratchpad; + + ok(!isStar(win), "no star before changing text in scratchpad restored from file"); + + scratchpad.setText("new text"); + ok(isStar(win), "star when text changed from scratchpad restored from file"); + + win.close(); + done(); + }); +} + +function testRestoreFromFileUnsaved() +{ + let session = [{ + filename: "test.js", + text: "test1", + executionContext: 1, + saved: false + }]; + + let [win] = ScratchpadManager.restoreSession(session); + win.addEventListener("load", function() { + let scratchpad = win.Scratchpad; + + ok(isStar(win), "star with scratchpad restored with unsaved text"); + + win.close(); + done(); + }); +} + +function isStar(win) +{ + return win.document.title.match(/^\*[^\*]/); +}
--- a/browser/installer/package-manifest.in +++ b/browser/installer/package-manifest.in @@ -439,16 +439,18 @@ @BINPATH@/defaults/autoconfig/prefcalls.js @BINPATH@/defaults/profile/prefs.js ; [Layout Engine Resources] ; Style Sheets, Graphics and other Resources used by the layout engine. @BINPATH@/res/EditorOverride.css @BINPATH@/res/contenteditable.css @BINPATH@/res/designmode.css +@BINPATH@/res/TopLevelImageDocument.css +@BINPATH@/res/TopLevelVideoDocument.css @BINPATH@/res/table-add-column-after-active.gif @BINPATH@/res/table-add-column-after-hover.gif @BINPATH@/res/table-add-column-after.gif @BINPATH@/res/table-add-column-before-active.gif @BINPATH@/res/table-add-column-before-hover.gif @BINPATH@/res/table-add-column-before.gif @BINPATH@/res/table-add-row-after-active.gif @BINPATH@/res/table-add-row-after-hover.gif
--- a/configure.in +++ b/configure.in @@ -4746,16 +4746,20 @@ if test -z "$XULRUNNER_STUB_NAME"; then fi AC_SUBST(XULRUNNER_STUB_NAME) AC_MSG_CHECKING([for application to build]) if test -z "$MOZ_BUILD_APP"; then AC_MSG_RESULT([browser]) MOZ_BUILD_APP=browser else + # default mobile to be mobile/xul + if test "$MOZ_BUILD_APP" = "mobile" ; then + MOZ_BUILD_APP=mobile/xul + fi # We have a valid application only if it has a build.mk file in its top # directory. if test ! -f "${srcdir}/${MOZ_BUILD_APP}/build.mk" ; then AC_MSG_RESULT([none]) AC_MSG_ERROR([--enable-application value not recognized (${MOZ_BUILD_APP}/build.mk does not exist).]) else AC_MSG_RESULT([$MOZ_BUILD_APP]) fi @@ -7111,16 +7115,31 @@ MOZ_ARG_ENABLE_BOOL(logrefcnt, _ENABLE_LOGREFCNT= ) if test "$_ENABLE_LOGREFCNT" = "1"; then AC_DEFINE(FORCE_BUILD_REFCNT_LOGGING) elif test -z "$_ENABLE_LOGREFCNT"; then AC_DEFINE(NO_BUILD_REFCNT_LOGGING) fi dnl ======================================================== +dnl moz_dump_painting +dnl ======================================================== +MOZ_ARG_ENABLE_BOOL(dump-painting, +[ --enable-dump-painting Enable paint debugging.], + MOZ_DUMP_PAINTING=1, + MOZ_DUMP_PAINTING= ) +if test -n "$MOZ_DUMP_PAINTING"; then + AC_DEFINE(MOZ_DUMP_PAINTING) + AC_DEFINE(MOZ_LAYERS_HAVE_LOG) +fi +if test -n "$MOZ_DEBUG"; then + AC_DEFINE(MOZ_DUMP_PAINTING) +fi + +dnl ======================================================== dnl = Enable trace malloc dnl ======================================================== NS_TRACE_MALLOC=${MOZ_TRACE_MALLOC} MOZ_ARG_ENABLE_BOOL(trace-malloc, [ --enable-trace-malloc Enable malloc tracing], NS_TRACE_MALLOC=1, NS_TRACE_MALLOC= ) if test "$NS_TRACE_MALLOC"; then
--- a/content/base/public/nsContentCreatorFunctions.h +++ b/content/base/public/nsContentCreatorFunctions.h @@ -53,17 +53,17 @@ class nsAString; class nsIContent; class nsIDocument; class nsINodeInfo; class imgIRequest; class nsNodeInfoManager; class nsGenericHTMLElement; nsresult -NS_NewElement(nsIContent** aResult, PRInt32 aElementType, +NS_NewElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo, mozilla::dom::FromParser aFromParser); nsresult NS_NewXMLElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo); /** * aNodeInfoManager must not be null.
--- a/content/base/public/nsContentErrors.h +++ b/content/base/public/nsContentErrors.h @@ -40,20 +40,16 @@ #ifndef nsContentErrors_h___ #define nsContentErrors_h___ /** Error codes for nsHTMLStyleSheet */ // XXX this is not really used #define NS_HTML_STYLE_PROPERTY_NOT_THERE \ NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 2) -/** Error codes for nsScriptLoader */ -#define NS_CONTENT_SCRIPT_IS_EVENTHANDLER \ - NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 3) - /** Error codes for image loading */ #define NS_ERROR_IMAGE_SRC_CHANGED \ NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 4) #define NS_ERROR_IMAGE_BLOCKED \ NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 5) /** Error codes for content policy blocking */
--- a/content/base/public/nsContentUtils.h +++ b/content/base/public/nsContentUtils.h @@ -71,23 +71,25 @@ static fp_except_t oldmask = fpsetmask(~ #include "nsIXPCScriptable.h" #include "nsDataHashtable.h" #include "nsIScriptRuntime.h" #include "nsIScriptGlobalObject.h" #include "nsIDOMEvent.h" #include "nsTArray.h" #include "nsTextFragment.h" #include "nsReadableUtils.h" -#include "mozilla/AutoRestore.h" #include "nsINode.h" #include "nsHashtable.h" #include "nsIDOMNode.h" #include "nsHtml5Parser.h" #include "nsIFragmentContentSink.h" #include "nsMathUtils.h" + +#include "mozilla/AutoRestore.h" +#include "mozilla/GuardObjects.h" #include "mozilla/TimeStamp.h" struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error! class nsIDOMScriptObjectFactory; class nsIXPConnect; class nsIContent; class nsIDOMKeyEvent; @@ -1715,20 +1717,20 @@ public: /** * Returns true if key input is restricted in DOM full-screen mode * to non-alpha-numeric key codes only. This mirrors the * "full-screen-api.key-input-restricted" pref. */ static bool IsFullScreenKeyInputRestricted(); /** - * Returns true if the doctree rooted at aDoc contains any plugins which - * we don't control event dispatch for, i.e. do any plugins in this doc tree - * receive key events outside of our control? This always returns false - * on MacOSX. + * Returns true if the doc tree branch which contains aDoc contains any + * plugins which we don't control event dispatch for, i.e. do any plugins + * in the same tab as this document receive key events outside of our + * control? This always returns false on MacOSX. */ static bool HasPluginWithUncontrolledEventDispatch(nsIDocument* aDoc); /** * Returns true if the content is in a document and contains a plugin * which we don't control event dispatch for, i.e. do any plugins in this * doc tree receive key events outside of our control? This always returns * false on MacOSX.
--- a/content/base/public/nsDOMFile.h +++ b/content/base/public/nsDOMFile.h @@ -44,22 +44,23 @@ #include "nsIDOMFile.h" #include "nsIDOMFileList.h" #include "nsIDOMFileError.h" #include "nsIInputStream.h" #include "nsIJSNativeInitializer.h" #include "nsIMutable.h" #include "nsCOMArray.h" #include "nsCOMPtr.h" -#include "mozilla/AutoRestore.h" #include "nsString.h" #include "nsIXMLHttpRequest.h" #include "prmem.h" #include "nsAutoPtr.h" +#include "mozilla/GuardObjects.h" + #ifndef PR_UINT64_MAX #define PR_UINT64_MAX (~(PRUint64)(0)) #endif class nsIFile; class nsIInputStream; class nsIClassInfo; class nsIBlobBuilder;
--- a/content/base/public/nsIContent.h +++ b/content/base/public/nsIContent.h @@ -69,19 +69,19 @@ class StyleRule; enum nsLinkState { eLinkState_Unknown = 0, eLinkState_Unvisited = 1, eLinkState_Visited = 2, eLinkState_NotLink = 3 }; // IID for the nsIContent interface -#define NS_ICONTENT_IID \ -{ 0xdec4b381, 0xa3fc, 0x402b, \ - { 0x83, 0x96, 0x0a, 0x7b, 0x37, 0x52, 0xcf, 0x70 } } +#define NS_ICONTENT_IID \ +{ 0xb651e0a7, 0x1471, 0x49cc, \ + { 0xb4, 0xe1, 0xc2, 0xca, 0x01, 0xfe, 0xb7, 0x80 } } /** * A node of content in a document's content model. This interface * is supported by all content objects. */ class nsIContent : public nsINode { public: #ifdef MOZILLA_INTERNAL_API @@ -748,32 +748,22 @@ public: * choice to do so. This is an efficiency measure. * * If you also need to determine whether the parser is the one creating your * element (through createElement() or cloneNode() generally) then add a * boolean aFromParser to the NS_NewXXX() constructor for your element and * have the parser pass true. See nsHTMLInputElement.cpp and * nsHTMLContentSink::MakeContentObject(). * - * It is ok to ignore an error returned from this function. However the - * following errors may be of interest to some callers: - * - * NS_ERROR_HTMLPARSER_BLOCK Returned by script elements to indicate - * that a script will be loaded asynchronously - * - * This means that implementations will have to deal with returned error - * codes being ignored. - * * @param aHaveNotified Whether there has been a * ContentInserted/ContentAppended notification for this content node * yet. */ - virtual nsresult DoneAddingChildren(bool aHaveNotified) + virtual void DoneAddingChildren(bool aHaveNotified) { - return NS_OK; } /** * For HTML textarea, select, applet, and object elements, returns * true if all children have been added OR if the element was not * created by the parser. Returns true for all other elements. * @returns false if the element was created by the parser and * it is an HTML textarea, select, applet, or object
--- a/content/base/public/nsIScriptElement.h +++ b/content/base/public/nsIScriptElement.h @@ -44,18 +44,18 @@ #include "nsCOMPtr.h" #include "nsIScriptLoaderObserver.h" #include "nsWeakPtr.h" #include "nsIParser.h" #include "nsContentCreatorFunctions.h" #include "nsIDOMHTMLScriptElement.h" #define NS_ISCRIPTELEMENT_IID \ -{ 0x6d625b30, 0xfac4, 0x11de, \ -{ 0x8a, 0x39, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 } } +{ 0x5bb3b905, 0x5988, 0x476f, \ + { 0x95, 0x4f, 0x99, 0x02, 0x59, 0x82, 0x24, 0x67 } } /** * Internal interface implemented by script elements */ class nsIScriptElement : public nsIScriptLoaderObserver { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTELEMENT_IID) @@ -212,18 +212,55 @@ public: * Retrieves a pointer to the creator parser if this has one or null if not */ already_AddRefed<nsIParser> GetCreatorParser() { nsCOMPtr<nsIParser> parser = do_QueryReferent(mCreatorParser); return parser.forget(); } + /** + * This method is called when the parser finishes creating the script + * element's children, if any are present. + * + * @return whether the parser will be blocked while this script is being + * loaded + */ + bool AttemptToExecute() + { + mDoneAddingChildren = true; + bool block = MaybeProcessScript(); + if (!mAlreadyStarted) { + // Need to lose parser-insertedness here to allow another script to cause + // execution later. + LoseParserInsertedness(); + } + return block; + } + protected: /** + * Processes the script if it's in the document-tree and links to or + * contains a script. Once it has been evaluated there is no way to make it + * reevaluate the script, you'll have to create a new element. This also means + * that when adding a src attribute to an element that already contains an + * inline script, the script referenced by the src attribute will not be + * loaded. + * + * In order to be able to use multiple childNodes, or to use the + * fallback mechanism of using both inline script and linked script you have + * to add all attributes and childNodes before adding the element to the + * document-tree. + * + * @return whether the parser will be blocked while this script is being + * loaded + */ + virtual bool MaybeProcessScript() = 0; + + /** * The start line number of the script. */ PRUint32 mLineNumber; /** * The "already started" flag per HTML5. */ bool mAlreadyStarted;
--- a/content/base/src/nsContentUtils.cpp +++ b/content/base/src/nsContentUtils.cpp @@ -5871,17 +5871,25 @@ DocTreeContainsWindowedPlugins(nsIDocume bool nsContentUtils::HasPluginWithUncontrolledEventDispatch(nsIDocument* aDoc) { #ifdef XP_MACOSX // We control dispatch to all mac plugins. return false; #endif bool result = false; - DocTreeContainsWindowedPlugins(aDoc, &result); + + // Find the top of the document's branch, the child of the chrome document. + nsIDocument* doc = aDoc; + nsIDocument* parent = nsnull; + while (doc && (parent = doc->GetParentDocument()) && !IsChromeDoc(parent)) { + doc = parent; + } + + DocTreeContainsWindowedPlugins(doc, &result); return result; } /* static */ bool nsContentUtils::HasPluginWithUncontrolledEventDispatch(nsIContent* aContent) { #ifdef XP_MACOSX
--- a/content/base/src/nsDocument.cpp +++ b/content/base/src/nsDocument.cpp @@ -4416,19 +4416,17 @@ nsDocument::CreateElementNS(const nsAStr nsCOMPtr<nsINodeInfo> nodeInfo; nsresult rv = nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName, mNodeInfoManager, nsIDOMNode::ELEMENT_NODE, getter_AddRefs(nodeInfo)); NS_ENSURE_SUCCESS(rv, rv); - PRInt32 ns = nodeInfo->NamespaceID(); - return NS_NewElement(aReturn, ns, - nodeInfo.forget(), NOT_FROM_PARSER); + return NS_NewElement(aReturn, nodeInfo.forget(), NOT_FROM_PARSER); } NS_IMETHODIMP nsDocument::CreateTextNode(const nsAString& aData, nsIDOMText** aReturn) { *aReturn = nsnull; nsCOMPtr<nsIContent> content; nsresult rv = CreateTextNode(aData, getter_AddRefs(content)); @@ -6749,18 +6747,17 @@ nsDocument::CreateElem(const nsAString& *aResult = nsnull; nsCOMPtr<nsINodeInfo> nodeInfo; mNodeInfoManager->GetNodeInfo(aName, aPrefix, aNamespaceID, nsIDOMNode::ELEMENT_NODE, getter_AddRefs(nodeInfo)); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); - return NS_NewElement(aResult, aNamespaceID, nodeInfo.forget(), - NOT_FROM_PARSER); + return NS_NewElement(aResult, nodeInfo.forget(), NOT_FROM_PARSER); } bool nsDocument::IsSafeToFlush() const { nsCOMPtr<nsIPresShell> shell = GetShell(); if (!shell) return true;
--- a/content/base/src/nsFrameLoader.cpp +++ b/content/base/src/nsFrameLoader.cpp @@ -100,26 +100,26 @@ #include "nsINameSpaceManager.h" #include "nsThreadUtils.h" #include "nsIContentViewer.h" #include "nsIView.h" #include "nsIDOMChromeWindow.h" #include "nsInProcessTabChildGlobal.h" -#include "mozilla/AutoRestore.h" -#include "mozilla/unused.h" #include "Layers.h" #include "ContentParent.h" #include "TabParent.h" -#include "mozilla/layout/RenderFrameParent.h" +#include "mozilla/GuardObjects.h" +#include "mozilla/Preferences.h" +#include "mozilla/unused.h" #include "mozilla/dom/Element.h" -#include "mozilla/Preferences.h" +#include "mozilla/layout/RenderFrameParent.h" #include "jsapi.h" using namespace mozilla; using namespace mozilla::dom; using namespace mozilla::layers; using namespace mozilla::layout; typedef FrameMetrics::ViewID ViewID;
--- a/content/base/src/nsGkAtomList.h +++ b/content/base/src/nsGkAtomList.h @@ -494,16 +494,17 @@ GK_ATOM(keycode, "keycode") GK_ATOM(keydown, "keydown") GK_ATOM(keypress, "keypress") GK_ATOM(keyset, "keyset") GK_ATOM(keytext, "keytext") GK_ATOM(keyup, "keyup") GK_ATOM(kind, "kind") GK_ATOM(label, "label") GK_ATOM(lang, "lang") +GK_ATOM(language, "language") GK_ATOM(last, "last") GK_ATOM(layer, "layer") GK_ATOM(layout, "layout") GK_ATOM(leading, "leading") GK_ATOM(leaf, "leaf") GK_ATOM(left, "left") GK_ATOM(leftmargin, "leftmargin") GK_ATOM(leftpadding, "leftpadding") @@ -1981,17 +1982,16 @@ GK_ATOM(containerRelevant, "container-re GK_ATOM(cycles, "cycles") GK_ATOM(datatable, "datatable") GK_ATOM(droppable, "droppable") GK_ATOM(eventFromInput, "event-from-input") GK_ATOM(InlineBlockFrame, "InlineBlockFrame") GK_ATOM(invalid, "invalid") GK_ATOM(item, "item") GK_ATOM(itemset, "itemset") -GK_ATOM(language, "language") GK_ATOM(lineNumber, "line-number") GK_ATOM(linkedPanel, "linkedpanel") GK_ATOM(live, "live") GK_ATOM(mixed, "mixed") GK_ATOM(multiline, "multiline") GK_ATOM(password, "password") GK_ATOM(posinset, "posinset") GK_ATOM(select1, "select1")
--- a/content/base/src/nsNameSpaceManager.cpp +++ b/content/base/src/nsNameSpaceManager.cpp @@ -219,38 +219,39 @@ NameSpaceManagerImpl::GetNameSpaceID(con NS_POSTCONDITION(nameSpaceID >= 0, "Bogus namespace ID"); return nameSpaceID; } return kNameSpaceID_Unknown; } nsresult -NS_NewElement(nsIContent** aResult, PRInt32 aElementType, +NS_NewElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo, FromParser aFromParser) { - if (aElementType == kNameSpaceID_XHTML) { + PRInt32 ns = aNodeInfo.get()->NamespaceID(); + if (ns == kNameSpaceID_XHTML) { return NS_NewHTMLElement(aResult, aNodeInfo, aFromParser); } #ifdef MOZ_XUL - if (aElementType == kNameSpaceID_XUL) { + if (ns == kNameSpaceID_XUL) { return NS_NewXULElement(aResult, aNodeInfo); } #endif - if (aElementType == kNameSpaceID_MathML) { + if (ns == kNameSpaceID_MathML) { return NS_NewMathMLElement(aResult, aNodeInfo); } - if (aElementType == kNameSpaceID_SVG) { + if (ns == kNameSpaceID_SVG) { return NS_NewSVGElement(aResult, aNodeInfo, aFromParser); } - if (aElementType == kNameSpaceID_XMLEvents) { + if (ns == kNameSpaceID_XMLEvents) { return NS_NewXMLEventsElement(aResult, aNodeInfo); } #ifdef MOZ_XTF - if (aElementType > kNameSpaceID_LastBuiltin) { + if (ns > kNameSpaceID_LastBuiltin) { nsIXTFService* xtfService = nsContentUtils::GetXTFService(); NS_ASSERTION(xtfService, "could not get xtf service"); if (xtfService && NS_SUCCEEDED(xtfService->CreateElement(aResult, aNodeInfo))) return NS_OK; } #endif return NS_NewXMLElement(aResult, aNodeInfo);
--- a/content/base/src/nsScriptElement.cpp +++ b/content/base/src/nsScriptElement.cpp @@ -142,52 +142,42 @@ void nsScriptElement::ContentInserted(nsIDocument *aDocument, nsIContent* aContainer, nsIContent* aChild, PRInt32 aIndexInContainer) { MaybeProcessScript(); } -nsresult +bool nsScriptElement::MaybeProcessScript() { nsCOMPtr<nsIContent> cont = do_QueryInterface((nsIScriptElement*) this); NS_ASSERTION(cont->DebugGetSlots()->mMutationObservers.Contains(this), "You forgot to add self as observer"); if (mAlreadyStarted || !mDoneAddingChildren || !cont->IsInDoc() || mMalformed || !HasScriptContent()) { - return NS_OK; + return false; } FreezeUriAsyncDefer(); mAlreadyStarted = true; nsIDocument* ownerDoc = cont->OwnerDoc(); nsCOMPtr<nsIParser> parser = ((nsIScriptElement*) this)->GetCreatorParser(); if (parser) { nsCOMPtr<nsIContentSink> sink = parser->GetContentSink(); if (sink) { nsCOMPtr<nsIDocument> parserDoc = do_QueryInterface(sink->GetTarget()); if (ownerDoc != parserDoc) { // Willful violation of HTML5 as of 2010-12-01 - return NS_OK; + return false; } } } nsRefPtr<nsScriptLoader> loader = ownerDoc->ScriptLoader(); - nsresult scriptresult = loader->ProcessScriptElement(this); - - // The only error we don't ignore is NS_ERROR_HTMLPARSER_BLOCK - // However we don't want to override other success values - // (such as NS_CONTENT_SCRIPT_IS_EVENTHANDLER) - if (NS_FAILED(scriptresult) && - scriptresult != NS_ERROR_HTMLPARSER_BLOCK) { - scriptresult = NS_OK; - } - - return scriptresult; + return loader->ProcessScriptElement(this); }
--- a/content/base/src/nsScriptElement.h +++ b/content/base/src/nsScriptElement.h @@ -67,23 +67,10 @@ public: protected: // Internal methods /** * Check if this element contains any script, linked or inline */ virtual bool HasScriptContent() = 0; - /** - * Processes the script if it's in the document-tree and links to or - * contains a script. Once it has been evaluated there is no way to make it - * reevaluate the script, you'll have to create a new element. This also means - * that when adding a src attribute to an element that already contains an - * inline script, the script referenced by the src attribute will not be - * loaded. - * - * In order to be able to use multiple childNodes, or to use the - * fallback mechanism of using both inline script and linked script you have - * to add all attributes and childNodes before adding the element to the - * document-tree. - */ - virtual nsresult MaybeProcessScript(); + virtual bool MaybeProcessScript(); };
--- a/content/base/src/nsScriptLoader.cpp +++ b/content/base/src/nsScriptLoader.cpp @@ -38,31 +38,29 @@ * ***** END LICENSE BLOCK ***** */ /* * A class that handles loading and evaluation of <script> elements. */ #include "jscntxt.h" #include "nsScriptLoader.h" -#include "nsIDOMCharacterData.h" #include "nsParserUtils.h" #include "nsICharsetConverterManager.h" #include "nsIUnicodeDecoder.h" #include "nsIContent.h" #include "mozilla/dom/Element.h" #include "nsGkAtoms.h" #include "nsNetUtil.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptContext.h" #include "nsIScriptRuntime.h" #include "nsIScriptSecurityManager.h" #include "nsIPrincipal.h" #include "nsContentPolicyUtils.h" -#include "nsIDOMWindow.h" #include "nsIHttpChannel.h" #include "nsIScriptElement.h" #include "nsIDOMHTMLScriptElement.h" #include "nsIDocShell.h" #include "nsContentUtils.h" #include "nsUnicharUtils.h" #include "nsAutoPtr.h" #include "nsIXPConnect.h" @@ -186,24 +184,25 @@ NS_IMPL_ISUPPORTS1(nsScriptLoader, nsISt // This means that it has both a for-attribute and a event-attribute. // Also, if the for-attribute has a value that matches "\s*window\s*", // and the event-attribute matches "\s*onload([ \(].*)?" then it isn't an // eventhandler. (both matches are case insensitive). // This is how IE seems to filter out a window's onload handler from a // <script for=... event=...> element. static bool -IsScriptEventHandler(nsIScriptElement *aScriptElement) +IsScriptEventHandler(nsIContent* aScriptElement) { - nsCOMPtr<nsIContent> contElement = do_QueryInterface(aScriptElement); - NS_ASSERTION(contElement, "nsIScriptElement isn't nsIContent"); + if (!aScriptElement->IsHTML()) { + return false; + } nsAutoString forAttr, eventAttr; - if (!contElement->GetAttr(kNameSpaceID_None, nsGkAtoms::_for, forAttr) || - !contElement->GetAttr(kNameSpaceID_None, nsGkAtoms::event, eventAttr)) { + if (!aScriptElement->GetAttr(kNameSpaceID_None, nsGkAtoms::_for, forAttr) || + !aScriptElement->GetAttr(kNameSpaceID_None, nsGkAtoms::event, eventAttr)) { return false; } const nsAString& for_str = nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(forAttr); if (!for_str.LowerCaseEqualsLiteral("window")) { return true; } @@ -363,54 +362,56 @@ public: , mRequest(aRequest) {} NS_IMETHODIMP Run() { return mLoader->ProcessRequest(mRequest); } }; -nsresult +bool nsScriptLoader::ProcessScriptElement(nsIScriptElement *aElement) { // We need a document to evaluate scripts. - NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE); + NS_ENSURE_TRUE(mDocument, false); // Check to see if scripts has been turned off. if (!mEnabled || !mDocument->IsScriptEnabled()) { - return NS_ERROR_NOT_AVAILABLE; + return false; } NS_ASSERTION(!aElement->IsMalformed(), "Executing malformed script"); - // Check that the script is not an eventhandler - if (IsScriptEventHandler(aElement)) { - return NS_CONTENT_SCRIPT_IS_EVENTHANDLER; + nsCOMPtr<nsIContent> scriptContent = do_QueryInterface(aElement); + + // Step 12. Check that the script is not an eventhandler + if (IsScriptEventHandler(scriptContent)) { + return false; } // Script evaluation can also be disabled in the current script // context even though it's enabled in the document. // XXX - still hard-coded for JS here, even though another language // may be specified. Should this check be made *after* we examine // the attributes to locate the script-type? // For now though, if JS is disabled we assume every language is // disabled. // XXX is this different from the mDocument->IsScriptEnabled() call? nsIScriptGlobalObject *globalObject = mDocument->GetScriptGlobalObject(); if (!globalObject) { - return NS_ERROR_NOT_AVAILABLE; + return false; } nsIScriptContext *context = globalObject->GetScriptContext( nsIProgrammingLanguage::JAVASCRIPT); // If scripts aren't enabled in the current context, there's no // point in going on. if (!context || !context->GetScriptsEnabled()) { - return NS_ERROR_NOT_AVAILABLE; + return false; } // Default script language is whatever the root element specifies // (which may come from a header or http-meta tag), or if there // is no root element, from the script global object. Element* rootElement = mDocument->GetRootElement(); PRUint32 typeID = rootElement ? rootElement->GetScriptTypeID() : context->GetScriptTypeID(); @@ -421,17 +422,17 @@ nsScriptLoader::ProcessScriptElement(nsI // Check the type attribute to determine language and version. // If type exists, it trumps the deprecated 'language=' aElement->GetScriptType(type); if (!type.IsEmpty()) { nsContentTypeParser parser(type); nsAutoString mimeType; rv = parser.GetType(mimeType); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, false); // Javascript keeps the fast path, optimized for most-likely type // Table ordered from most to least likely JS MIME types. // See bug 62485, feel free to add <script type="..."> survey data to it, // or to a new bug once 62485 is closed. static const char *jsTypes[] = { "text/javascript", "text/ecmascript", @@ -463,56 +464,54 @@ nsScriptLoader::ProcessScriptElement(nsI } if (typeID != nsIProgrammingLanguage::UNKNOWN) { // Get the version string, and ensure the language supports it. nsAutoString versionName; rv = parser.GetParameter("version", versionName); if (NS_FAILED(rv)) { // no version attribute - version remains 0. if (rv != NS_ERROR_INVALID_ARG) - return rv; + return false; } else { nsCOMPtr<nsIScriptRuntime> runtime; rv = NS_GetScriptRuntimeByID(typeID, getter_AddRefs(runtime)); if (NS_FAILED(rv)) { NS_ERROR("Failed to locate the language with this ID"); - return rv; + return false; } rv = runtime->ParseVersion(versionName, &version); if (NS_FAILED(rv)) { NS_WARNING("This script language version is not supported - ignored"); typeID = nsIProgrammingLanguage::UNKNOWN; } } } // Some js specifics yet to be abstracted. if (typeID == nsIProgrammingLanguage::JAVASCRIPT) { nsAutoString value; rv = parser.GetParameter("e4x", value); if (NS_FAILED(rv)) { if (rv != NS_ERROR_INVALID_ARG) - return rv; + return false; } else { if (value.Length() == 1 && value[0] == '1') // This means that we need to set JSOPTION_XML in the JS options. // We re-use our knowledge of the implementation to reuse // JSVERSION_HAS_XML as a safe version flag. // If version has JSVERSION_UNKNOWN (-1), then this is still OK. version |= js::VersionFlags::HAS_XML; } } } else { // no 'type=' element // "language" is a deprecated attribute of HTML, so we check it only for // HTML script elements. - nsCOMPtr<nsIDOMHTMLScriptElement> htmlScriptElement = - do_QueryInterface(aElement); - if (htmlScriptElement) { - htmlScriptElement->GetAttribute(NS_LITERAL_STRING("language"), language); + if (scriptContent->IsHTML()) { + scriptContent->GetAttr(kNameSpaceID_None, nsGkAtoms::language, language); if (!language.IsEmpty()) { if (nsParserUtils::IsJavaScriptLanguage(language, &version)) typeID = nsIProgrammingLanguage::JAVASCRIPT; else typeID = nsIProgrammingLanguage::UNKNOWN; // IE, Opera, etc. do not respect language version, so neither should // we at this late date in the browser wars saga. Note that this change // affects HTML but not XUL or SVG (but note also that XUL has its own @@ -523,40 +522,39 @@ nsScriptLoader::ProcessScriptElement(nsI "We rely on all languages having 0 as a version default"); version = 0; } } } // If we don't know the language, we don't know how to evaluate if (typeID == nsIProgrammingLanguage::UNKNOWN) { - return NS_ERROR_NOT_AVAILABLE; + return false; } // If not from a chrome document (which is always trusted), we need some way // of checking the language is "safe". Currently the only other language // impl is Python, and that is *not* safe in untrusted code - so fixing // this isn't a priority.! // See also similar code in nsXULContentSink.cpp if (typeID != nsIProgrammingLanguage::JAVASCRIPT && !nsContentUtils::IsChromeDoc(mDocument)) { NS_WARNING("Untrusted language called from non-chrome - ignored"); - return NS_ERROR_NOT_AVAILABLE; + return false; } - nsCOMPtr<nsIContent> eltContent(do_QueryInterface(aElement)); - eltContent->SetScriptTypeID(typeID); + scriptContent->SetScriptTypeID(typeID); - // Step 9. in the HTML5 spec + // Step 14. in the HTML5 spec nsRefPtr<nsScriptLoadRequest> request; if (aElement->GetScriptExternal()) { // external script nsCOMPtr<nsIURI> scriptURI = aElement->GetScriptURI(); if (!scriptURI) { - return NS_ERROR_NOT_AVAILABLE; + return false; } nsTArray<PreloadInfo>::index_type i = mPreloads.IndexOf(scriptURI.get(), 0, PreloadURIComparator()); if (i != nsTArray<PreloadInfo>::NoIndex) { // preloaded // note that a script-inserted script can steal a preload! request = mPreloads[i].mRequest; request->mElement = aElement; @@ -564,123 +562,122 @@ nsScriptLoader::ProcessScriptElement(nsI mPreloads.RemoveElementAt(i); // Double-check that the charset the preload used is the same as // the charset we have now. nsAutoString elementCharset; aElement->GetScriptCharset(elementCharset); if (elementCharset.Equals(preloadCharset)) { rv = CheckContentPolicy(mDocument, aElement, request->mURI, type); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, false); } else { // Drop the preload request = nsnull; } } if (!request) { // no usable preload request = new nsScriptLoadRequest(aElement, version); - NS_ENSURE_TRUE(request, NS_ERROR_OUT_OF_MEMORY); request->mURI = scriptURI; request->mIsInline = false; request->mLoading = true; rv = StartLoad(request, type); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, false); } request->mJSVersion = version; if (aElement->GetScriptAsync()) { mAsyncRequests.AppendElement(request); if (!request->mLoading) { // The script is available already. Run it ASAP when the event // loop gets a chance to spin. ProcessPendingRequestsAsync(); } - return NS_OK; + return false; } if (!aElement->GetParserCreated()) { // Violate the HTML5 spec in order to make LABjs and the "order" plug-in // for RequireJS work with their Gecko-sniffed code path. See // http://lists.w3.org/Archives/Public/public-html/2010Oct/0088.html mNonAsyncExternalScriptInsertedRequests.AppendElement(request); if (!request->mLoading) { // The script is available already. Run it ASAP when the event // loop gets a chance to spin. ProcessPendingRequestsAsync(); } - return NS_OK; + return false; } // we now have a parser-inserted request that may or may not be still // loading if (aElement->GetScriptDeferred()) { // We don't want to run this yet. // If we come here, the script is a parser-created script and it has // the defer attribute but not the async attribute. Since a // a parser-inserted script is being run, we came here by the parser // running the script, which means the parser is still alive and the // parse is ongoing. NS_ASSERTION(mDocument->GetCurrentContentSink() || aElement->GetParserCreated() == FROM_PARSER_XSLT, "Non-XSLT Defer script on a document without an active parser; bug 592366."); mDeferRequests.AppendElement(request); - return NS_OK; + return false; } if (aElement->GetParserCreated() == FROM_PARSER_XSLT) { // Need to maintain order for XSLT-inserted scripts NS_ASSERTION(!mParserBlockingRequest, "Parser-blocking scripts and XSLT scripts in the same doc!"); mXSLTRequests.AppendElement(request); if (!request->mLoading) { // The script is available already. Run it ASAP when the event // loop gets a chance to spin. ProcessPendingRequestsAsync(); } - return NS_ERROR_HTMLPARSER_BLOCK; + return true; } if (!request->mLoading && ReadyToExecuteScripts()) { // The request has already been loaded and there are no pending style // sheets. If the script comes from the network stream, cheat for // performance reasons and avoid a trip through the event loop. if (aElement->GetParserCreated() == FROM_PARSER_NETWORK) { - return ProcessRequest(request); + return ProcessRequest(request) == NS_ERROR_HTMLPARSER_BLOCK; } // Otherwise, we've got a document.written script, make a trip through // the event loop to hide the preload effects from the scripts on the // Web page. NS_ASSERTION(!mParserBlockingRequest, "There can be only one parser-blocking script at a time"); NS_ASSERTION(mXSLTRequests.IsEmpty(), "Parser-blocking scripts and XSLT scripts in the same doc!"); mParserBlockingRequest = request; ProcessPendingRequestsAsync(); - return NS_ERROR_HTMLPARSER_BLOCK; + return true; } // The script hasn't loaded yet or there's a style sheet blocking it. // The script will be run when it loads or the style sheet loads. NS_ASSERTION(!mParserBlockingRequest, "There can be only one parser-blocking script at a time"); NS_ASSERTION(mXSLTRequests.IsEmpty(), "Parser-blocking scripts and XSLT scripts in the same doc!"); mParserBlockingRequest = request; - return NS_ERROR_HTMLPARSER_BLOCK; + return true; } // inline script nsCOMPtr<nsIContentSecurityPolicy> csp; rv = mDocument->NodePrincipal()->GetCsp(getter_AddRefs(csp)); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, false); if (csp) { PR_LOG(gCspPRLog, PR_LOG_DEBUG, ("New ScriptLoader i ****with CSP****")); bool inlineOK; rv = csp->GetAllowsInlineScript(&inlineOK); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, false); if (!inlineOK) { PR_LOG(gCspPRLog, PR_LOG_DEBUG, ("CSP blocked inline scripts (2)")); // gather information to log with violation report nsIURI* uri = mDocument->GetDocumentURI(); nsCAutoString asciiSpec; uri->GetAsciiSpec(asciiSpec); nsAutoString scriptText; @@ -691,63 +688,62 @@ nsScriptLoader::ProcessScriptElement(nsI scriptText.Truncate(40); scriptText.Append(NS_LITERAL_STRING("...")); } csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_INLINE_SCRIPT, NS_ConvertUTF8toUTF16(asciiSpec), scriptText, aElement->GetScriptLineNumber()); - return NS_ERROR_FAILURE; + return false; } } request = new nsScriptLoadRequest(aElement, version); - NS_ENSURE_TRUE(request, NS_ERROR_OUT_OF_MEMORY); request->mJSVersion = version; request->mLoading = false; request->mIsInline = true; request->mURI = mDocument->GetDocumentURI(); request->mLineNo = aElement->GetScriptLineNumber(); if (aElement->GetParserCreated() == FROM_PARSER_XSLT && (!ReadyToExecuteScripts() || !mXSLTRequests.IsEmpty())) { // Need to maintain order for XSLT-inserted scripts NS_ASSERTION(!mParserBlockingRequest, "Parser-blocking scripts and XSLT scripts in the same doc!"); mXSLTRequests.AppendElement(request); - return NS_ERROR_HTMLPARSER_BLOCK; + return true; } if (aElement->GetParserCreated() == NOT_FROM_PARSER) { NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(), "A script-inserted script is inserted without an update batch?"); nsContentUtils::AddScriptRunner(new nsScriptRequestProcessor(this, request)); - return NS_OK; + return false; } if (aElement->GetParserCreated() == FROM_PARSER_NETWORK && !ReadyToExecuteScripts()) { NS_ASSERTION(!mParserBlockingRequest, "There can be only one parser-blocking script at a time"); mParserBlockingRequest = request; NS_ASSERTION(mXSLTRequests.IsEmpty(), "Parser-blocking scripts and XSLT scripts in the same doc!"); - return NS_ERROR_HTMLPARSER_BLOCK; + return true; } // We now have a document.written inline script or we have an inline script // from the network but there is no style sheet that is blocking scripts. // Don't check for style sheets blocking scripts in the document.write // case to avoid style sheet network activity affecting when // document.write returns. It's not really necessary to do this if // there's no document.write currently on the call stack. However, // this way matches IE more closely than checking if document.write // is on the call stack. NS_ASSERTION(nsContentUtils::IsSafeToRunScript(), "Not safe to run a parser-inserted script?"); - return ProcessRequest(request); + return ProcessRequest(request) == NS_ERROR_HTMLPARSER_BLOCK; } nsresult nsScriptLoader::ProcessRequest(nsScriptLoadRequest* aRequest) { NS_ASSERTION(nsContentUtils::IsSafeToRunScript(), "Processing requests when running scripts is unsafe.");
--- a/content/base/src/nsScriptLoader.h +++ b/content/base/src/nsScriptLoader.h @@ -103,24 +103,24 @@ public: * Process a script element. This will include both loading the * source of the element if it is not inline and evaluating * the script itself. * * If the script is an inline script that can be executed immediately * (i.e. there are no other scripts pending) then ScriptAvailable * and ScriptEvaluated will be called before the function returns. * - * If NS_ERROR_HTMLPARSER_BLOCK is returned the script could not be - * executed immediately. In this case ScriptAvailable is guaranteed - * to be called at a later point (as well as possibly ScriptEvaluated). + * If true is returned the script could not be executed immediately. + * In this case ScriptAvailable is guaranteed to be called at a later + * point (as well as possibly ScriptEvaluated). * * @param aElement The element representing the script to be loaded and * evaluated. */ - nsresult ProcessScriptElement(nsIScriptElement* aElement); + bool ProcessScriptElement(nsIScriptElement* aElement); /** * Gets the currently executing script. This is useful if you want to * generate a unique key based on the currently executing script. */ nsIScriptElement* GetCurrentScript() { return mCurrentScript; @@ -129,19 +129,18 @@ public: nsIScriptElement* GetCurrentParserInsertedScript() { return mCurrentParserInsertedScript; } /** * Whether the loader is enabled or not. * When disabled, processing of new script elements is disabled. - * Any call to ProcessScriptElement() will fail with a return code of - * NS_ERROR_NOT_AVAILABLE. Note that this DOES NOT disable - * currently loading or executing scripts. + * Any call to ProcessScriptElement() will return false. Note that + * this DOES NOT disable currently loading or executing scripts. */ bool GetEnabled() { return mEnabled; } void SetEnabled(bool aEnabled) { if (!mEnabled && aEnabled) {
--- a/content/base/src/nsXMLHttpRequest.cpp +++ b/content/base/src/nsXMLHttpRequest.cpp @@ -66,16 +66,17 @@ #include "nsDOMClassInfoID.h" #include "nsIDOMElement.h" #include "nsIDOMWindow.h" #include "nsIMIMEService.h" #include "nsCExternalHandlerService.h" #include "nsIVariant.h" #include "xpcprivate.h" #include "nsIParser.h" +#include "XPCQuickStubs.h" #include "nsStringStream.h" #include "nsIStreamConverterService.h" #include "nsICachingChannel.h" #include "nsContentUtils.h" #include "nsEventDispatcher.h" #include "nsDOMJSUtils.h" #include "nsCOMArray.h" #include "nsIScriptableUConv.h" @@ -1025,25 +1026,18 @@ NS_IMETHODIMP nsXMLHttpRequest::GetRespo switch (mResponseType) { case XML_HTTP_RESPONSE_TYPE_DEFAULT: case XML_HTTP_RESPONSE_TYPE_TEXT: case XML_HTTP_RESPONSE_TYPE_CHUNKED_TEXT: { nsString str; rv = GetResponseText(str); if (NS_FAILED(rv)) return rv; - if (str.IsVoid()) { - *aResult = JSVAL_NULL; - } else { - nsStringBuffer* buf; - *aResult = XPCStringConvert::ReadableToJSVal(aCx, str, &buf); - if (buf) { - str.ForgetSharedBuffer(); - } - } + NS_ENSURE_TRUE(xpc_qsStringToJsval(aCx, str, aResult), + NS_ERROR_OUT_OF_MEMORY); } break; case XML_HTTP_RESPONSE_TYPE_ARRAYBUFFER: case XML_HTTP_RESPONSE_TYPE_CHUNKED_ARRAYBUFFER: if ((mResponseType == XML_HTTP_RESPONSE_TYPE_ARRAYBUFFER && mState & XML_HTTP_REQUEST_DONE) || (mResponseType == XML_HTTP_RESPONSE_TYPE_CHUNKED_ARRAYBUFFER &&
--- a/content/html/content/src/nsGenericHTMLElement.cpp +++ b/content/html/content/src/nsGenericHTMLElement.cpp @@ -469,23 +469,16 @@ nsGenericHTMLElement::GetAccessKeyLabel( nsAutoString suffix; GetAccessKey(suffix); aLabel.Append(suffix); } return NS_OK; } -static bool -IsBody(nsIContent *aContent) -{ - return aContent->NodeInfo()->Equals(nsGkAtoms::body) && - aContent->IsHTML(); -} - static bool IS_TABLE_CELL(nsIAtom* frameType) { return nsGkAtoms::tableCellFrame == frameType || nsGkAtoms::bcTableCellFrame == frameType; } static bool IsOffsetParent(nsIFrame* aFrame) { @@ -511,17 +504,17 @@ nsGenericHTMLElement::GetOffsetRect(nsRe if (parent && parent->GetType() == nsGkAtoms::tableOuterFrame) { origin = parent->GetPositionIgnoringScrolling(); parent = parent->GetParent(); } Element* docElement = GetCurrentDoc()->GetRootElement(); nsIContent* content = frame->GetContent(); - if (content && (IsBody(content) || content == docElement)) { + if (content && (content->IsHTML(nsGkAtoms::body) || content == docElement)) { parent = frame; } else { const bool isPositioned = frame->GetStyleDisplay()->IsPositioned(); const bool isAbsolutelyPositioned = frame->GetStyleDisplay()->IsAbsolutelyPositioned(); origin += frame->GetPositionIgnoringScrolling(); @@ -545,17 +538,17 @@ nsGenericHTMLElement::GetOffsetRect(nsRe if (content) { // If we've hit the document element, break here. if (content == docElement) { break; } // Break if the ancestor frame type makes it suitable as offset parent // and this element is *not* positioned or if we found the body element. - if (isOffsetParent || IsBody(content)) { + if (isOffsetParent || content->IsHTML(nsGkAtoms::body)) { *aOffsetParent = content; NS_ADDREF(*aOffsetParent); break; } } } if (isAbsolutelyPositioned && !*aOffsetParent) { @@ -1085,18 +1078,18 @@ nsGenericHTMLElement::GetDraggable(bool* nsGkAtoms::_true, eIgnoreCase); return NS_OK; } NS_IMETHODIMP nsGenericHTMLElement::SetDraggable(bool aDraggable) { return SetAttrHelper(nsGkAtoms::draggable, - aDraggable ? NS_LITERAL_STRING("true") : - NS_LITERAL_STRING("false")); + aDraggable ? NS_LITERAL_STRING("true") + : NS_LITERAL_STRING("false")); } bool nsGenericHTMLElement::InNavQuirksMode(nsIDocument* aDoc) { return aDoc && aDoc->GetCompatibilityMode() == eCompatibility_NavQuirks; } @@ -1167,18 +1160,17 @@ nsGenericHTMLElement::FindAncestorForm(n // Make sure we don't end up finding a form that's anonymous from // our point of view. nsIContent* bindingParent = GetBindingParent(); nsIContent* content = this; while (content != bindingParent && content) { // If the current ancestor is a form, return it as our form - if (content->Tag() == nsGkAtoms::form && - content->IsHTML()) { + if (content->IsHTML(nsGkAtoms::form)) { #ifdef DEBUG if (!nsContentUtils::IsInSameAnonymousTree(this, content)) { // It's possible that we started unbinding at |content| or // some ancestor of it, and |content| and |this| used to all be // anonymous. Check for this the hard way. for (nsIContent* child = this; child != content; child = child->GetParent()) { NS_ASSERTION(child->GetParent()->IndexOf(child) != -1, @@ -1560,20 +1552,16 @@ nsGenericHTMLElement::GetPrimaryPresStat nsCAutoString key; GetLayoutHistoryAndKey(aContent, false, getter_AddRefs(history), key); if (history) { // Get the pres state for this key, if it doesn't exist, create one result = history->GetState(key, aPresState); if (!*aPresState) { *aPresState = new nsPresState(); - if (!*aPresState) { - return NS_ERROR_OUT_OF_MEMORY; - } - result = history->AddState(key, *aPresState); } } return result; } @@ -1654,17 +1642,17 @@ nsGenericHTMLElement::RestoreFormControl // XXX This creates a dependency between content and frames nsPresContext* nsGenericHTMLElement::GetPresContext() { // Get the document nsIDocument* doc = GetDocument(); if (doc) { - // Get presentation shell 0 + // Get presentation shell. nsIPresShell *presShell = doc->GetShell(); if (presShell) { return presShell->GetPresContext(); } } return nsnull; } @@ -1789,19 +1777,19 @@ bool nsGenericHTMLElement::ParseImageAttribute(nsIAtom* aAttribute, const nsAString& aString, nsAttrValue& aResult) { if ((aAttribute == nsGkAtoms::width) || (aAttribute == nsGkAtoms::height)) { return aResult.ParseSpecialIntValue(aString); } - else if ((aAttribute == nsGkAtoms::hspace) || - (aAttribute == nsGkAtoms::vspace) || - (aAttribute == nsGkAtoms::border)) { + if ((aAttribute == nsGkAtoms::hspace) || + (aAttribute == nsGkAtoms::vspace) || + (aAttribute == nsGkAtoms::border)) { return aResult.ParseIntWithBounds(aString, 0); } return false; } bool nsGenericHTMLElement::ParseFrameborderValue(const nsAString& aString, nsAttrValue& aResult) @@ -3132,18 +3120,17 @@ nsGenericHTMLFormElement::UpdateFormOwne NS_ASSERTION(GetCurrentDoc(), "The element should be in a document " "when UpdateFormOwner is called!"); NS_ASSERTION(!GetCurrentDoc() || element == GetCurrentDoc()->GetElementById(formId), "element should be equals to the current element " "associated with the id in @form!"); - if (element && element->Tag() == nsGkAtoms::form && - element->IsHTML()) { + if (element && element->IsHTML(nsGkAtoms::form)) { mForm = static_cast<nsHTMLFormElement*>(element); } } } else { // We now have a parent, so we may have picked up an ancestor form. Search // for it. Note that if mForm is already set we don't want to do this, // because that means someone (probably the content sink) has already set // it to the right value. Also note that even if being bound here didn't @@ -3311,19 +3298,18 @@ nsGenericHTMLFrameElement::GetFrameLoade { NS_IF_ADDREF(*aFrameLoader = mFrameLoader); return NS_OK; } NS_IMETHODIMP_(already_AddRefed<nsFrameLoader>) nsGenericHTMLFrameElement::GetFrameLoader() { - nsFrameLoader* loader = mFrameLoader; - NS_IF_ADDREF(loader); - return loader; + nsRefPtr<nsFrameLoader> loader = mFrameLoader; + return loader.forget(); } NS_IMETHODIMP nsGenericHTMLFrameElement::SwapFrameLoaders(nsIFrameLoaderOwner* aOtherOwner) { // We don't support this yet return NS_ERROR_NOT_IMPLEMENTED; } @@ -3393,18 +3379,17 @@ nsresult nsGenericHTMLFrameElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aValue, bool aNotify) { nsresult rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, aValue, aNotify); NS_ENSURE_SUCCESS(rv, rv); - if (aNameSpaceID == kNameSpaceID_None && - aName == nsGkAtoms::src) { + if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::src) { // Don't propagate error here. The attribute was successfully set, that's // what we should reflect. LoadSrc(); } return NS_OK; } @@ -3448,28 +3433,28 @@ nsGenericHTMLFrameElement::SizeOf() cons return size; } //---------------------------------------------------------------------- nsresult nsGenericHTMLElement::Blur() { - if (!ShouldBlur(this)) + if (!ShouldBlur(this)) { return NS_OK; + } nsIDocument* doc = GetCurrentDoc(); - if (!doc) + if (!doc) { return NS_OK; + } nsIDOMWindow* win = doc->GetWindow(); nsIFocusManager* fm = nsFocusManager::GetFocusManager(); return (win && fm) ? fm->ClearFocus(win) : NS_OK; - - return NS_OK; } nsresult nsGenericHTMLElement::Focus() { nsIFocusManager* fm = nsFocusManager::GetFocusManager(); nsCOMPtr<nsIDOMElement> elem = do_QueryInterface(this); return fm ? fm->SetFocus(elem, 0) : NS_OK; @@ -3500,18 +3485,18 @@ nsresult nsGenericHTMLElement::MozReques nsresult nsGenericHTMLElement::Click() { if (HasFlag(NODE_HANDLING_CLICK)) return NS_OK; // Strong in case the event kills it nsCOMPtr<nsIDocument> doc = GetCurrentDoc(); - nsCOMPtr<nsIPresShell> shell = nsnull; - nsRefPtr<nsPresContext> context = nsnull; + nsCOMPtr<nsIPresShell> shell; + nsRefPtr<nsPresContext> context; if (doc) { shell = doc->GetShell(); if (shell) { context = shell->GetPresContext(); } } SetFlags(NODE_HANDLING_CLICK); @@ -3648,18 +3633,19 @@ nsGenericHTMLElement::InternalGetExistin return mAttrsAndChildren.GetExistingAttrNameFromQName(aStr); } nsresult nsGenericHTMLElement::GetEditor(nsIEditor** aEditor) { *aEditor = nsnull; - if (!nsContentUtils::IsCallerTrustedForWrite()) + if (!nsContentUtils::IsCallerTrustedForWrite()) { return NS_ERROR_DOM_SECURITY_ERR; + } return GetEditorInternal(aEditor); } nsresult nsGenericHTMLElement::GetEditorInternal(nsIEditor** aEditor) { *aEditor = nsnull; @@ -3681,16 +3667,18 @@ nsGenericHTMLElement::GetAssociatedEdito nsIEditor* editor = nsnull; GetEditorInternal(&editor); return editor; } bool nsGenericHTMLElement::IsCurrentBodyElement() { + // TODO Bug 698498: Should this handle the case where GetBody returns a + // frameset? nsCOMPtr<nsIDOMHTMLBodyElement> bodyElement = do_QueryInterface(this); if (!bodyElement) { return false; } nsCOMPtr<nsIDOMHTMLDocument> htmlDocument = do_QueryInterface(GetCurrentDoc()); if (!htmlDocument) {
--- a/content/html/content/src/nsHTMLButtonElement.cpp +++ b/content/html/content/src/nsHTMLButtonElement.cpp @@ -546,18 +546,16 @@ NS_IMETHODIMP nsHTMLButtonElement::Reset() { return NS_OK; } NS_IMETHODIMP nsHTMLButtonElement::SubmitNamesValues(nsFormSubmission* aFormSubmission) { - nsresult rv = NS_OK; - // // We only submit if we were the button pressed // if (aFormSubmission->GetOriginatingElement() != this) { return NS_OK; } // Disabled elements don't submit @@ -573,27 +571,25 @@ nsHTMLButtonElement::SubmitNamesValues(n if (name.IsEmpty()) { return NS_OK; } // // Get the value // nsAutoString value; - rv = GetValue(value); + nsresult rv = GetValue(value); if (NS_FAILED(rv)) { return rv; } // // Submit // - rv = aFormSubmission->AddNameValuePair(name, value); - - return rv; + return aFormSubmission->AddNameValuePair(name, value); } void nsHTMLButtonElement::DoneCreatingElement() { if (!mInhibitStateRestoration) { // Restore state as needed. RestoreFormControlState(this, this); @@ -665,9 +661,8 @@ nsHTMLButtonElement::IntrinsicState() co nsEventStates state = nsGenericHTMLFormElement::IntrinsicState(); if (mForm && !mForm->GetValidity() && IsSubmitControl()) { state |= NS_EVENT_STATE_MOZ_SUBMITINVALID; } return state; } -
--- a/content/html/content/src/nsHTMLCanvasElement.cpp +++ b/content/html/content/src/nsHTMLCanvasElement.cpp @@ -272,17 +272,17 @@ nsHTMLCanvasElement::ExtractData(const n // XXX ERRMSG we need to report an error to developers here! (bug 329026) aFellBackToPNG = true; encoderType.AssignLiteral("image/png"); goto try_again; } NS_ENSURE_SUCCESS(rv, rv); - return CallQueryInterface(imgStream, aStream); + imgStream.forget(aStream); return NS_OK; } nsresult nsHTMLCanvasElement::ToDataURLImpl(const nsAString& aMimeType, nsIVariant* aEncoderOptions, nsAString& aDataURL) { @@ -401,17 +401,18 @@ nsHTMLCanvasElement::MozGetAsFileImpl(co void* imgData = nsnull; rv = NS_ReadInputStreamToBuffer(stream, &imgData, imgSize); NS_ENSURE_SUCCESS(rv, rv); // The DOMFile takes ownership of the buffer nsRefPtr<nsDOMMemoryFile> file = new nsDOMMemoryFile(imgData, imgSize, aName, type); - return CallQueryInterface(file, aResult); + file.forget(aResult); + return NS_OK; } nsresult nsHTMLCanvasElement::GetContextHelper(const nsAString& aContextId, bool aForceThebes, nsICanvasRenderingContextInternal **aContext) { NS_ENSURE_ARG(aContext); @@ -452,17 +453,17 @@ nsHTMLCanvasElement::GetContextHelper(co } rv = ctx->SetCanvasElement(this); if (NS_FAILED(rv)) { *aContext = nsnull; return rv; } - *aContext = ctx.forget().get(); + ctx.forget(aContext); return rv; } NS_IMETHODIMP nsHTMLCanvasElement::GetContext(const nsAString& aContextId, const jsval& aContextOptions, nsISupports **aContext) @@ -567,20 +568,18 @@ nsHTMLCanvasElement::MozGetIPCContext(co // XXX ERRMSG we need to report an error to developers here! (bug 329026) return NS_ERROR_DOM_SECURITY_ERR; } // We only support 2d shmem contexts for now. if (!aContextId.Equals(NS_LITERAL_STRING("2d"))) return NS_ERROR_INVALID_ARG; - nsresult rv; - if (mCurrentContextId.IsEmpty()) { - rv = GetContextHelper(aContextId, false, getter_AddRefs(mCurrentContext)); + nsresult rv = GetContextHelper(aContextId, false, getter_AddRefs(mCurrentContext)); NS_ENSURE_SUCCESS(rv, rv); if (!mCurrentContext) { return NS_OK; } mCurrentContext->SetIsIPC(true); rv = UpdateContext(); @@ -597,37 +596,36 @@ nsHTMLCanvasElement::MozGetIPCContext(co } nsresult nsHTMLCanvasElement::UpdateContext(nsIPropertyBag *aNewContextOptions) { if (!mCurrentContext) return NS_OK; - nsresult rv = NS_OK; nsIntSize sz = GetWidthHeight(); - rv = mCurrentContext->SetIsOpaque(GetIsOpaque()); + nsresult rv = mCurrentContext->SetIsOpaque(GetIsOpaque()); if (NS_FAILED(rv)) { mCurrentContext = nsnull; - mCurrentContextId.AssignLiteral(""); + mCurrentContextId.Truncate(); return rv; } rv = mCurrentContext->SetContextOptions(aNewContextOptions); if (NS_FAILED(rv)) { mCurrentContext = nsnull; - mCurrentContextId.AssignLiteral(""); + mCurrentContextId.Truncate(); return rv; } rv = mCurrentContext->SetDimensions(sz.width, sz.height); if (NS_FAILED(rv)) { mCurrentContext = nsnull; - mCurrentContextId.AssignLiteral(""); + mCurrentContextId.Truncate(); return rv; } return rv; } nsIFrame * nsHTMLCanvasElement::GetPrimaryCanvasFrame() @@ -710,20 +708,20 @@ nsHTMLCanvasElement::CountContexts() { if (mCurrentContext) return 1; return 0; } nsICanvasRenderingContextInternal * -nsHTMLCanvasElement::GetContextAtIndex (PRInt32 index) +nsHTMLCanvasElement::GetContextAtIndex(PRInt32 index) { if (mCurrentContext && index == 0) - return mCurrentContext.get(); + return mCurrentContext; return NULL; } bool nsHTMLCanvasElement::GetIsOpaque() { return HasAttr(kNameSpaceID_None, nsGkAtoms::moz_opaque);
--- a/content/html/content/src/nsHTMLFieldSetElement.cpp +++ b/content/html/content/src/nsHTMLFieldSetElement.cpp @@ -58,17 +58,17 @@ nsHTMLFieldSetElement::nsHTMLFieldSetEle // We start out enabled AddStatesSilently(NS_EVENT_STATE_ENABLED); } nsHTMLFieldSetElement::~nsHTMLFieldSetElement() { PRUint32 length = mDependentElements.Length(); - for (PRUint32 i=0; i<length; ++i) { + for (PRUint32 i = 0; i < length; ++i) { mDependentElements[i]->ForgetFieldSet(this); } } // nsISupports NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsHTMLFieldSetElement, nsGenericHTMLFormElement) @@ -259,14 +259,14 @@ nsHTMLFieldSetElement::NotifyElementsFor * However, this method shouldn't be called very often in normal use cases. */ if (!mElements) { mElements = new nsContentList(this, MatchListedElements, nsnull, nsnull, true); } PRUint32 length = mElements->Length(true); - for (PRUint32 i=0; i<length; ++i) { + for (PRUint32 i = 0; i < length; ++i) { static_cast<nsGenericHTMLFormElement*>(mElements->GetNodeAt(i)) ->FieldSetFirstLegendChanged(aNotify); } }
--- a/content/html/content/src/nsHTMLFontElement.cpp +++ b/content/html/content/src/nsHTMLFontElement.cpp @@ -42,16 +42,17 @@ #include "nsIDOMEventTarget.h" #include "nsGenericHTMLElement.h" #include "nsGkAtoms.h" #include "nsStyleConsts.h" #include "nsPresContext.h" #include "nsMappedAttributes.h" #include "nsRuleData.h" #include "nsIDocument.h" +#include "nsAlgorithm.h" using namespace mozilla; class nsHTMLFontElement : public nsGenericHTMLElement, public nsIDOMHTMLFontElement { public: nsHTMLFontElement(already_AddRefed<nsINodeInfo> aNodeInfo); @@ -212,17 +213,17 @@ MapAttributesIntoRule(const nsMappedAttr nsAttrValue::ValueType unit = value->Type(); if (unit == nsAttrValue::eInteger || unit == nsAttrValue::eEnum) { PRInt32 size; if (unit == nsAttrValue::eEnum) // int (+/-) size = value->GetEnumValue() + 3; else size = value->GetIntegerValue(); - size = ((0 < size) ? ((size < 8) ? size : 7) : 1); + size = clamped(size, 1, 7); fontSize->SetIntValue(size, eCSSUnit_Enumerated); } } } } // fontWeight: int nsCSSValue* fontWeight = aData->ValueForFontWeight();
--- a/content/html/content/src/nsHTMLFormElement.cpp +++ b/content/html/content/src/nsHTMLFormElement.cpp @@ -1993,79 +1993,69 @@ nsHTMLFormElement::GetNextRadioButton(co return NS_OK; } NS_IMETHODIMP nsHTMLFormElement::WalkRadioGroup(const nsAString& aName, nsIRadioVisitor* aVisitor, bool aFlushContent) { - nsresult rv = NS_OK; - if (aName.IsEmpty()) { // // XXX If the name is empty, it's not stored in the control list. There // *must* be a more efficient way to do this. // nsCOMPtr<nsIFormControl> control; PRUint32 len = GetElementCount(); - for (PRUint32 i=0; i<len; i++) { + for (PRUint32 i = 0; i < len; i++) { control = GetElementAt(i); if (control->GetType() == NS_FORM_INPUT_RADIO) { - nsCOMPtr<nsIContent> controlContent(do_QueryInterface(control)); - if (controlContent) { - if (controlContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, - EmptyString(), eCaseMatters)) { - if (!aVisitor->Visit(control)) { - break; - } - } + nsCOMPtr<nsIContent> controlContent = do_QueryInterface(control); + if (controlContent && + controlContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, + EmptyString(), eCaseMatters) && + !aVisitor->Visit(control)) { + break; } } } - } else { - // - // Get the control / list of controls from the form using form["name"] - // - nsCOMPtr<nsISupports> item; - item = DoResolveName(aName, aFlushContent); - rv = item ? NS_OK : NS_ERROR_FAILURE; + return NS_OK; + } + + // Get the control / list of controls from the form using form["name"] + nsCOMPtr<nsISupports> item = DoResolveName(aName, aFlushContent); + if (!item) { + return NS_ERROR_FAILURE; + } - if (item) { - // - // If it's just a lone radio button, then select it. - // - nsCOMPtr<nsIFormControl> formControl(do_QueryInterface(item)); - if (formControl) { - if (formControl->GetType() == NS_FORM_INPUT_RADIO) { - aVisitor->Visit(formControl); - } - } else { - nsCOMPtr<nsIDOMNodeList> nodeList(do_QueryInterface(item)); - if (nodeList) { - PRUint32 length = 0; - nodeList->GetLength(&length); - for (PRUint32 i=0; i<length; i++) { - nsCOMPtr<nsIDOMNode> node; - nodeList->Item(i, getter_AddRefs(node)); - nsCOMPtr<nsIFormControl> formControl(do_QueryInterface(node)); - if (formControl) { - if (formControl->GetType() == NS_FORM_INPUT_RADIO) { - if (!aVisitor->Visit(formControl)) { - break; - } - } - } - } - } - } + // If it's just a lone radio button, then select it. + nsCOMPtr<nsIFormControl> formControl = do_QueryInterface(item); + if (formControl) { + if (formControl->GetType() == NS_FORM_INPUT_RADIO) { + aVisitor->Visit(formControl); + } + return NS_OK; + } + + nsCOMPtr<nsIDOMNodeList> nodeList = do_QueryInterface(item); + if (!nodeList) { + return NS_OK; + } + PRUint32 length = 0; + nodeList->GetLength(&length); + for (PRUint32 i = 0; i < length; i++) { + nsCOMPtr<nsIDOMNode> node; + nodeList->Item(i, getter_AddRefs(node)); + nsCOMPtr<nsIFormControl> formControl = do_QueryInterface(node); + if (formControl && formControl->GetType() == NS_FORM_INPUT_RADIO && + !aVisitor->Visit(formControl)) { + break; } } - - return rv; + return NS_OK; } NS_IMETHODIMP nsHTMLFormElement::AddToRadioGroup(const nsAString& aName, nsIFormControl* aRadio) { nsCOMPtr<nsIContent> element = do_QueryInterface(aRadio); NS_ASSERTION(element, "radio controls have to be content elements!"); @@ -2176,23 +2166,22 @@ nsFormControlList::DropFormReference() mForm = nsnull; Clear(); } void nsFormControlList::Clear() { // Null out childrens' pointer to me. No refcounting here - PRInt32 i; - for (i = mElements.Length()-1; i >= 0; i--) { + for (PRInt32 i = mElements.Length() - 1; i >= 0; i--) { mElements[i]->ClearForm(false); } mElements.Clear(); - for (i = mNotInElements.Length()-1; i >= 0; i--) { + for (PRInt32 i = mNotInElements.Length() - 1; i >= 0; i--) { mNotInElements[i]->ClearForm(false); } mNotInElements.Clear(); mNameLookupTable.Clear(); } void @@ -2272,41 +2261,43 @@ nsFormControlList::Item(PRUint32 aIndex, NS_IMETHODIMP nsFormControlList::NamedItem(const nsAString& aName, nsIDOMNode** aReturn) { FlushPendingNotifications(); *aReturn = nsnull; - nsresult rv = NS_OK; - nsCOMPtr<nsISupports> supports; - if (!mNameLookupTable.Get(aName, getter_AddRefs(supports))) // key not found - return rv; - - if (supports) { - // We found something, check if it's a node - CallQueryInterface(supports, aReturn); + if (!mNameLookupTable.Get(aName, getter_AddRefs(supports))) { + // key not found + return NS_OK; + } - if (!*aReturn) { - // If not, we check if it's a node list. - nsCOMPtr<nsIDOMNodeList> nodeList(do_QueryInterface(supports)); - NS_ASSERTION(nodeList, "Huh, what's going one here?"); - - if (nodeList) { - // And since we're only asking for one node here, we return the first - // one from the list. - rv = nodeList->Item(0, aReturn); - } - } + if (!supports) { + return NS_OK; } - return rv; + // We found something, check if it's a node + CallQueryInterface(supports, aReturn); + if (*aReturn) { + return NS_OK; + } + + // If not, we check if it's a node list. + nsCOMPtr<nsIDOMNodeList> nodeList = do_QueryInterface(supports); + NS_ASSERTION(nodeList, "Huh, what's going one here?"); + if (!nodeList) { + return NS_OK; + } + + // And since we're only asking for one node here, we return the first + // one from the list. + return nodeList->Item(0, aReturn); } nsISupports* nsFormControlList::NamedItemInternal(const nsAString& aName, bool aFlushContent) { if (aFlushContent) { FlushPendingNotifications(); @@ -2323,36 +2314,35 @@ nsFormControlList::AddElementToTable(nsG return NS_OK; } nsCOMPtr<nsISupports> supports; mNameLookupTable.Get(aName, getter_AddRefs(supports)); if (!supports) { // No entry found, add the form control - NS_ENSURE_TRUE( mNameLookupTable.Put(aName, - NS_ISUPPORTS_CAST(nsIContent*, aChild)), - NS_ERROR_FAILURE ); + NS_ENSURE_TRUE(mNameLookupTable.Put(aName, + NS_ISUPPORTS_CAST(nsIContent*, aChild)), + NS_ERROR_FAILURE); } else { // Found something in the hash, check its type - nsCOMPtr<nsIContent> content(do_QueryInterface(supports)); + nsCOMPtr<nsIContent> content = do_QueryInterface(supports); if (content) { // Check if the new content is the same as the one we found in the // hash, if it is then we leave it in the hash as it is, this will // happen if a form control has both a name and an id with the same // value if (content == aChild) { return NS_OK; } // Found an element, create a list, add the element to the list and put // the list in the hash nsSimpleContentList *list = new nsSimpleContentList(mForm); - NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY); NS_ASSERTION(content->GetParent(), "Item in list without parent"); // Determine the ordering between the new and old element. bool newFirst = nsContentUtils::PositionIsBefore(aChild, content); list->AppendElement(newFirst ? aChild : content); list->AppendElement(newFirst ? content : aChild); @@ -2360,31 +2350,31 @@ nsFormControlList::AddElementToTable(nsG nsCOMPtr<nsISupports> listSupports = do_QueryObject(list); // Replace the element with the list. NS_ENSURE_TRUE(mNameLookupTable.Put(aName, listSupports), NS_ERROR_FAILURE); } else { // There's already a list in the hash, add the child to the list - nsCOMPtr<nsIDOMNodeList> nodeList(do_QueryInterface(supports)); + nsCOMPtr<nsIDOMNodeList> nodeList = do_QueryInterface(supports); NS_ENSURE_TRUE(nodeList, NS_ERROR_FAILURE); // Upcast, uggly, but it works! - nsSimpleContentList *list = static_cast<nsSimpleContentList *> - ((nsIDOMNodeList *)nodeList.get()); + nsSimpleContentList *list = + static_cast<nsSimpleContentList*>(nodeList.get()); NS_ASSERTION(list->Length() > 1, "List should have been converted back to a single element"); // Fast-path appends; this check is ok even if the child is // already in the list, since if it tests true the child would // have come at the end of the list, and the PositionIsBefore // will test false. - if(nsContentUtils::PositionIsBefore(list->GetNodeAt(list->Length() - 1), aChild)) { + if (nsContentUtils::PositionIsBefore(list->GetNodeAt(list->Length() - 1), aChild)) { list->AppendElement(aChild); return NS_OK; } // If a control has a name equal to its id, it could be in the // list already. if (list->IndexOf(aChild) != -1) { return NS_OK; @@ -2450,18 +2440,17 @@ nsFormControlList::RemoveElementFromTabl return NS_OK; } nsCOMPtr<nsIDOMNodeList> nodeList(do_QueryInterface(supports)); NS_ENSURE_TRUE(nodeList, NS_ERROR_FAILURE); // Upcast, uggly, but it works! - nsBaseContentList *list = static_cast<nsBaseContentList *> - ((nsIDOMNodeList *)nodeList.get()); + nsBaseContentList *list = static_cast<nsBaseContentList*>(nodeList.get()); list->RemoveElement(aChild); PRUint32 length = 0; list->GetLength(&length); if (!length) { // If the list is empty we remove if from our hash, this shouldn't
--- a/content/html/content/src/nsHTMLFormElement.h +++ b/content/html/content/src/nsHTMLFormElement.h @@ -69,17 +69,17 @@ public: typedef const nsAString* KeyTypePointer; nsStringCaseInsensitiveHashKey(KeyTypePointer aStr) : mStr(*aStr) { } //take it easy just deal HashKey nsStringCaseInsensitiveHashKey(const nsStringCaseInsensitiveHashKey& toCopy) : mStr(toCopy.mStr) { } ~nsStringCaseInsensitiveHashKey() { } KeyType GetKey() const { return mStr; } bool KeyEquals(const KeyTypePointer aKey) const { - return mStr.Equals(*aKey,nsCaseInsensitiveStringComparator()); + return mStr.Equals(*aKey, nsCaseInsensitiveStringComparator()); } static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; } static PLDHashNumber HashKey(const KeyTypePointer aKey) { nsAutoString tmKey(*aKey); ToLowerCase(tmKey); return HashString(tmKey);
--- a/content/html/content/src/nsHTMLImageElement.cpp +++ b/content/html/content/src/nsHTMLImageElement.cpp @@ -673,13 +673,13 @@ nsImageLoadingContent::CORSMode nsHTMLImageElement::GetCORSMode() { nsImageLoadingContent::CORSMode ret = nsImageLoadingContent::CORS_NONE; const nsAttrValue* value = GetParsedAttr(nsGkAtoms::crossorigin); if (value) { NS_ASSERTION(value->Type() == nsAttrValue::eEnum, "Why is this not an enum value?"); - ret = (nsImageLoadingContent::CORSMode) value->GetEnumValue(); + ret = nsImageLoadingContent::CORSMode(value->GetEnumValue()); } return ret; }
--- a/content/html/content/src/nsHTMLInputElement.cpp +++ b/content/html/content/src/nsHTMLInputElement.cpp @@ -114,16 +114,17 @@ #include "mozAutoDocUpdate.h" #include "nsContentCreatorFunctions.h" #include "nsCharSeparatedTokenizer.h" #include "nsContentUtils.h" #include "nsRadioVisitor.h" #include "mozilla/LookAndFeel.h" +#include "mozilla/Util.h" // DebugOnly using namespace mozilla; using namespace mozilla::dom; // XXX align=left, hspace, vspace, border? other nav4 attrs static NS_DEFINE_CID(kXULControllersCID, NS_XULCONTROLLERS_CID); @@ -252,18 +253,16 @@ public: protected: nsRefPtr<nsHTMLInputElement> mInput; PopupControlState mPopupControlState; }; NS_IMETHODIMP AsyncClickHandler::Run() { - nsresult rv; - // Get parent nsPIDOMWindow object. nsCOMPtr<nsIDocument> doc = mInput->OwnerDoc(); nsPIDOMWindow* win = doc->GetWindow(); if (!win) { return NS_ERROR_FAILURE; } @@ -291,19 +290,20 @@ AsyncClickHandler::Run() "FileUpload", title); nsCOMPtr<nsIFilePicker> filePicker = do_CreateInstance("@mozilla.org/filepicker;1"); if (!filePicker) return NS_ERROR_FAILURE; bool multi = mInput->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple); - rv = filePicker->Init(win, title, multi ? - (PRInt16)nsIFilePicker::modeOpenMultiple : - (PRInt16)nsIFilePicker::modeOpen); + nsresult rv = filePicker->Init(win, title, + multi + ? static_cast<PRInt16>(nsIFilePicker::modeOpenMultiple) + : static_cast<PRInt16>(nsIFilePicker::modeOpen)); NS_ENSURE_SUCCESS(rv, rv); if (mInput->HasAttr(kNameSpaceID_None, nsGkAtoms::accept)) { PRInt32 filters = mInput->GetFilterFromAccept(); if (filters) { // We add |filterAll| to be sure the user always has a sane fallback. filePicker->AppendFilters(filters | nsIFilePicker::filterAll); @@ -480,19 +480,17 @@ UploadLastDir::FetchLastUsedDirectory(ns contentPrefService->GetPref(uri, CPS_PREF_NAME, nsnull, getter_AddRefs(pref)); nsString prefStr; pref->GetAsAString(prefStr); nsCOMPtr<nsILocalFile> localFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID); if (!localFile) return NS_ERROR_OUT_OF_MEMORY; localFile->InitWithPath(prefStr); - - *aFile = localFile; - NS_ADDREF(*aFile); + localFile.forget(aFile); } return NS_OK; } nsresult UploadLastDir::StoreLastUsedDirectory(nsIURI* aURI, nsILocalFile* aFile) { NS_PRECONDITION(aURI, "aURI is null"); @@ -548,25 +546,32 @@ static nsresult FireEventForAccessibilit // // construction, destruction // NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Input) nsHTMLInputElement::nsHTMLInputElement(already_AddRefed<nsINodeInfo> aNodeInfo, FromParser aFromParser) - : nsGenericHTMLFormElement(aNodeInfo), - mType(kInputDefaultType->value), - mBitField(0) + : nsGenericHTMLFormElement(aNodeInfo) + , mType(kInputDefaultType->value) + , mDisabledChanged(false) + , mValueChanged(false) + , mCheckedChanged(false) + , mChecked(false) + , mHandlingSelectEvent(false) + , mShouldInitChecked(false) + , mParserCreating(aFromParser != NOT_FROM_PARSER) + , mInInternalActivate(false) + , mCheckedIsToggled(false) + , mIndeterminate(false) + , mInhibitRestoration(aFromParser & FROM_PARSER_FRAGMENT) + , mCanShowValidUI(true) + , mCanShowInvalidUI(true) { - SET_BOOLBIT(mBitField, BF_PARSER_CREATING, aFromParser); - SET_BOOLBIT(mBitField, BF_INHIBIT_RESTORATION, - aFromParser & mozilla::dom::FROM_PARSER_FRAGMENT); - SET_BOOLBIT(mBitField, BF_CAN_SHOW_INVALID_UI, true); - SET_BOOLBIT(mBitField, BF_CAN_SHOW_VALID_UI, true); mInputData.mState = new nsTextEditorState(this); NS_ADDREF(mInputData.mState); if (!gUploadLastDir) nsHTMLInputElement::InitUploadLastDir(); // Set up our default state. By default we're enabled (since we're // a control type that can be disabled but not actually disabled @@ -658,30 +663,30 @@ NS_IMPL_NSICONSTRAINTVALIDATION_EXCEPT_S // nsIDOMNode nsresult nsHTMLInputElement::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const { *aResult = nsnull; nsCOMPtr<nsINodeInfo> ni = aNodeInfo; - nsHTMLInputElement *it = new nsHTMLInputElement(ni.forget(), NOT_FROM_PARSER); - - nsCOMPtr<nsINode> kungFuDeathGrip = it; + nsRefPtr<nsHTMLInputElement> it = + new nsHTMLInputElement(ni.forget(), NOT_FROM_PARSER); + nsresult rv = CopyInnerTo(it); NS_ENSURE_SUCCESS(rv, rv); switch (mType) { case NS_FORM_INPUT_EMAIL: case NS_FORM_INPUT_SEARCH: case NS_FORM_INPUT_TEXT: case NS_FORM_INPUT_PASSWORD: case NS_FORM_INPUT_TEL: case NS_FORM_INPUT_URL: - if (GetValueChanged()) { + if (mValueChanged) { // We don't have our default value anymore. Set our value on // the clone. nsAutoString value; GetValueInternal(value); // SetValueInternal handles setting the VALUE_CHANGED bit for us it->SetValueInternal(value, false, true); } break; @@ -692,33 +697,32 @@ nsHTMLInputElement::Clone(nsINodeInfo *a GetDisplayFileName(it->mStaticDocFileList); } else { it->mFiles.Clear(); it->mFiles.AppendObjects(mFiles); } break; case NS_FORM_INPUT_RADIO: case NS_FORM_INPUT_CHECKBOX: - if (GET_BOOLBIT(mBitField, BF_CHECKED_CHANGED)) { + if (mCheckedChanged) { // We no longer have our original checked state. Set our // checked state on the clone. - it->DoSetChecked(GetChecked(), false, true); + it->DoSetChecked(mChecked, false, true); } break; case NS_FORM_INPUT_IMAGE: if (it->OwnerDoc()->IsStaticDocument()) { CreateStaticImageClone(it); } break; default: break; } - kungFuDeathGrip.swap(*aResult); - + it.forget(aResult); return NS_OK; } nsresult nsHTMLInputElement::BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, const nsAString* aValue, bool aNotify) { @@ -726,28 +730,28 @@ nsHTMLInputElement::BeforeSetAttr(PRInt3 // // When name or type changes, radio should be removed from radio group. // (type changes are handled in the form itself currently) // If the parser is not done creating the radio, we also should not do it. // if ((aName == nsGkAtoms::name || (aName == nsGkAtoms::type && !mForm)) && mType == NS_FORM_INPUT_RADIO && - (mForm || !(GET_BOOLBIT(mBitField, BF_PARSER_CREATING)))) { + (mForm || !mParserCreating)) { WillRemoveFromRadioGroup(); } else if (aNotify && aName == nsGkAtoms::src && mType == NS_FORM_INPUT_IMAGE) { if (aValue) { LoadImage(*aValue, true, aNotify); } else { // Null value means the attr got unset; drop the image CancelImageRequests(aNotify); } } else if (aNotify && aName == nsGkAtoms::disabled) { - SET_BOOLBIT(mBitField, BF_DISABLED_CHANGED, true); + mDisabledChanged = true; } } return nsGenericHTMLFormElement::BeforeSetAttr(aNameSpaceID, aName, aValue, aNotify); } nsresult @@ -759,43 +763,40 @@ nsHTMLInputElement::AfterSetAttr(PRInt32 // // When name or type changes, radio should be added to radio group. // (type changes are handled in the form itself currently) // If the parser is not done creating the radio, we also should not do it. // if ((aName == nsGkAtoms::name || (aName == nsGkAtoms::type && !mForm)) && mType == NS_FORM_INPUT_RADIO && - (mForm || !(GET_BOOLBIT(mBitField, BF_PARSER_CREATING)))) { + (mForm || !mParserCreating)) { AddedToRadioGroup(); UpdateValueMissingValidityStateForRadio(false); } // If @value is changed and BF_VALUE_CHANGED is false, @value is the value // of the element so, if the value of the element is different than @value, // we have to re-set it. This is only the case when GetValueMode() returns // VALUE_MODE_VALUE. if (aName == nsGkAtoms::value && - !GetValueChanged() && GetValueMode() == VALUE_MODE_VALUE) { + !mValueChanged && GetValueMode() == VALUE_MODE_VALUE) { SetDefaultValueAsValue(); } // // Checked must be set no matter what type of control it is, since - // GetChecked() must reflect the new value - if (aName == nsGkAtoms::checked && - !GET_BOOLBIT(mBitField, BF_CHECKED_CHANGED)) { + // mChecked must reflect the new value + if (aName == nsGkAtoms::checked && !mCheckedChanged) { // Delay setting checked if the parser is creating this element (wait // until everything is set) - if (GET_BOOLBIT(mBitField, BF_PARSER_CREATING)) { - SET_BOOLBIT(mBitField, BF_SHOULD_INIT_CHECKED, true); + if (mParserCreating) { + mShouldInitChecked = true; } else { - bool defaultChecked; - GetDefaultChecked(&defaultChecked); - DoSetChecked(defaultChecked, true, true); + DoSetChecked(DefaultChecked(), true, true); SetCheckedChanged(false); } } if (aName == nsGkAtoms::type) { if (!aValue) { // We're now a text input. Note that we have to handle this manually, // since removing an attribute (which is what happened, since aValue is @@ -892,25 +893,25 @@ NS_IMPL_UINT_ATTR_NON_ZERO_DEFAULT_VALUE NS_IMPL_STRING_ATTR(nsHTMLInputElement, Pattern, pattern) NS_IMPL_STRING_ATTR(nsHTMLInputElement, Placeholder, placeholder) NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLInputElement, Type, type, kInputDefaultType->tag) NS_IMETHODIMP nsHTMLInputElement::GetIndeterminate(bool* aValue) { - *aValue = GET_BOOLBIT(mBitField, BF_INDETERMINATE); + *aValue = mIndeterminate; return NS_OK; } nsresult nsHTMLInputElement::SetIndeterminateInternal(bool aValue, bool aShouldInvalidate) { - SET_BOOLBIT(mBitField, BF_INDETERMINATE, aValue); + mIndeterminate = aValue; if (aShouldInvalidate) { // Repaint the frame nsIFrame* frame = GetPrimaryFrame(); if (frame) frame->InvalidateFrameSubtree(); } @@ -1006,49 +1007,55 @@ nsHTMLInputElement::SetValue(const nsASt } return NS_OK; } NS_IMETHODIMP nsHTMLInputElement::GetList(nsIDOMHTMLElement** aValue) { + *aValue = nsnull; + nsAutoString dataListId; GetAttr(kNameSpaceID_None, nsGkAtoms::list, dataListId); - if (!dataListId.IsEmpty()) { - nsIDocument* doc = GetCurrentDoc(); - - if (doc) { - Element* elem = doc->GetElementById(dataListId); - - if (elem && elem->IsHTML(nsGkAtoms::datalist)) { - CallQueryInterface(elem, aValue); - return NS_OK; - } - } + if (dataListId.IsEmpty()) { + return NS_OK; + } + + nsIDocument* doc = GetCurrentDoc(); + if (!doc) { + return NS_OK; } - *aValue = nsnull; + Element* element = doc->GetElementById(dataListId); + if (!element || !element->IsHTML(nsGkAtoms::datalist)) { + return NS_OK; + } + + CallQueryInterface(element, aValue); return NS_OK; } NS_IMETHODIMP nsHTMLInputElement::MozGetFileNameArray(PRUint32 *aLength, PRUnichar ***aFileNames) { if (!nsContentUtils::IsCallerTrustedForCapability("UniversalFileRead")) { // Since this function returns full paths it's important that normal pages // can't call it. return NS_ERROR_DOM_SECURITY_ERR; } *aLength = mFiles.Count(); PRUnichar **ret = static_cast<PRUnichar **>(NS_Alloc(mFiles.Count() * sizeof(PRUnichar*))); - - for (PRInt32 i = 0; i < mFiles.Count(); i++) { + if (!ret) { + return NS_ERROR_OUT_OF_MEMORY; + } + + for (PRInt32 i = 0; i < mFiles.Count(); i++) { nsString str; mFiles[i]->GetMozFullPathInternal(str); ret[i] = NS_strdup(str.get()); } *aFileNames = ret; return NS_OK; @@ -1238,17 +1245,17 @@ void nsHTMLInputElement::GetDisplayFileName(nsAString& aValue) const { if (OwnerDoc()->IsStaticDocument()) { aValue = mStaticDocFileList; return; } aValue.Truncate(); - for (PRUint32 i = 0; i < (PRUint32)mFiles.Count(); ++i) { + for (PRInt32 i = 0; i < mFiles.Count(); ++i) { nsString str; mFiles[i]->GetMozFullPathInternal(str); if (i == 0) { aValue.Append(str); } else { aValue.Append(NS_LITERAL_STRING(", ") + str); } @@ -1314,17 +1321,17 @@ nsHTMLInputElement::GetFiles() const nsresult nsHTMLInputElement::UpdateFileList() { if (mFileList) { mFileList->Clear(); const nsCOMArray<nsIDOMFile>& files = GetFiles(); - for (PRUint32 i = 0; i < (PRUint32)files.Count(); ++i) { + for (PRInt32 i = 0; i < files.Count(); ++i) { if (!mFileList->Append(files[i])) { return NS_ERROR_FAILURE; } } } return NS_OK; } @@ -1340,17 +1347,17 @@ nsHTMLInputElement::SetValueInternal(con switch (GetValueMode()) { case VALUE_MODE_VALUE: { // At the moment, only single line text control have to sanitize their value // Because we have to create a new string for that, we should prevent doing // it if it's useless. nsAutoString value(aValue); - if (!GET_BOOLBIT(mBitField, BF_PARSER_CREATING)) { + if (!mParserCreating) { SanitizeValue(value); } if (aSetValueChanged) { SetValueChanged(true); } mInputData.mState->SetValue(value, aUserInput); @@ -1389,61 +1396,61 @@ nsHTMLInputElement::SetValueInternal(con // This return statement is required for some compilers. return NS_OK; } NS_IMETHODIMP nsHTMLInputElement::SetValueChanged(bool aValueChanged) { - bool valueChangedBefore = GetValueChanged(); - - SET_BOOLBIT(mBitField, BF_VALUE_CHANGED, aValueChanged); + bool valueChangedBefore = mValueChanged; + + mValueChanged = aValueChanged; if (valueChangedBefore != aValueChanged) { UpdateState(true); } return NS_OK; } NS_IMETHODIMP nsHTMLInputElement::GetChecked(bool* aChecked) { - *aChecked = GetChecked(); + *aChecked = mChecked; return NS_OK; } void nsHTMLInputElement::SetCheckedChanged(bool aCheckedChanged) { DoSetCheckedChanged(aCheckedChanged, true); } void nsHTMLInputElement::DoSetCheckedChanged(bool aCheckedChanged, bool aNotify) { if (mType == NS_FORM_INPUT_RADIO) { - if (GET_BOOLBIT(mBitField, BF_CHECKED_CHANGED) != aCheckedChanged) { + if (mCheckedChanged != aCheckedChanged) { nsCOMPtr<nsIRadioVisitor> visitor = new nsRadioSetCheckedChangedVisitor(aCheckedChanged); VisitGroup(visitor, aNotify); } } else { SetCheckedChangedInternal(aCheckedChanged); } } void nsHTMLInputElement::SetCheckedChangedInternal(bool aCheckedChanged) { - bool checkedChangedBefore = GetCheckedChanged(); - - SET_BOOLBIT(mBitField, BF_CHECKED_CHANGED, aCheckedChanged); + bool checkedChangedBefore = mCheckedChanged; + + mCheckedChanged = aCheckedChanged; // This method can't be called when we are not authorized to notify // so we do not need a aNotify parameter. if (checkedChangedBefore != aCheckedChanged) { UpdateState(true); } } @@ -1452,85 +1459,70 @@ nsHTMLInputElement::SetChecked(bool aChe { return DoSetChecked(aChecked, true, true); } nsresult nsHTMLInputElement::DoSetChecked(bool aChecked, bool aNotify, bool aSetValueChanged) { - nsresult rv = NS_OK; - // If the user or JS attempts to set checked, whether it actually changes the // value or not, we say the value was changed so that defaultValue don't // affect it no more. if (aSetValueChanged) { DoSetCheckedChanged(true, aNotify); } - // // Don't do anything if we're not changing whether it's checked (it would // screw up state actually, especially when you are setting radio button to // false) - // - if (GetChecked() == aChecked) { + if (mChecked == aChecked) { + return NS_OK; + } + + // Set checked + if (mType != NS_FORM_INPUT_RADIO) { + SetCheckedInternal(aChecked, aNotify); return NS_OK; } - // - // Set checked - // - if (mType == NS_FORM_INPUT_RADIO) { - // - // For radio button, we need to do some extra fun stuff - // - if (aChecked) { - rv = RadioSetChecked(aNotify); - } else { - nsIRadioGroupContainer* container = GetRadioGroupContainer(); - if (container) { - nsAutoString name; - GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); - container->SetCurrentRadioButton(name, nsnull); - } - // SetCheckedInternal is going to ask all radios to update their - // validity state. We have to be sure the radio group container knows - // the currently selected radio. - SetCheckedInternal(false, aNotify); - } - } else { - SetCheckedInternal(aChecked, aNotify); + // For radio button, we need to do some extra fun stuff + if (aChecked) { + return RadioSetChecked(aNotify); } - return rv; + nsIRadioGroupContainer* container = GetRadioGroupContainer(); + if (container) { + nsAutoString name; + GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); + container->SetCurrentRadioButton(name, nsnull); + } + // SetCheckedInternal is going to ask all radios to update their + // validity state. We have to be sure the radio group container knows + // the currently selected radio. + SetCheckedInternal(false, aNotify); + return NS_OK; } nsresult nsHTMLInputElement::RadioSetChecked(bool aNotify) { - nsresult rv = NS_OK; - - // // Find the selected radio button so we can deselect it - // nsCOMPtr<nsIDOMHTMLInputElement> currentlySelected = GetSelectedRadioButton(); - // // Deselect the currently selected radio button - // if (currentlySelected) { // Pass true for the aNotify parameter since the currently selected // button is already in the document. - static_cast<nsHTMLInputElement*> - (static_cast<nsIDOMHTMLInputElement*>(currentlySelected))->SetCheckedInternal(false, true); + static_cast<nsHTMLInputElement*>(currentlySelected.get()) + ->SetCheckedInternal(false, true); } - // // Let the group know that we are now the One True Radio Button - // + nsresult rv = NS_OK; nsIRadioGroupContainer* container = GetRadioGroupContainer(); if (container) { nsAutoString name; GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); rv = container->SetCurrentRadioButton(name, this); } // SetCheckedInternal is going to ask all radios to update their @@ -1561,28 +1553,27 @@ nsHTMLInputElement::GetRadioGroupContain } return static_cast<nsDocument*>(GetCurrentDoc()); } already_AddRefed<nsIDOMHTMLInputElement> nsHTMLInputElement::GetSelectedRadioButton() { - nsIDOMHTMLInputElement* selected; nsIRadioGroupContainer* container = GetRadioGroupContainer(); - if (!container) { return nsnull; } nsAutoString name; GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); - container->GetCurrentRadioButton(name, &selected); - return selected; + nsCOMPtr<nsIDOMHTMLInputElement> selected; + container->GetCurrentRadioButton(name, getter_AddRefs(selected)); + return selected.forget(); } nsresult nsHTMLInputElement::MaybeSubmitForm(nsPresContext* aPresContext) { if (!mForm) { // Nothing to do here. return NS_OK; @@ -1591,50 +1582,46 @@ nsHTMLInputElement::MaybeSubmitForm(nsPr nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell(); if (!shell) { return NS_OK; } // Get the default submit element nsIFormControl* submitControl = mForm->GetDefaultSubmitElement(); if (submitControl) { - nsCOMPtr<nsIContent> submitContent(do_QueryInterface(submitControl)); + nsCOMPtr<nsIContent> submitContent = do_QueryInterface(submitControl); NS_ASSERTION(submitContent, "Form control not implementing nsIContent?!"); // Fire the button's onclick handler and let the button handle // submitting the form. nsMouseEvent event(true, NS_MOUSE_CLICK, nsnull, nsMouseEvent::eReal); nsEventStatus status = nsEventStatus_eIgnore; shell->HandleDOMEventWithTarget(submitContent, &event, &status); } else if (mForm->HasSingleTextControl() && (mForm->HasAttr(kNameSpaceID_None, nsGkAtoms::novalidate) || mForm->CheckValidFormSubmission())) { // TODO: removing this code and have the submit event sent by the form, // bug 592124. // If there's only one text control, just submit the form // Hold strong ref across the event - nsRefPtr<nsHTMLFormElement> form(mForm); + nsRefPtr<nsHTMLFormElement> form = mForm; nsFormEvent event(true, NS_FORM_SUBMIT); - nsEventStatus status = nsEventStatus_eIgnore; + nsEventStatus status = nsEventStatus_eIgnore; shell->HandleDOMEventWithTarget(mForm, &event, &status); } return NS_OK; } void nsHTMLInputElement::SetCheckedInternal(bool aChecked, bool aNotify) { - // // Set the value - // - SET_BOOLBIT(mBitField, BF_CHECKED, aChecked); - - // + mChecked = aChecked; + // Notify the frame - // if (mType == NS_FORM_INPUT_CHECKBOX || mType == NS_FORM_INPUT_RADIO) { nsIFrame* frame = GetPrimaryFrame(); if (frame) { frame->InvalidateFrameSubtree(); } } UpdateAllValidityStates(aNotify); @@ -1642,41 +1629,41 @@ nsHTMLInputElement::SetCheckedInternal(b // Notify the document that the CSS :checked pseudoclass for this element // has changed state. UpdateState(aNotify); } NS_IMETHODIMP nsHTMLInputElement::Focus() { - if (mType == NS_FORM_INPUT_FILE) { - // for file inputs, focus the button instead - nsIFrame* frame = GetPrimaryFrame(); - if (frame) { - nsIFrame* childFrame = frame->GetFirstPrincipalChild(); - while (childFrame) { - // see if the child is a button control - nsCOMPtr<nsIFormControl> formCtrl = - do_QueryInterface(childFrame->GetContent()); - if (formCtrl && formCtrl->GetType() == NS_FORM_INPUT_BUTTON) { - nsCOMPtr<nsIDOMElement> element(do_QueryInterface(formCtrl)); - nsIFocusManager* fm = nsFocusManager::GetFocusManager(); - if (fm && element) - fm->SetFocus(element, 0); - break; + if (mType != NS_FORM_INPUT_FILE) { + return nsGenericHTMLElement::Focus(); + } + + // For file inputs, focus the button instead. + nsIFrame* frame = GetPrimaryFrame(); + if (frame) { + for (nsIFrame* childFrame = frame->GetFirstPrincipalChild(); + childFrame; + childFrame = childFrame->GetNextSibling()) { + // See if the child is a button control. + nsCOMPtr<nsIFormControl> formCtrl = + do_QueryInterface(childFrame->GetContent()); + if (formCtrl && formCtrl->GetType() == NS_FORM_INPUT_BUTTON) { + nsCOMPtr<nsIDOMElement> element = do_QueryInterface(formCtrl); + nsIFocusManager* fm = nsFocusManager::GetFocusManager(); + if (fm && element) { + fm->SetFocus(element, 0); } - - childFrame = childFrame->GetNextSibling(); + break; } } - - return NS_OK; } - return nsGenericHTMLElement::Focus(); + return NS_OK; } NS_IMETHODIMP nsHTMLInputElement::Select() { if (!IsSingleLineTextControl(false)) { return NS_OK; } @@ -1715,23 +1702,23 @@ nsHTMLInputElement::Select() } bool nsHTMLInputElement::DispatchSelectEvent(nsPresContext* aPresContext) { nsEventStatus status = nsEventStatus_eIgnore; // If already handling select event, don't dispatch a second. - if (!GET_BOOLBIT(mBitField, BF_HANDLING_SELECT_EVENT)) { + if (!mHandlingSelectEvent) { nsEvent event(nsContentUtils::IsCallerChrome(), NS_FORM_SELECTED); - SET_BOOLBIT(mBitField, BF_HANDLING_SELECT_EVENT, true); + mHandlingSelectEvent = true; nsEventDispatcher::Dispatch(static_cast<nsIContent*>(this), aPresContext, &event, nsnull, &status); - SET_BOOLBIT(mBitField, BF_HANDLING_SELECT_EVENT, false); + mHandlingSelectEvent = false; } // If the DOM event was not canceled (e.g. by a JS event handler // returning false) return (status == nsEventStatus_eIgnore); } void @@ -1763,31 +1750,31 @@ nsHTMLInputElement::FireAsyncClickHandle bool nsHTMLInputElement::NeedToInitializeEditorForEvent(nsEventChainPreVisitor& aVisitor) const { // We only need to initialize the editor for single line input controls because they // are lazily initialized. We don't need to initialize the control for // certain types of events, because we know that those events are safe to be // handled without the editor being initialized. These events include: // mousein/move/out, and DOM mutation events. - if (IsSingleLineTextControl(false) && - aVisitor.mEvent->eventStructType != NS_MUTATION_EVENT) { - - switch (aVisitor.mEvent->message) { - case NS_MOUSE_MOVE: - case NS_MOUSE_ENTER: - case NS_MOUSE_EXIT: - case NS_MOUSE_ENTER_SYNTH: - case NS_MOUSE_EXIT_SYNTH: - return false; - break; - } + if (!IsSingleLineTextControl(false) || + aVisitor.mEvent->eventStructType == NS_MUTATION_EVENT) { + return false; + } + + switch (aVisitor.mEvent->message) { + case NS_MOUSE_MOVE: + case NS_MOUSE_ENTER: + case NS_MOUSE_EXIT: + case NS_MOUSE_ENTER_SYNTH: + case NS_MOUSE_EXIT_SYNTH: + return false; + default: return true; } - return false; } nsresult nsHTMLInputElement::PreHandleEvent(nsEventChainPreVisitor& aVisitor) { // Do not process any DOM events if the element is disabled aVisitor.mCanHandle = false; if (IsElementDisabledForEvents(aVisitor.mEvent->message, GetPrimaryFrame())) { @@ -1822,69 +1809,68 @@ nsHTMLInputElement::PreHandleEvent(nsEve // // Track whether we're in the outermost Dispatch invocation that will // cause activation of the input. That is, if we're a click event, or a // DOMActivate that was dispatched directly, this will be set, but if we're // a DOMActivate dispatched from click handling, it will not be set. bool outerActivateEvent = (NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent) || - (aVisitor.mEvent->message == NS_UI_ACTIVATE && - !GET_BOOLBIT(mBitField, BF_IN_INTERNAL_ACTIVATE))); + (aVisitor.mEvent->message == NS_UI_ACTIVATE && !mInInternalActivate)); if (outerActivateEvent) { aVisitor.mItemFlags |= NS_OUTER_ACTIVATE_EVENT; } bool originalCheckedValue = false; if (outerActivateEvent) { - SET_BOOLBIT(mBitField, BF_CHECKED_IS_TOGGLED, false); + mCheckedIsToggled = false; switch(mType) { case NS_FORM_INPUT_CHECKBOX: { - if (GET_BOOLBIT(mBitField, BF_INDETERMINATE)) { + if (mIndeterminate) { // indeterminate is always set to FALSE when the checkbox is toggled SetIndeterminateInternal(false, false); aVisitor.mItemFlags |= NS_ORIGINAL_INDETERMINATE_VALUE; } GetChecked(&originalCheckedValue); DoSetChecked(!originalCheckedValue, true, true); - SET_BOOLBIT(mBitField, BF_CHECKED_IS_TOGGLED, true); + mCheckedIsToggled = true; } break; case NS_FORM_INPUT_RADIO: { nsCOMPtr<nsIDOMHTMLInputElement> selectedRadioButton = GetSelectedRadioButton(); aVisitor.mItemData = selectedRadioButton; - originalCheckedValue = GetChecked(); + originalCheckedValue = mChecked; if (!originalCheckedValue) { DoSetChecked(true, true, true); - SET_BOOLBIT(mBitField, BF_CHECKED_IS_TOGGLED, true); + mCheckedIsToggled = true; } } break; case NS_FORM_INPUT_SUBMIT: case NS_FORM_INPUT_IMAGE: if(mForm) { // tell the form that we are about to enter a click handler. // that means that if there are scripted submissions, the // latest one will be deferred until after the exit point of the handler. mForm->OnSubmitClickBegin(this); } break; default: break; - } //switch + } } if (originalCheckedValue) { aVisitor.mItemFlags |= NS_ORIGINAL_CHECKED_VALUE; } // If NS_EVENT_FLAG_NO_CONTENT_DISPATCH is set we will not allow content to handle // this event. But to allow middle mouse button paste to work we must allow @@ -1981,19 +1967,19 @@ nsHTMLInputElement::PostHandleEvent(nsEv if (aVisitor.mEventStatus != nsEventStatus_eConsumeNoDefault && !IsSingleLineTextControl(true) && NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent)) { nsUIEvent actEvent(NS_IS_TRUSTED_EVENT(aVisitor.mEvent), NS_UI_ACTIVATE, 1); nsCOMPtr<nsIPresShell> shell = aVisitor.mPresContext->GetPresShell(); if (shell) { nsEventStatus status = nsEventStatus_eIgnore; - SET_BOOLBIT(mBitField, BF_IN_INTERNAL_ACTIVATE, true); + mInInternalActivate = true; rv = shell->HandleDOMEventWithTarget(this, &actEvent, &status); - SET_BOOLBIT(mBitField, BF_IN_INTERNAL_ACTIVATE, false); + mInInternalActivate = false; // If activate is cancelled, we must do the same as when click is // cancelled (revert the checkbox to its original value). if (status == nsEventStatus_eConsumeNoDefault) aVisitor.mEventStatus = status; } } @@ -2004,25 +1990,25 @@ nsHTMLInputElement::PostHandleEvent(nsEv if(mForm) { // tell the form that we are about to exit a click handler // so the form knows not to defer subsequent submissions // the pending ones that were created during the handler // will be flushed or forgoten. mForm->OnSubmitClickEnd(); } break; - } //switch + } } // Reset the flag for other content besides this text field aVisitor.mEvent->flags |= noContentDispatch ? NS_EVENT_FLAG_NO_CONTENT_DISPATCH : NS_EVENT_FLAG_NONE; // now check to see if the event was "cancelled" - if (GET_BOOLBIT(mBitField, BF_CHECKED_IS_TOGGLED) && outerActivateEvent) { + if (mCheckedIsToggled && outerActivateEvent) { if (aVisitor.mEventStatus == nsEventStatus_eConsumeNoDefault) { // if it was cancelled and a radio button, then set the old // selected btn to TRUE. if it is a checkbox then set it to its // original value nsCOMPtr<nsIDOMHTMLInputElement> selectedRadioButton = do_QueryInterface(aVisitor.mItemData); if (selectedRadioButton) { selectedRadioButton->SetChecked(true); @@ -2377,17 +2363,17 @@ nsHTMLInputElement::UnbindFromTree(bool } void nsHTMLInputElement::HandleTypeChange(PRUint8 aNewType) { ValueModeType aOldValueMode = GetValueMode(); nsAutoString aOldValue; - if (aOldValueMode == VALUE_MODE_VALUE && !GET_BOOLBIT(mBitField, BF_PARSER_CREATING)) { + if (aOldValueMode == VALUE_MODE_VALUE && !mParserCreating) { GetValue(aOldValue); } // Only single line text inputs have a text editor state. bool isNewTypeSingleLine = IsSingleLineTextControl(false, aNewType); bool isCurrentTypeSingleLine = IsSingleLineTextControl(false, mType); if (isNewTypeSingleLine && !isCurrentTypeSingleLine) { @@ -2395,17 +2381,17 @@ nsHTMLInputElement::HandleTypeChange(PRU mInputData.mState = new nsTextEditorState(this); NS_ADDREF(mInputData.mState); } else if (isCurrentTypeSingleLine && !isNewTypeSingleLine) { FreeData(); } mType = aNewType; - if (!GET_BOOLBIT(mBitField, BF_PARSER_CREATING)) { + if (!mParserCreating) { /** * The following code is trying to reproduce the algorithm described here: * http://www.whatwg.org/specs/web-apps/current-work/complete.html#input-type-change */ switch (GetValueMode()) { case VALUE_MODE_DEFAULT: case VALUE_MODE_DEFAULT_ON: // If the previous value mode was value, we need to set the value content @@ -2440,18 +2426,17 @@ nsHTMLInputElement::HandleTypeChange(PRU // Do not notify, it will be done after if needed. UpdateAllValidityStates(false); } void nsHTMLInputElement::SanitizeValue(nsAString& aValue) { - NS_ASSERTION(!GET_BOOLBIT(mBitField, BF_PARSER_CREATING), - "The element parsing should be finished!"); + NS_ASSERTION(!mParserCreating, "The element parsing should be finished!"); switch (mType) { case NS_FORM_INPUT_TEXT: case NS_FORM_INPUT_SEARCH: case NS_FORM_INPUT_TEL: case NS_FORM_INPUT_PASSWORD: { PRUnichar crlf[] = { PRUnichar('\r'), PRUnichar('\n'), 0 }; @@ -2868,17 +2853,17 @@ nsHTMLInputElement::SetSelectionDirectio } return rv; } NS_IMETHODIMP nsHTMLInputElement::GetPhonetic(nsAString& aPhonetic) { - aPhonetic.Truncate(0); + aPhonetic.Truncate(); nsIFormControlFrame* formControlFrame = GetFormControlFrame(true); if (formControlFrame) { nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame); if (textControlFrame) textControlFrame->GetPhonetic(aPhonetic); } @@ -2930,44 +2915,40 @@ nsHTMLInputElement::Reset() // We should be able to reset all dirty flags regardless of the type. SetCheckedChanged(false); SetValueChanged(false); switch (GetValueMode()) { case VALUE_MODE_VALUE: return SetDefaultValueAsValue(); case VALUE_MODE_DEFAULT_ON: - bool resetVal; - GetDefaultChecked(&resetVal); - return DoSetChecked(resetVal, true, false); + return DoSetChecked(DefaultChecked(), true, false); case VALUE_MODE_FILENAME: ClearFiles(false); return NS_OK; case VALUE_MODE_DEFAULT: default: return NS_OK; } } NS_IMETHODIMP nsHTMLInputElement::SubmitNamesValues(nsFormSubmission* aFormSubmission) { - nsresult rv = NS_OK; - // Disabled elements don't submit // For type=reset, and type=button, we just never submit, period. // For type=image and type=button, we only submit if we were the button // pressed // For type=radio and type=checkbox, we only submit if checked=true if (IsDisabled() || mType == NS_FORM_INPUT_RESET || mType == NS_FORM_INPUT_BUTTON || ((mType == NS_FORM_INPUT_SUBMIT || mType == NS_FORM_INPUT_IMAGE) && aFormSubmission->GetOriginatingElement() != this) || ((mType == NS_FORM_INPUT_RADIO || mType == NS_FORM_INPUT_CHECKBOX) && - !GetChecked())) { + !mChecked)) { return NS_OK; } // Get the name nsAutoString name; GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); // Submit .x, .y for input type=image @@ -3007,17 +2988,17 @@ nsHTMLInputElement::SubmitNamesValues(ns // If name not there, don't submit if (name.IsEmpty()) { return NS_OK; } // Get the value nsAutoString value; - rv = GetValue(value); + nsresult rv = GetValue(value); if (NS_FAILED(rv)) { return rv; } if (mType == NS_FORM_INPUT_SUBMIT && value.IsEmpty() && !HasAttr(kNameSpaceID_None, nsGkAtoms::value)) { // Get our default value, which is the same as our default label nsXPIDLString defaultValue; @@ -3029,192 +3010,166 @@ nsHTMLInputElement::SubmitNamesValues(ns // // Submit file if its input type=file and this encoding method accepts files // if (mType == NS_FORM_INPUT_FILE) { // Submit files const nsCOMArray<nsIDOMFile>& files = GetFiles(); - for (PRUint32 i = 0; i < (PRUint32)files.Count(); ++i) { + for (PRInt32 i = 0; i < files.Count(); ++i) { aFormSubmission->AddNameFilePair(name, files[i]); } if (files.Count() == 0) { // If no file was selected, pretend we had an empty file with an // empty filename. aFormSubmission->AddNameFilePair(name, nsnull); } return NS_OK; } if (mType == NS_FORM_INPUT_HIDDEN && name.EqualsLiteral("_charset_")) { nsCString charset; aFormSubmission->GetCharset(charset); - rv = aFormSubmission->AddNameValuePair(name, - NS_ConvertASCIItoUTF16(charset)); + return aFormSubmission->AddNameValuePair(name, + NS_ConvertASCIItoUTF16(charset)); } - else if (IsSingleLineTextControl(true) && - name.EqualsLiteral("isindex") && - aFormSubmission->SupportsIsindexSubmission()) { - rv = aFormSubmission->AddIsindex(value); + if (IsSingleLineTextControl(true) && + name.EqualsLiteral("isindex") && + aFormSubmission->SupportsIsindexSubmission()) { + return aFormSubmission->AddIsindex(value); } - else { - rv = aFormSubmission->AddNameValuePair(name, value); - } - - return rv; + return aFormSubmission->AddNameValuePair(name, value); } NS_IMETHODIMP nsHTMLInputElement::SaveState() { - nsresult rv = NS_OK; - - nsRefPtr<nsHTMLInputElementState> inputState = nsnull; - + nsRefPtr<nsHTMLInputElementState> inputState; switch (mType) { case NS_FORM_INPUT_CHECKBOX: case NS_FORM_INPUT_RADIO: { - if (GetCheckedChanged()) { + if (mCheckedChanged) { inputState = new nsHTMLInputElementState(); - if (!inputState) { - return NS_ERROR_OUT_OF_MEMORY; - } - - inputState->SetChecked(GetChecked()); + inputState->SetChecked(mChecked); } break; } // Never save passwords in session history case NS_FORM_INPUT_PASSWORD: break; case NS_FORM_INPUT_EMAIL: case NS_FORM_INPUT_SEARCH: case NS_FORM_INPUT_TEXT: case NS_FORM_INPUT_TEL: case NS_FORM_INPUT_URL: case NS_FORM_INPUT_HIDDEN: { - if (GetValueChanged()) { + if (mValueChanged) { inputState = new nsHTMLInputElementState(); - if (!inputState) { - return NS_ERROR_OUT_OF_MEMORY; - } - nsAutoString value; GetValue(value); - rv = nsLinebreakConverter::ConvertStringLineBreaks( + DebugOnly<nsresult> rv = + nsLinebreakConverter::ConvertStringLineBreaks( value, nsLinebreakConverter::eLinebreakPlatform, nsLinebreakConverter::eLinebreakContent); NS_ASSERTION(NS_SUCCEEDED(rv), "Converting linebreaks failed!"); inputState->SetValue(value); } break; } case NS_FORM_INPUT_FILE: { if (mFiles.Count()) { inputState = new nsHTMLInputElementState(); - if (!inputState) { - return NS_ERROR_OUT_OF_MEMORY; - } - inputState->SetFiles(mFiles); } break; } } + nsresult rv = NS_OK; nsPresState* state = nsnull; if (inputState) { rv = GetPrimaryPresState(this, &state); if (state) { state->SetStateProperty(inputState); } } - if (GET_BOOLBIT(mBitField, BF_DISABLED_CHANGED)) { + if (mDisabledChanged) { rv |= GetPrimaryPresState(this, &state); if (state) { // We do not want to save the real disabled state but the disabled // attribute. state->SetDisabled(HasAttr(kNameSpaceID_None, nsGkAtoms::disabled)); } } return rv; } void nsHTMLInputElement::DoneCreatingElement() { - SET_BOOLBIT(mBitField, BF_PARSER_CREATING, false); + mParserCreating = false; // // Restore state as needed. Note that disabled state applies to all control // types. // bool restoredCheckedState = - GET_BOOLBIT(mBitField, BF_INHIBIT_RESTORATION) ? - false : - RestoreFormControlState(this, this); + !mInhibitRestoration && RestoreFormControlState(this, this); // // If restore does not occur, we initialize .checked using the CHECKED // property. // - if (!restoredCheckedState && - GET_BOOLBIT(mBitField, BF_SHOULD_INIT_CHECKED)) { - bool resetVal; - GetDefaultChecked(&resetVal); - DoSetChecked(resetVal, false, true); + if (!restoredCheckedState && mShouldInitChecked) { + DoSetChecked(DefaultChecked(), false, true); DoSetCheckedChanged(false, false); } // Sanitize the value. if (GetValueMode() == VALUE_MODE_VALUE) { nsAutoString aValue; GetValue(aValue); SetValueInternal(aValue, false, false); } - SET_BOOLBIT(mBitField, BF_SHOULD_INIT_CHECKED, false); + mShouldInitChecked = false; } nsEventStates nsHTMLInputElement::IntrinsicState() const { // If you add states here, and they're type-dependent, you need to add them // to the type case in AfterSetAttr. nsEventStates state = nsGenericHTMLFormElement::IntrinsicState(); if (mType == NS_FORM_INPUT_CHECKBOX || mType == NS_FORM_INPUT_RADIO) { // Check current checked state (:checked) - if (GET_BOOLBIT(mBitField, BF_CHECKED)) { + if (mChecked) { state |= NS_EVENT_STATE_CHECKED; } // Check current indeterminate state (:indeterminate) - if (mType == NS_FORM_INPUT_CHECKBOX && GET_BOOLBIT(mBitField, BF_INDETERMINATE)) { + if (mType == NS_FORM_INPUT_CHECKBOX && mIndeterminate) { state |= NS_EVENT_STATE_INDETERMINATE; } // Check whether we are the default checked element (:default) - // The call is to an interface function, which makes it non-const, so we - // use a nasty hack :( - bool defaultState = false; - const_cast<nsHTMLInputElement*>(this)->GetDefaultChecked(&defaultState); - if (defaultState) { + if (DefaultChecked()) { state |= NS_EVENT_STATE_DEFAULT; } } else if (mType == NS_FORM_INPUT_IMAGE) { state |= nsImageLoadingContent::ImageState(); } if (DoesRequiredApply() && HasAttr(kNameSpaceID_None, nsGkAtoms::required)) { state |= NS_EVENT_STATE_REQUIRED; @@ -3225,35 +3180,34 @@ nsHTMLInputElement::IntrinsicState() con if (IsCandidateForConstraintValidation()) { if (IsValid()) { state |= NS_EVENT_STATE_VALID; } else { state |= NS_EVENT_STATE_INVALID; if ((!mForm || !mForm->HasAttr(kNameSpaceID_None, nsGkAtoms::novalidate)) && (GetValidityState(VALIDITY_STATE_CUSTOM_ERROR) || - (GET_BOOLBIT(mBitField, BF_CAN_SHOW_INVALID_UI) && - ShouldShowValidityUI()))) { + (mCanShowInvalidUI && ShouldShowValidityUI()))) { state |= NS_EVENT_STATE_MOZ_UI_INVALID; } } // :-moz-ui-valid applies if all of the following conditions are true: // 1. The element is not focused, or had either :-moz-ui-valid or // :-moz-ui-invalid applying before it was focused ; // 2. The element is either valid or isn't allowed to have // :-moz-ui-invalid applying ; // 3. The element has no form owner or its form owner doesn't have the // novalidate attribute set ; // 4. The element has already been modified or the user tried to submit the // form owner while invalid. if ((!mForm || !mForm->HasAttr(kNameSpaceID_None, nsGkAtoms::novalidate)) && - (GET_BOOLBIT(mBitField, BF_CAN_SHOW_VALID_UI) && ShouldShowValidityUI() && + (mCanShowValidUI && ShouldShowValidityUI() && (IsValid() || (!state.HasState(NS_EVENT_STATE_MOZ_UI_INVALID) && - !GET_BOOLBIT(mBitField, BF_CAN_SHOW_INVALID_UI))))) { + !mCanShowInvalidUI)))) { state |= NS_EVENT_STATE_MOZ_UI_VALID; } } if (PlaceholderApplies() && HasAttr(kNameSpaceID_None, nsGkAtoms::placeholder) && !nsContentUtils::IsFocusedContent((nsIContent*)(this)) && IsValueEmpty()) { state |= NS_EVENT_STATE_MOZ_PLACEHOLDER; @@ -3323,46 +3277,46 @@ nsHTMLInputElement::AllowDrop() /* * Radio group stuff */ void nsHTMLInputElement::AddedToRadioGroup() { // Make sure not to notify if we're still being created by the parser - bool notify = !GET_BOOLBIT(mBitField, BF_PARSER_CREATING); + bool notify = !mParserCreating; // // If the input element is not in a form and // not in a document, we just need to return. // if (!mForm && !(IsInDoc() && GetParent())) { return; } // // If the input element is checked, and we add it to the group, it will // deselect whatever is currently selected in that group // - if (GetChecked()) { + if (mChecked) { // // If it is checked, call "RadioSetChecked" to perform the selection/ // deselection ritual. This has the side effect of repainting the // radio button, but as adding a checked radio button into the group // should not be that common an occurrence, I think we can live with // that. // RadioSetChecked(notify); } // // For integrity purposes, we have to ensure that "checkedChanged" is // the same for this new element as for all the others in the group // - bool checkedChanged = GET_BOOLBIT(mBitField, BF_CHECKED_CHANGED); + bool checkedChanged = mCheckedChanged; nsCOMPtr<nsIRadioVisitor> visitor = new nsRadioGetCheckedChangedVisitor(&checkedChanged, this); VisitGroup(visitor, notify); SetCheckedChangedInternal(checkedChanged); // @@ -3389,17 +3343,17 @@ nsHTMLInputElement::WillRemoveFromRadioG return; } nsAutoString name; GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); // If this button was checked, we need to notify the group that there is no // longer a selected radio button - if (GetChecked()) { + if (mChecked) { container->SetCurrentRadioButton(name, nsnull); } // Remove this radio from its group in the container. // We need to call UpdateValueMissingValidityStateForRadio before to make sure // the group validity is updated (with this element being ignored). UpdateValueMissingValidityStateForRadio(true); container->RemoveFromRadioGroup(name, static_cast<nsIFormControl*>(this)); @@ -3450,17 +3404,17 @@ nsHTMLInputElement::IsHTMLFocusable(bool return false; } if (mType != NS_FORM_INPUT_RADIO) { *aIsFocusable = defaultFocusable; return false; } - if (GetChecked()) { + if (mChecked) { // Selected radio buttons are tabbable *aIsFocusable = defaultFocusable; return false; } // Current radio button is not selected. // But make it tabbable if nothing in group is selected. nsIRadioGroupContainer* container = GetRadioGroupContainer(); @@ -3625,17 +3579,17 @@ nsHTMLInputElement::SetCustomValidity(co return NS_OK; } bool nsHTMLInputElement::IsTooLong() { if (!MaxLengthApplies() || !HasAttr(kNameSpaceID_None, nsGkAtoms::maxlength) || - !GetValueChanged()) { + !mValueChanged) { return false; } PRInt32 maxLength = -1; GetMaxLength(&maxLength); // Maxlength of -1 means parsing error. if (maxLength == -1) { @@ -3662,17 +3616,17 @@ nsHTMLInputElement::IsValueMissing() con } return IsValueEmpty(); } switch (mType) { case NS_FORM_INPUT_CHECKBOX: - return !GetChecked(); + return !mChecked; case NS_FORM_INPUT_FILE: { const nsCOMArray<nsIDOMFile>& files = GetFiles(); return !files.Count(); } default: return false; } @@ -3745,25 +3699,23 @@ nsHTMLInputElement::UpdateTooLongValidit #if 0 SetValidityState(VALIDITY_STATE_TOO_LONG, IsTooLong()); #endif } void nsHTMLInputElement::UpdateValueMissingValidityStateForRadio(bool aIgnoreSelf) { - bool notify = !GET_BOOLBIT(mBitField, BF_PARSER_CREATING); + bool notify = !mParserCreating; nsCOMPtr<nsIDOMHTMLInputElement> selection = GetSelectedRadioButton(); // If there is no selection, that might mean the radio is not in a group. // In that case, we can look for the checked state of the radio. - bool selected = selection ? true - : aIgnoreSelf ? false : GetChecked(); - bool required = aIgnoreSelf ? false - : HasAttr(kNameSpaceID_None, nsGkAtoms::required); + bool selected = selection || (!aIgnoreSelf && mChecked); + bool required = !aIgnoreSelf && HasAttr(kNameSpaceID_None, nsGkAtoms::required); bool valueMissing = false; nsCOMPtr<nsIRadioGroupContainer> container = GetRadioGroupContainer(); if (!container) { SetValidityState(VALIDITY_STATE_VALUE_MISSING, required && !selected); return; } @@ -4067,26 +4019,26 @@ nsHTMLInputElement::GetRows() NS_IMETHODIMP_(void) nsHTMLInputElement::GetDefaultValueFromContent(nsAString& aValue) { nsTextEditorState *state = GetEditorState(); if (state) { GetDefaultValue(aValue); // This is called by the frame to show the value. // We have to sanitize it when needed. - if (!GET_BOOLBIT(mBitField, BF_PARSER_CREATING)) { + if (!mParserCreating) { SanitizeValue(aValue); } } } NS_IMETHODIMP_(bool) nsHTMLInputElement::ValueChanged() const { - return GetValueChanged(); + return mValueChanged; } NS_IMETHODIMP_(void) nsHTMLInputElement::GetTextEditorValue(nsAString& aValue, bool aIgnoreWrap) const { nsTextEditorState *state = GetEditorState(); if (state) { @@ -4115,19 +4067,19 @@ nsHTMLInputElement::InitializeKeyboardEv NS_IMETHODIMP_(void) nsHTMLInputElement::OnValueChanged(bool aNotify) { UpdateAllValidityStates(aNotify); // :-moz-placeholder pseudo-class may change when the value changes. // However, we don't want to waste cycles if the state doesn't apply. - if (PlaceholderApplies() - && HasAttr(kNameSpaceID_None, nsGkAtoms::placeholder) - && !nsContentUtils::IsFocusedContent((nsIContent*)(this))) { + if (PlaceholderApplies() && + HasAttr(kNameSpaceID_None, nsGkAtoms::placeholder) && + !nsContentUtils::IsFocusedContent(this)) { UpdateState(aNotify); } } NS_IMETHODIMP_(bool) nsHTMLInputElement::HasCachedSelection() { bool isCached = false; @@ -4192,20 +4144,19 @@ nsHTMLInputElement::GetFilterFromAccept( } void nsHTMLInputElement::UpdateValidityUIBits(bool aIsFocused) { if (aIsFocused) { // If the invalid UI is shown, we should show it while focusing (and // update). Otherwise, we should not. - SET_BOOLBIT(mBitField, BF_CAN_SHOW_INVALID_UI, - !IsValid() && ShouldShowValidityUI()); + mCanShowInvalidUI = !IsValid() && ShouldShowValidityUI(); // If neither invalid UI nor valid UI is shown, we shouldn't show the valid // UI while typing. - SET_BOOLBIT(mBitField, BF_CAN_SHOW_VALID_UI, ShouldShowValidityUI()); + mCanShowValidUI = ShouldShowValidityUI(); } else { - SET_BOOLBIT(mBitField, BF_CAN_SHOW_INVALID_UI, true); - SET_BOOLBIT(mBitField, BF_CAN_SHOW_VALID_UI, true); + mCanShowInvalidUI = true; + mCanShowValidUI = true; } }
--- a/content/html/content/src/nsHTMLInputElement.h +++ b/content/html/content/src/nsHTMLInputElement.h @@ -47,39 +47,16 @@ #include "nsIDOMNSEditableElement.h" #include "nsTextEditorState.h" #include "nsCOMPtr.h" #include "nsIConstraintValidation.h" #include "nsDOMFile.h" #include "nsHTMLFormElement.h" // for ShouldShowInvalidUI() #include "nsIFile.h" -// -// Accessors for mBitField -// -#define BF_DISABLED_CHANGED 0 -#define BF_VALUE_CHANGED 1 -#define BF_CHECKED_CHANGED 2 -#define BF_CHECKED 3 -#define BF_HANDLING_SELECT_EVENT 4 -#define BF_SHOULD_INIT_CHECKED 5 -#define BF_PARSER_CREATING 6 -#define BF_IN_INTERNAL_ACTIVATE 7 -#define BF_CHECKED_IS_TOGGLED 8 -#define BF_INDETERMINATE 9 -#define BF_INHIBIT_RESTORATION 10 -#define BF_CAN_SHOW_INVALID_UI 11 -#define BF_CAN_SHOW_VALID_UI 12 - -#define GET_BOOLBIT(bitfield, field) (((bitfield) & (0x01 << (field))) \ - ? true : false) -#define SET_BOOLBIT(bitfield, field, b) ((b) \ - ? ((bitfield) |= (0x01 << (field))) \ - : ((bitfield) &= ~(0x01 << (field)))) - class nsDOMFileList; class nsIRadioGroupContainer; class nsIRadioGroupVisitor; class nsIRadioVisitor; class UploadLastDir : public nsIObserver, public nsSupportsWeakReference { public: NS_DECL_ISUPPORTS @@ -223,17 +200,17 @@ public: void GetDisplayFileName(nsAString& aFileName) const; const nsCOMArray<nsIDOMFile>& GetFiles() const; void SetFiles(const nsCOMArray<nsIDOMFile>& aFiles, bool aSetValueChanged); void SetFiles(nsIDOMFileList* aFiles, bool aSetValueChanged); void SetCheckedChangedInternal(bool aCheckedChanged); bool GetCheckedChanged() const { - return GET_BOOLBIT(mBitField, BF_CHECKED_CHANGED); + return mCheckedChanged; } void AddedToRadioGroup(); void WillRemoveFromRadioGroup(); /** * Helper function returning the currently selected button in the radio group. * Returning null if the element is not a button or if there is no selectied * button in the group. @@ -315,16 +292,20 @@ public: * submission is tried. * * @param aIsFocused Whether the element is currently focused. * * @note The caller is responsible to call ContentStatesChanged. */ void UpdateValidityUIBits(bool aIsFocused); + bool DefaultChecked() const { + return HasAttr(kNameSpaceID_None, nsGkAtoms::checked); + } + protected: // Pull IsSingleLineTextControl into our scope, otherwise it'd be hidden // by the nsITextControlElement version. using nsGenericHTMLFormElement::IsSingleLineTextControl; /** * The ValueModeType specifies how the value IDL attribute should behave. * @@ -437,24 +418,16 @@ protected: void DoSetCheckedChanged(bool aCheckedChanged, bool aNotify); /** * Actually set checked and notify the frame of the change. * @param aValue the value of checked to set */ void SetCheckedInternal(bool aValue, bool aNotify); - /** - * Syntax sugar to make it easier to check for checked - */ - bool GetChecked() const - { - return GET_BOOLBIT(mBitField, BF_CHECKED); - } - nsresult RadioSetChecked(bool aNotify); void SetCheckedChanged(bool aCheckedChanged); /** * MaybeSubmitForm looks for a submit input or a single text control * and submits the form if either is present. */ nsresult MaybeSubmitForm(nsPresContext* aPresContext); @@ -531,24 +504,16 @@ protected: /** * Set the current default value to the value of the input element. * @note You should not call this method if GetValueMode() doesn't return * VALUE_MODE_VALUE. */ nsresult SetDefaultValueAsValue(); /** - * Returns whether the value has been changed since the element has been created. - * @return Whether the value has been changed since the element has been created. - */ - bool GetValueChanged() const { - return GET_BOOLBIT(mBitField, BF_VALUE_CHANGED); - } - - /** * Return if an element should have a specific validity UI * (with :-moz-ui-invalid and :-moz-ui-valid pseudo-classes). * * @return Whether the elemnet should have a validity UI. */ bool ShouldShowValidityUI() const { /** * Always show the validity UI if the form has already tried to be submitted @@ -562,43 +527,33 @@ protected: switch (GetValueMode()) { case VALUE_MODE_DEFAULT: return true; case VALUE_MODE_DEFAULT_ON: return GetCheckedChanged(); case VALUE_MODE_VALUE: case VALUE_MODE_FILENAME: - return GetValueChanged(); + return mValueChanged; default: NS_NOTREACHED("We should not be there: there are no other modes."); return false; } } /** * Returns the radio group container if the element has one, null otherwise. * The radio group container will be the form owner if there is one. * The current document otherwise. * @return the radio group container if the element has one, null otherwise. */ nsIRadioGroupContainer* GetRadioGroupContainer() const; nsCOMPtr<nsIControllers> mControllers; - /** - * The type of this input (<input type=...>) as an integer. - * @see nsIFormControl.h (specifically NS_FORM_INPUT_*) - */ - PRUint8 mType; - /** - * A bitfield containing our booleans - * @see GET_BOOLBIT / SET_BOOLBIT macros and BF_* field identifiers - */ - PRInt16 mBitField; /* * In mInputData, the mState field is used if IsSingleLineTextControl returns * true and mValue is used otherwise. We have to be careful when handling it * on a type change. * * Accessing the mState member should be done using the GetEditorState function, * which returns null if the state is not present. */ @@ -622,11 +577,30 @@ protected: * the frame. Whenever the frame wants to change the filename it has to call * SetFileNames to update this member. */ nsCOMArray<nsIDOMFile> mFiles; nsRefPtr<nsDOMFileList> mFileList; nsString mStaticDocFileList; + + /** + * The type of this input (<input type=...>) as an integer. + * @see nsIFormControl.h (specifically NS_FORM_INPUT_*) + */ + PRUint8 mType; + bool mDisabledChanged : 1; + bool mValueChanged : 1; + bool mCheckedChanged : 1; + bool mChecked : 1; + bool mHandlingSelectEvent : 1; + bool mShouldInitChecked : 1; + bool mParserCreating : 1; + bool mInInternalActivate : 1; + bool mCheckedIsToggled : 1; + bool mIndeterminate : 1; + bool mInhibitRestoration : 1; + bool mCanShowValidUI : 1; + bool mCanShowInvalidUI : 1; }; #endif
--- a/content/html/content/src/nsHTMLLabelElement.cpp +++ b/content/html/content/src/nsHTMLLabelElement.cpp @@ -99,21 +99,18 @@ NS_IMETHODIMP nsHTMLLabelElement::GetForm(nsIDOMHTMLFormElement** aForm) { return nsGenericHTMLFormElement::GetForm(aForm); } NS_IMETHODIMP nsHTMLLabelElement::GetControl(nsIDOMHTMLElement** aElement) { - *aElement = nsnull; - nsCOMPtr<nsIDOMHTMLElement> element = do_QueryInterface(GetLabeledElement()); - - element.swap(*aElement); + element.forget(aElement); return NS_OK; } NS_IMPL_STRING_ATTR(nsHTMLLabelElement, HtmlFor, _for) NS_IMETHODIMP nsHTMLLabelElement::Focus() @@ -165,17 +162,17 @@ EventTargetIn(nsEvent *aEvent, nsIConten } static void DestroyMouseDownPoint(void * /*aObject*/, nsIAtom * /*aPropertyName*/, void * aPropertyValue, void * /*aData*/) { - nsIntPoint *pt = (nsIntPoint *)aPropertyValue; + nsIntPoint* pt = static_cast<nsIntPoint*>(aPropertyValue); delete pt; } nsresult nsHTMLLabelElement::PostHandleEvent(nsEventChainPostVisitor& aVisitor) { if (mHandlingEvent || (!NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent) &&
--- a/content/html/content/src/nsHTMLLegendElement.cpp +++ b/content/html/content/src/nsHTMLLegendElement.cpp @@ -78,17 +78,17 @@ NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLA NS_IMPL_ELEMENT_CLONE(nsHTMLLegendElement) NS_IMETHODIMP nsHTMLLegendElement::GetForm(nsIDOMHTMLFormElement** aForm) { - Element *form = GetFormElement(); + Element* form = GetFormElement(); return form ? CallQueryInterface(form, aForm) : NS_OK; } NS_IMPL_STRING_ATTR(nsHTMLLegendElement, Align, align) // this contains center, because IE4 does @@ -101,17 +101,17 @@ static const nsAttrValue::EnumTable kAli { 0 } }; nsIContent* nsHTMLLegendElement::GetFieldSet() { nsIContent* parent = GetParent(); - if (parent && parent->IsHTML() && parent->Tag() == nsGkAtoms::fieldset) { + if (parent && parent->IsHTML(nsGkAtoms::fieldset)) { return parent; } return nsnull; } bool nsHTMLLegendElement::ParseAttribute(PRInt32 aNamespaceID,
--- a/content/html/content/src/nsHTMLLegendElement.h +++ b/content/html/content/src/nsHTMLLegendElement.h @@ -45,18 +45,19 @@ class nsHTMLLegendElement : public nsGen public nsIDOMHTMLLegendElement { public: nsHTMLLegendElement(already_AddRefed<nsINodeInfo> aNodeInfo); virtual ~nsHTMLLegendElement(); static nsHTMLLegendElement* FromContent(nsIContent *aContent) { - if (aContent->IsHTML() && aContent->Tag() == nsGkAtoms::legend) + if (aContent->IsHTML(nsGkAtoms::legend)) { return static_cast<nsHTMLLegendElement*>(aContent); + } return nsnull; } // nsISupports NS_DECL_ISUPPORTS_INHERITED // nsIDOMNode NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
--- a/content/html/content/src/nsHTMLLinkElement.cpp +++ b/content/html/content/src/nsHTMLLinkElement.cpp @@ -161,32 +161,32 @@ NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLA NS_IMPL_ELEMENT_CLONE(nsHTMLLinkElement) NS_IMETHODIMP nsHTMLLinkElement::GetDisabled(bool* aDisabled) { - nsCOMPtr<nsIDOMStyleSheet> ss(do_QueryInterface(GetStyleSheet())); + nsCOMPtr<nsIDOMStyleSheet> ss = do_QueryInterface(GetStyleSheet()); nsresult result = NS_OK; if (ss) { result = ss->GetDisabled(aDisabled); } else { *aDisabled = false; } return result; } NS_IMETHODIMP nsHTMLLinkElement::SetDisabled(bool aDisabled) { - nsCOMPtr<nsIDOMStyleSheet> ss(do_QueryInterface(GetStyleSheet())); + nsCOMPtr<nsIDOMStyleSheet> ss = do_QueryInterface(GetStyleSheet()); nsresult result = NS_OK; if (ss) { result = ss->SetDisabled(aDisabled); } return result; } @@ -276,21 +276,19 @@ nsHTMLLinkElement::CreateAndDispatchEven if (!nsContentUtils::HasNonEmptyAttr(this, kNameSpaceID_None, nsGkAtoms::rev) && FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::rel, strings, eIgnoreCase) != ATTR_VALUE_NO_MATCH) return; nsRefPtr<nsPLDOMEvent> event = new nsPLDOMEvent(this, aEventName, true, true); - if (event) { - // Always run async in order to avoid running script when the content - // sink isn't expecting it. - event->PostDOMEvent(); - } + // Always run async in order to avoid running script when the content + // sink isn't expecting it. + event->PostDOMEvent(); } nsresult nsHTMLLinkElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aValue, bool aNotify) { nsresult rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix,
--- a/content/html/content/src/nsHTMLMapElement.cpp +++ b/content/html/content/src/nsHTMLMapElement.cpp @@ -111,17 +111,17 @@ NS_IMPL_ELEMENT_CLONE(nsHTMLMapElement) NS_IMETHODIMP nsHTMLMapElement::GetAreas(nsIDOMHTMLCollection** aAreas) { NS_ENSURE_ARG_POINTER(aAreas); if (!mAreas) { // Not using NS_GetContentList because this should not be cached mAreas = new nsContentList(this, - mNodeInfo->NamespaceID(), + kNameSpaceID_XHTML, nsGkAtoms::area, nsGkAtoms::area, false); } NS_ADDREF(*aAreas = mAreas); return NS_OK; }
--- a/content/html/content/src/nsHTMLMediaElement.cpp +++ b/content/html/content/src/nsHTMLMediaElement.cpp @@ -293,19 +293,18 @@ NS_IMETHODIMP nsHTMLMediaElement::MediaL if (mLoadID != element->GetCurrentLoadID()) { // The channel has been cancelled before we had a chance to create // a decoder. Abort, don't dispatch an "error" event, as the new load // may not be in an error state. return NS_BINDING_ABORTED; } // Don't continue to load if the request failed or has been canceled. - nsresult rv; nsresult status; - rv = aRequest->GetStatus(&status); + nsresult rv = aRequest->GetStatus(&status); NS_ENSURE_SUCCESS(rv, rv); if (NS_FAILED(status)) { if (element) element->NotifyLoadError(); return status; } nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest); @@ -327,27 +326,27 @@ NS_IMETHODIMP nsHTMLMediaElement::MediaL // interested in keeping the channel alive ourselves. rv = NS_BINDING_ABORTED; } return rv; } NS_IMETHODIMP nsHTMLMediaElement::MediaLoadListener::OnStopRequest(nsIRequest* aRequest, nsISupports* aContext, - nsresult aStatus) + nsresult aStatus) { if (mNextListener) { return mNextListener->OnStopRequest(aRequest, aContext, aStatus); } return NS_OK; } NS_IMETHODIMP nsHTMLMediaElement::MediaLoadListener::OnDataAvailable(nsIRequest* aRequest, nsISupports* aContext, - nsIInputStream* aStream, PRUint32 aOffset, - PRUint32 aCount) + nsIInputStream* aStream, PRUint32 aOffset, + PRUint32 aCount) { if (!mNextListener) { NS_ERROR("Must have a chained listener; OnStartRequest should have canceled this request"); return NS_BINDING_ABORTED; } return mNextListener->OnDataAvailable(aRequest, aContext, aStream, aOffset, aCount); } @@ -630,21 +629,20 @@ void nsHTMLMediaElement::SelectResource( ChangeDelayLoadStatus(true); mNetworkState = nsIDOMHTMLMediaElement::NETWORK_LOADING; // Load event was delayed, and still is, so no need to call // AddRemoveSelfReference, since it must still be held DispatchAsyncEvent(NS_LITERAL_STRING("loadstart")); + // If we have a 'src' attribute, use that exclusively. nsAutoString src; - nsCOMPtr<nsIURI> uri; - - // If we have a 'src' attribute, use that exclusively. if (GetAttr(kNameSpaceID_None, nsGkAtoms::src, src)) { + nsCOMPtr<nsIURI> uri; nsresult rv = NewURIFromString(src, getter_AddRefs(uri)); if (NS_SUCCEEDED(rv)) { LOG(PR_LOG_DEBUG, ("%p Trying load from src=%s", this, NS_ConvertUTF16toUTF8(src).get())); NS_ASSERTION(!mIsLoadingFromSourceChildren, "Should think we're not loading from source children by default"); mLoadingSrc = uri; if (mPreloadAction == nsHTMLMediaElement::PRELOAD_NONE) { // preload:none media, suspend the load here before we make any @@ -723,46 +721,44 @@ bool nsHTMLMediaElement::MayHaveAudioAva void nsHTMLMediaElement::LoadFromSourceChildren() { NS_ASSERTION(mDelayingLoadEvent, "Should delay load event (if in document) during load"); NS_ASSERTION(mIsLoadingFromSourceChildren, "Must remember we're loading from source children"); while (true) { - nsresult rv; nsIContent* child = GetNextSource(); if (!child) { // Exhausted candidates, wait for more candidates to be appended to // the media element. mLoadWaitStatus = WAITING_FOR_SOURCE; mNetworkState = nsIDOMHTMLMediaElement::NETWORK_NO_SOURCE; ChangeDelayLoadStatus(false); return; } - nsCOMPtr<nsIURI> uri; - nsAutoString src,type; - // Must have src attribute. + nsAutoString src; if (!child->GetAttr(kNameSpaceID_None, nsGkAtoms::src, src)) { DispatchAsyncSourceError(child); continue; } // If we have a type attribute, it must be a supported type. - if (child->HasAttr(kNameSpaceID_None, nsGkAtoms::type) && - child->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type) && - GetCanPlay(type) == CANPLAY_NO) - { + nsAutoString type; + if (child->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type) && + GetCanPlay(type) == CANPLAY_NO) { DispatchAsyncSourceError(child); continue; } LOG(PR_LOG_DEBUG, ("%p Trying load from <source>=%s type=%s", this, NS_ConvertUTF16toUTF8(src).get(), NS_ConvertUTF16toUTF8(type).get())); + + nsCOMPtr<nsIURI> uri; NewURIFromString(src, getter_AddRefs(uri)); if (!uri) { DispatchAsyncSourceError(child); continue; } mLoadingSrc = uri; NS_ASSERTION(mNetworkState == nsIDOMHTMLMediaElement::NETWORK_LOADING, @@ -770,19 +766,19 @@ void nsHTMLMediaElement::LoadFromSourceC if (mPreloadAction == nsHTMLMediaElement::PRELOAD_NONE) { // preload:none media, suspend the load here before we make any // network requests. SuspendLoad(uri); return; } - rv = LoadResource(uri); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(LoadResource(uri))) { return; + } // If we fail to load, loop back and try loading the next resource. DispatchAsyncSourceError(child); } NS_NOTREACHED("Execution should not reach here!"); } void nsHTMLMediaElement::SuspendLoad(nsIURI* aURI) @@ -887,50 +883,49 @@ void nsHTMLMediaElement::UpdatePreloadAc if (mLoadIsSuspended) { // Our load was previouly suspended due to the media having preload // value "none". The preload value has changed to preload:metadata, so // resume the load. We'll pause the load again after we've read the // metadata. ResumeLoad(PRELOAD_METADATA); } } - - return; } nsresult nsHTMLMediaElement::LoadResource(nsIURI* aURI) { NS_ASSERTION(mDelayingLoadEvent, "Should delay load event (if in document) during load"); - nsresult rv; // If a previous call to mozSetup() was made, kill that media stream // in order to use this new src instead. if (mAudioStream) { mAudioStream->Shutdown(); mAudioStream = nsnull; } if (mChannel) { mChannel->Cancel(NS_BINDING_ABORTED); mChannel = nsnull; } PRInt16 shouldLoad = nsIContentPolicy::ACCEPT; - rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_MEDIA, - aURI, - NodePrincipal(), - static_cast<nsGenericElement*>(this), - EmptyCString(), // mime type - nsnull, // extra - &shouldLoad, - nsContentUtils::GetContentPolicy(), - nsContentUtils::GetSecurityManager()); - NS_ENSURE_SUCCESS(rv,rv); - if (NS_CP_REJECTED(shouldLoad)) return NS_ERROR_FAILURE; + nsresult rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_MEDIA, + aURI, + NodePrincipal(), + static_cast<nsGenericElement*>(this), + EmptyCString(), // mime type + nsnull, // extra + &shouldLoad, + nsContentUtils::GetContentPolicy(), + nsContentUtils::GetSecurityManager()); + NS_ENSURE_SUCCESS(rv, rv); + if (NS_CP_REJECTED(shouldLoad)) { + return NS_ERROR_FAILURE; + } nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup(); // check for a Content Security Policy to pass down to the channel // created to load the media content nsCOMPtr<nsIChannelPolicy> channelPolicy; nsCOMPtr<nsIContentSecurityPolicy> csp; rv = NodePrincipal()->GetCsp(getter_AddRefs(csp)); @@ -1117,22 +1112,21 @@ NS_IMETHODIMP nsHTMLMediaElement::GetDur { *aDuration = mDecoder ? mDecoder->GetDuration() : std::numeric_limits<double>::quiet_NaN(); return NS_OK; } /* readonly attribute nsIDOMHTMLTimeRanges seekable; */ NS_IMETHODIMP nsHTMLMediaElement::GetSeekable(nsIDOMTimeRanges** aSeekable) { - nsTimeRanges* ranges = new nsTimeRanges(); - NS_ADDREF(*aSeekable = ranges); - + nsRefPtr<nsTimeRanges> ranges = new nsTimeRanges(); if (mDecoder && mReadyState > nsIDOMHTMLMediaElement::HAVE_NOTHING) { mDecoder->GetSeekable(ranges); } + ranges.forget(aSeekable); return NS_OK; } /* readonly attribute boolean paused; */ NS_IMETHODIMP nsHTMLMediaElement::GetPaused(bool *aPaused) { *aPaused = mPaused; @@ -1170,17 +1164,17 @@ NS_IMETHODIMP nsHTMLMediaElement::GetVol { *aVolume = mVolume; return NS_OK; } NS_IMETHODIMP nsHTMLMediaElement::SetVolume(double aVolume) { - if (aVolume < 0.0f || aVolume > 1.0f) + if (aVolume < 0.0 || aVolume > 1.0) return NS_ERROR_DOM_INDEX_SIZE_ERR; if (aVolume == mVolume) return NS_OK; mVolume = aVolume; if (mDecoder && !mMuted) { @@ -1341,38 +1335,41 @@ void nsHTMLMediaElement::StopSuspendingA mSuspendedAfterFirstFrame = false; if (mDecoder) { mDecoder->Resume(true); } } void nsHTMLMediaElement::SetPlayedOrSeeked(bool aValue) { - if (aValue == mHasPlayedOrSeeked) + if (aValue == mHasPlayedOrSeeked) { return; + } mHasPlayedOrSeeked = aValue; // Force a reflow so that the poster frame hides or shows immediately. nsIFrame* frame = GetPrimaryFrame(); - if (!frame) return; + if (!frame) { + return; + } frame->PresContext()->PresShell()->FrameNeedsReflow(frame, nsIPresShell::eTreeChange, NS_FRAME_IS_DIRTY); } NS_IMETHODIMP nsHTMLMediaElement::Play() { StopSuspendingAfterFirstFrame(); SetPlayedOrSeeked(true); if (mNetworkState == nsIDOMHTMLMediaElement::NETWORK_EMPTY) { nsresult rv = Load(); NS_ENSURE_SUCCESS(rv, rv); - } else if (mLoadIsSuspended) { + } else if (mLoadIsSuspended) { ResumeLoad(PRELOAD_ENOUGH); } else if (mDecoder) { if (mDecoder->IsEnded()) { SetCurrentTime(0); } if (!mPausedForInactiveDocument) { nsresult rv = mDecoder->Play(); NS_ENSURE_SUCCESS(rv, rv); @@ -1420,41 +1417,41 @@ bool nsHTMLMediaElement::ParseAttribute( { "", nsHTMLMediaElement::PRELOAD_ATTR_EMPTY }, { "none", nsHTMLMediaElement::PRELOAD_ATTR_NONE }, { "metadata", nsHTMLMediaElement::PRELOAD_ATTR_METADATA }, { "auto", nsHTMLMediaElement::PRELOAD_ATTR_AUTO }, { 0 } }; if (aNamespaceID == kNameSpaceID_None) { - if (aAttribute == nsGkAtoms::loopstart - || aAttribute == nsGkAtoms::loopend - || aAttribute == nsGkAtoms::start - || aAttribute == nsGkAtoms::end) { + if (aAttribute == nsGkAtoms::loopstart || + aAttribute == nsGkAtoms::loopend || + aAttribute == nsGkAtoms::start || + aAttribute == nsGkAtoms::end) { return aResult.ParseDoubleValue(aValue); } - else if (ParseImageAttribute(aAttribute, aValue, aResult)) { + if (ParseImageAttribute(aAttribute, aValue, aResult)) { return true; } - else if (aAttribute == nsGkAtoms::preload) { + if (aAttribute == nsGkAtoms::preload) { return aResult.ParseEnumValue(aValue, kPreloadTable, false); } } return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue, aResult); } nsresult nsHTMLMediaElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aValue, bool aNotify) { nsresult rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, aValue, - aNotify); + aNotify); if (NS_FAILED(rv)) return rv; if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::src) { Load(); } if (aNotify && aNameSpaceID == kNameSpaceID_None) { if (aName == nsGkAtoms::autoplay) { StopSuspendingAfterFirstFrame(); @@ -1531,22 +1528,26 @@ static const char* gRawCodecs[] = { static bool IsRawEnabled() { return Preferences::GetBool("media.raw.enabled"); } static bool IsRawType(const nsACString& aType) { - if (!IsRawEnabled()) + if (!IsRawEnabled()) { return false; + } + for (PRUint32 i = 0; i < ArrayLength(gRawTypes); ++i) { - if (aType.EqualsASCII(gRawTypes[i])) + if (aType.EqualsASCII(gRawTypes[i])) { return true; + } } + return false; } #endif #ifdef MOZ_OGG // See http://www.rfc-editor.org/rfc/rfc5334.txt for the definitions // of Ogg media types and codec types const char nsHTMLMediaElement::gOggTypes[3][16] = { "video/ogg", @@ -1564,22 +1565,26 @@ bool nsHTMLMediaElement::IsOggEnabled() { return Preferences::GetBool("media.ogg.enabled"); } bool nsHTMLMediaElement::IsOggType(const nsACString& aType) { - if (!IsOggEnabled()) + if (!IsOggEnabled()) { return false; + } + for (PRUint32 i = 0; i < ArrayLength(gOggTypes); ++i) { - if (aType.EqualsASCII(gOggTypes[i])) + if (aType.EqualsASCII(gOggTypes[i])) { return true; + } } + return false; } #endif #ifdef MOZ_WAVE // See http://www.rfc-editor.org/rfc/rfc2361.txt for the definitions // of WAVE media types and codec types. However, the audio/vnd.wave // MIME type described there is not used. @@ -1599,22 +1604,26 @@ bool nsHTMLMediaElement::IsWaveEnabled() { return Preferences::GetBool("media.wave.enabled"); } bool nsHTMLMediaElement::IsWaveType(const nsACString& aType) { - if (!IsWaveEnabled()) + if (!IsWaveEnabled()) { return false; + } + for (PRUint32 i = 0; i < ArrayLength(gWaveTypes); ++i) { - if (aType.EqualsASCII(gWaveTypes[i])) + if (aType.EqualsASCII(gWaveTypes[i])) { return true; + } } + return false; } #endif #ifdef MOZ_WEBM const char nsHTMLMediaElement::gWebMTypes[2][17] = { "video/webm", "audio/webm" @@ -1631,22 +1640,26 @@ bool nsHTMLMediaElement::IsWebMEnabled() { return Preferences::GetBool("media.webm.enabled"); } bool nsHTMLMediaElement::IsWebMType(const nsACString& aType) { - if (!IsWebMEnabled()) + if (!IsWebMEnabled()) { return false; + } + for (PRUint32 i = 0; i < ArrayLength(gWebMTypes); ++i) { - if (aType.EqualsASCII(gWebMTypes[i])) + if (aType.EqualsASCII(gWebMTypes[i])) { return true; + } } + return false; } #endif /* static */ nsHTMLMediaElement::CanPlayStatus nsHTMLMediaElement::CanHandleMediaType(const char* aMIMEType, char const *const ** aCodecList) @@ -1755,56 +1768,62 @@ nsHTMLMediaElement::GetCanPlay(const nsA } return result; } NS_IMETHODIMP nsHTMLMediaElement::CanPlayType(const nsAString& aType, nsAString& aResult) { switch (GetCanPlay(aType)) { - case CANPLAY_NO: aResult.AssignLiteral(""); break; - case CANPLAY_YES: aResult.AssignLiteral("probably"); break; + case CANPLAY_NO: + aResult.Truncate(); + break; + case CANPLAY_YES: + aResult.AssignLiteral("probably"); + break; default: - case CANPLAY_MAYBE: aResult.AssignLiteral("maybe"); break; + case CANPLAY_MAYBE: + aResult.AssignLiteral("maybe"); + break; } return NS_OK; } already_AddRefed<nsMediaDecoder> nsHTMLMediaElement::CreateDecoder(const nsACString& aType) { #ifdef MOZ_RAW if (IsRawType(aType)) { nsRefPtr<nsRawDecoder> decoder = new nsRawDecoder(); - if (decoder && decoder->Init(this)) { - return decoder.forget().get(); + if (decoder->Init(this)) { + return decoder.forget(); } } #endif #ifdef MOZ_OGG if (IsOggType(aType)) { nsRefPtr<nsOggDecoder> decoder = new nsOggDecoder(); - if (decoder && decoder->Init(this)) { - return decoder.forget().get(); + if (decoder->Init(this)) { + return decoder.forget(); } } #endif #ifdef MOZ_WAVE if (IsWaveType(aType)) { nsRefPtr<nsWaveDecoder> decoder = new nsWaveDecoder(); - if (decoder && decoder->Init(this)) { - return decoder.forget().get(); + if (decoder->Init(this)) { + return decoder.forget(); } } #endif #ifdef MOZ_WEBM if (IsWebMType(aType)) { nsRefPtr<nsWebMDecoder> decoder = new nsWebMDecoder(); - if (decoder && decoder->Init(this)) { - return decoder.forget().get(); + if (decoder->Init(this)) { + return decoder.forget(); } } #endif return nsnull; } nsresult nsHTMLMediaElement::InitializeDecoderAsClone(nsMediaDecoder* aOriginal) { @@ -1908,35 +1927,36 @@ nsresult nsHTMLMediaElement::NewURIFromS { NS_ENSURE_ARG_POINTER(aURI); *aURI = nsnull; nsCOMPtr<nsIDocument> doc = OwnerDoc(); nsCOMPtr<nsIURI> baseURI = GetBaseURI(); - nsresult rv = nsContentUtils::NewURIWithDocumentCharset(aURI, + nsCOMPtr<nsIURI> uri; + nsresult rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri), aURISpec, doc, baseURI); NS_ENSURE_SUCCESS(rv, rv); bool equal; if (aURISpec.IsEmpty() && doc->GetDocumentURI() && - NS_SUCCEEDED(doc->GetDocumentURI()->Equals(*aURI, &equal)) && + NS_SUCCEEDED(doc->GetDocumentURI()->Equals(uri, &equal)) && equal) { // It's not possible for a media resource to be embedded in the current // document we extracted aURISpec from, so there's no point returning // the current document URI just to let the caller attempt and fail to // decode it. - NS_RELEASE(*aURI); return NS_ERROR_DOM_INVALID_STATE_ERR; } + uri.forget(aURI); return NS_OK; } void nsHTMLMediaElement::ProcessMediaFragmentURI() { nsCAutoString ref; GetCurrentSpec(ref); nsMediaFragmentURIParser parser(ref); @@ -2480,21 +2500,21 @@ void nsHTMLMediaElement::NotifyAddedSour // a new source child to be added, resume the resource selction algorithm. if (mLoadWaitStatus == WAITING_FOR_SOURCE) { QueueLoadFromSourceTask(); } } nsIContent* nsHTMLMediaElement::GetNextSource() { - nsresult rv = NS_OK; nsCOMPtr<nsIDOMNode> thisDomNode = do_QueryObject(this); mSourceLoadCandidate = nsnull; + nsresult rv = NS_OK; if (!mSourcePointer) { // First time this has been run, create a selection to cover children. mSourcePointer = do_CreateInstance("@mozilla.org/content/range;1"); rv = mSourcePointer->SelectNodeContents(thisDomNode); if (NS_FAILED(rv)) return nsnull; rv = mSourcePointer->Collapse(true); @@ -2513,33 +2533,33 @@ nsIContent* nsHTMLMediaElement::GetNextS PRInt32 startOffset = 0; rv = mSourcePointer->GetStartOffset(&startOffset); NS_ENSURE_SUCCESS(rv, nsnull); if (PRUint32(startOffset) == GetChildCount()) return nsnull; // No more children. // Advance the range to the next child. - rv = mSourcePointer->SetStart(thisDomNode, startOffset+1); + rv = mSourcePointer->SetStart(thisDomNode, startOffset + 1); NS_ENSURE_SUCCESS(rv, nsnull); nsIContent* child = GetChildAt(startOffset); // If child is a <source> element, it is the next candidate. - if (child && child->IsHTML(nsGkAtoms::source)) - { + if (child && child->IsHTML(nsGkAtoms::source)) { mSourceLoadCandidate = child; return child; } } NS_NOTREACHED("Execution should not reach here!"); return nsnull; } -void nsHTMLMediaElement::ChangeDelayLoadStatus(bool aDelay) { +void nsHTMLMediaElement::ChangeDelayLoadStatus(bool aDelay) +{ if (mDelayingLoadEvent == aDelay) return; mDelayingLoadEvent = aDelay; if (aDelay) { mLoadBlockedDoc = OwnerDoc(); mLoadBlockedDoc->BlockOnload(); @@ -2594,38 +2614,38 @@ nsHTMLMediaElement::CopyInnerTo(nsGeneri dest->mMediaSize = nsIntSize(res.mSize.width, res.mSize.height); } } return rv; } nsresult nsHTMLMediaElement::GetBuffered(nsIDOMTimeRanges** aBuffered) { - nsTimeRanges* ranges = new nsTimeRanges(); - NS_ADDREF(*aBuffered = ranges); + nsRefPtr<nsTimeRanges> ranges = new nsTimeRanges(); if (mReadyState >= nsIDOMHTMLMediaElement::HAVE_CURRENT_DATA && mDecoder) { // If GetBuffered fails we ignore the error result and just return the // time ranges we found up till the error. mDecoder->GetBuffered(ranges); } + ranges.forget(aBuffered); return NS_OK; } void nsHTMLMediaElement::SetRequestHeaders(nsIHttpChannel* aChannel) { // Send Accept header for video and audio types only (Bug 489071) SetAcceptHeader(aChannel); // Apache doesn't send Content-Length when gzip transfer encoding is used, // which prevents us from estimating the video length (if explicit Content-Duration // and a length spec in the container are not present either) and from seeking. // So, disable the standard "Accept-Encoding: gzip,deflate" that we usually send. // See bug 614760. aChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Encoding"), - NS_LITERAL_CSTRING(""), false); + EmptyCString(), false); // Set the Referer header aChannel->SetReferrer(OwnerDoc()->GetDocumentURI()); } void nsHTMLMediaElement::FireTimeUpdate(bool aPeriodic) { NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
--- a/content/html/content/src/nsHTMLMetaElement.cpp +++ b/content/html/content/src/nsHTMLMetaElement.cpp @@ -145,12 +145,10 @@ void nsHTMLMetaElement::CreateAndDispatchEvent(nsIDocument* aDoc, const nsAString& aEventName) { if (!aDoc) return; nsRefPtr<nsPLDOMEvent> event = new nsPLDOMEvent(this, aEventName, true, true); - if (event) { - event->PostDOMEvent(); - } + event->PostDOMEvent(); }
--- a/content/html/content/src/nsHTMLObjectElement.cpp +++ b/content/html/content/src/nsHTMLObjectElement.cpp @@ -124,17 +124,17 @@ public: return NS_FORM_OBJECT; } NS_IMETHOD Reset(); NS_IMETHOD SubmitNamesValues(nsFormSubmission *aFormSubmission); virtual bool IsDisabled() const { return false; } - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual bool IsDoneAddingChildren(); virtual bool ParseAttribute(PRInt32 aNamespaceID, nsIAtom *aAttribute, const nsAString &aValue, nsAttrValue &aResult); virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const; NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom *aAttribute) const; @@ -195,27 +195,26 @@ nsHTMLObjectElement::~nsHTMLObjectElemen } bool nsHTMLObjectElement::IsDoneAddingChildren() { return mIsDoneAddingChildren; } -nsresult +void nsHTMLObjectElement::DoneAddingChildren(bool aHaveNotified) { mIsDoneAddingChildren = true; // If we're already in a document, we need to trigger the load // Otherwise, BindToTree takes care of that. if (IsInDoc()) { StartObjectLoad(aHaveNotified); } - return NS_OK; } NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLObjectElement) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLObjectElement, nsGenericHTMLFormElement) nsObjectLoadingContent::Traverse(tmp, cb); NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
--- a/content/html/content/src/nsHTMLOutputElement.cpp +++ b/content/html/content/src/nsHTMLOutputElement.cpp @@ -168,19 +168,17 @@ nsHTMLOutputElement::SetCustomValidity(c return NS_OK; } NS_IMETHODIMP nsHTMLOutputElement::Reset() { mValueModeFlag = eModeDefault; - nsresult rv = nsContentUtils::SetNodeTextContent(this, mDefaultValue, - true); - return rv; + return nsContentUtils::SetNodeTextContent(this, mDefaultValue, true); } NS_IMETHODIMP nsHTMLOutputElement::SubmitNamesValues(nsFormSubmission* aFormSubmission) { // The output element is not submittable. return NS_OK; }
--- a/content/html/content/src/nsHTMLScriptElement.cpp +++ b/content/html/content/src/nsHTMLScriptElement.cpp @@ -109,32 +109,26 @@ public: virtual void GetScriptCharset(nsAString& charset); virtual void FreezeUriAsyncDefer(); // nsIContent virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent, nsIContent* aBindingParent, bool aCompileEventHandlers); - virtual nsresult DoneAddingChildren(bool aHaveNotified); - virtual bool IsDoneAddingChildren(); - virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; // nsGenericElement virtual nsresult AfterSetAttr(PRInt32 aNamespaceID, nsIAtom* aName, const nsAString* aValue, bool aNotify); virtual nsXPCClassInfo* GetClassInfo(); protected: - bool IsOnloadEventForWindow(); - // nsScriptElement virtual bool HasScriptContent(); - virtual nsresult MaybeProcessScript(); }; NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Script) nsHTMLScriptElement::nsHTMLScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo, FromParser aFromParser) @@ -264,35 +258,16 @@ nsHTMLScriptElement::GetInnerHTML(nsAStr } nsresult nsHTMLScriptElement::SetInnerHTML(const nsAString& aInnerHTML) { return nsContentUtils::SetNodeTextContent(this, aInnerHTML, true); } -nsresult -nsHTMLScriptElement::DoneAddingChildren(bool aHaveNotified) -{ - mDoneAddingChildren = true; - nsresult rv = MaybeProcessScript(); - if (!mAlreadyStarted) { - // Need to lose parser-insertedness here to allow another script to cause - // execution later. - LoseParserInsertedness(); - } - return rv; -} - -bool -nsHTMLScriptElement::IsDoneAddingChildren() -{ - return mDoneAddingChildren; -} - // variation of this code in nsSVGScriptElement - check if changes // need to be transfered when modifying void nsHTMLScriptElement::GetScriptType(nsAString& type) { GetType(type); } @@ -337,19 +312,8 @@ nsHTMLScriptElement::FreezeUriAsyncDefer } bool nsHTMLScriptElement::HasScriptContent() { return (mFrozen ? mExternal : HasAttr(kNameSpaceID_None, nsGkAtoms::src)) || nsContentUtils::HasNonEmptyTextContent(this); } - -nsresult -nsHTMLScriptElement::MaybeProcessScript() -{ - nsresult rv = nsScriptElement::MaybeProcessScript(); - if (rv == NS_CONTENT_SCRIPT_IS_EVENTHANDLER) - // Don't return NS_CONTENT_SCRIPT_IS_EVENTHANDLER since callers can't deal - rv = NS_OK; - - return rv; -}
--- a/content/html/content/src/nsHTMLSelectElement.cpp +++ b/content/html/content/src/nsHTMLSelectElement.cpp @@ -268,17 +268,17 @@ nsHTMLSelectElement::InsertOptionsIntoLi // get into the right state once it's created. nsISelectControlFrame* selectFrame = nsnull; nsWeakFrame weakSelectFrame; bool didGetFrame = false; // Actually select the options if the added options warrant it nsCOMPtr<nsIDOMNode> optionNode; nsCOMPtr<nsIDOMHTMLOptionElement> option; - for (PRInt32 i=aListIndex;i<insertIndex;i++) { + for (PRInt32 i = aListIndex; i < insertIndex; i++) { // Notify the frame that the option is added if (!didGetFrame || (selectFrame && !weakSelectFrame.IsAlive())) { selectFrame = GetSelectFrame(); weakSelectFrame = do_QueryFrame(selectFrame); didGetFrame = true; } if (selectFrame) { @@ -321,17 +321,17 @@ nsHTMLSelectElement::RemoveOptionsFromLi aDepth); NS_ENSURE_SUCCESS(rv, rv); if (numRemoved) { // Tell the widget we removed the options nsISelectControlFrame* selectFrame = GetSelectFrame(); if (selectFrame) { nsAutoScriptBlocker scriptBlocker; - for (int i = aListIndex; i < aListIndex + numRemoved; ++i) { + for (PRInt32 i = aListIndex; i < aListIndex + numRemoved; ++i) { selectFrame->RemoveOption(i); } } // Fix the selected index if (aListIndex <= mSelectedIndex) { if (mSelectedIndex < (aListIndex+numRemoved)) { // aListIndex <= mSelectedIndex < aListIndex+numRemoved @@ -389,17 +389,17 @@ nsHTMLSelectElement::InsertOptionsIntoLi // Recurse down into optgroups if (aOptions->IsHTML(nsGkAtoms::optgroup)) { mOptGroupCount++; for (nsIContent* child = aOptions->GetFirstChild(); child; child = child->GetNextSibling()) { nsresult rv = InsertOptionsIntoListRecurse(child, - aInsertIndex, aDepth+1); + aInsertIndex, aDepth + 1); NS_ENSURE_SUCCESS(rv, rv); } } return NS_OK; } // If the document is such that recursing over these options gets us deeper than @@ -433,17 +433,16 @@ nsHTMLSelectElement::RemoveOptionsFromLi // Recurse down deeper for options if (mOptGroupCount && aOptions->IsHTML(nsGkAtoms::optgroup)) { mOptGroupCount--; for (nsIContent* child = aOptions->GetFirstChild(); child; child = child->GetNextSibling()) { - nsresult rv = RemoveOptionsFromListRecurse(child, aRemoveIndex, aNumRemoved, aDepth + 1); NS_ENSURE_SUCCESS(rv, rv); } } @@ -760,29 +759,25 @@ nsHTMLSelectElement::GetLength(PRUint32* return mOptions->GetLength(aLength); } #define MAX_DYNAMIC_SELECT_LENGTH 10000 NS_IMETHODIMP nsHTMLSelectElement::SetLength(PRUint32 aLength) { - nsresult rv=NS_OK; - PRUint32 curlen; - PRUint32 i; - - rv = GetLength(&curlen); + nsresult rv = GetLength(&curlen); if (NS_FAILED(rv)) { curlen = 0; } if (curlen > aLength) { // Remove extra options - for (i = curlen; i > aLength && NS_SUCCEEDED(rv); --i) { - rv = Remove(i-1); + for (PRUint32 i = curlen; i > aLength && NS_SUCCEEDED(rv); --i) { + rv = Remove(i - 1); } } else if (aLength > curlen) { if (aLength > MAX_DYNAMIC_SELECT_LENGTH) { return NS_ERROR_DOM_NOT_SUPPORTED_ERR; } // This violates the W3C DOM but we do this for backwards compatibility nsCOMPtr<nsINodeInfo> nodeInfo; @@ -799,17 +794,17 @@ nsHTMLSelectElement::SetLength(PRUint32 rv = NS_NewTextNode(getter_AddRefs(text), mNodeInfo->NodeInfoManager()); NS_ENSURE_SUCCESS(rv, rv); rv = element->AppendChildTo(text, false); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMNode> node(do_QueryInterface(element)); - for (i = curlen; i < aLength; i++) { + for (PRUint32 i = curlen; i < aLength; i++) { nsCOMPtr<nsIDOMNode> tmpNode; rv = AppendChild(node, getter_AddRefs(tmpNode)); NS_ENSURE_SUCCESS(rv, rv); if (i + 1 < aLength) { nsCOMPtr<nsIDOMNode> newNode; @@ -887,17 +882,17 @@ nsHTMLSelectElement::OnOptionSelected(ns bool aChangeOptionState, bool aNotify) { // Set the selected index if (aSelected && (aIndex < mSelectedIndex || mSelectedIndex < 0)) { mSelectedIndex = aIndex; SetSelectionChanged(true, aNotify); } else if (!aSelected && aIndex == mSelectedIndex) { - FindSelectedIndex(aIndex+1, aNotify); + FindSelectedIndex(aIndex + 1, aNotify); } if (aChangeOptionState) { // Tell the option to get its bad self selected nsCOMPtr<nsIDOMNode> option; Item(aIndex, getter_AddRefs(option)); if (option) { nsRefPtr<nsHTMLOptionElement> optionElement = @@ -917,17 +912,17 @@ nsHTMLSelectElement::OnOptionSelected(ns void nsHTMLSelectElement::FindSelectedIndex(PRInt32 aStartIndex, bool aNotify) { mSelectedIndex = -1; SetSelectionChanged(true, aNotify); PRUint32 len; GetLength(&len); - for (PRInt32 i=aStartIndex; i<(PRInt32)len; i++) { + for (PRInt32 i = aStartIndex; i < PRInt32(len); i++) { if (IsOptionSelectedByIndex(i)) { mSelectedIndex = i; SetSelectionChanged(true, aNotify); break; } } } @@ -1065,17 +1060,17 @@ nsHTMLSelectElement::SetOptionsSelectedB // Next remove all other options if single select or all is clear // If index is -1, everything will be deselected (bug 28143) if (((!isMultiple && optionsSelected) || (aClearAll && !allDisabled) || aStartIndex == -1) && previousSelectedIndex != -1) { for (PRInt32 optIndex = previousSelectedIndex; - optIndex < (PRInt32)numItems; + optIndex < PRInt32(numItems); optIndex++) { if (optIndex < aStartIndex || optIndex > aEndIndex) { nsIDOMHTMLOptionElement *option = mOptions->ItemAsOption(optIndex); if (option) { // If the index is already selected, ignore it. bool isSelected = false; option->GetSelected(&isSelected); if (isSelected) { @@ -1227,52 +1222,45 @@ nsHTMLSelectElement::GetValue(nsAString& rv = Item(selectedIndex, getter_AddRefs(node)); nsCOMPtr<nsIDOMHTMLOptionElement> option = do_QueryInterface(node); if (NS_SUCCEEDED(rv) && option) { return option->GetValue(aValue); } } - aValue.Truncate(0); + aValue.Truncate(); return rv; } NS_IMETHODIMP nsHTMLSelectElement::SetValue(const nsAString& aValue) { - nsresult rv = NS_OK; - PRUint32 length; - rv = GetLength(&length); - if (NS_SUCCEEDED(rv)) { - PRUint32 i; - for (i = 0; i < length; i++) { - nsCOMPtr<nsIDOMNode> node; - - rv = Item(i, getter_AddRefs(node)); + nsresult rv = GetLength(&length); + NS_ENSURE_SUCCESS(rv, rv); - if (NS_SUCCEEDED(rv) && node) { - nsCOMPtr<nsIDOMHTMLOptionElement> option = do_QueryInterface(node); - - if (option) { - nsAutoString optionVal; - - option->GetValue(optionVal); + for (PRUint32 i = 0; i < length; i++) { + nsCOMPtr<nsIDOMNode> node; + rv = Item(i, getter_AddRefs(node)); + if (NS_FAILED(rv) || !node) { + continue; + } - if (optionVal.Equals(aValue)) { - SetSelectedIndexInternal((PRInt32)i, true); - - break; - } - } - } + nsCOMPtr<nsIDOMHTMLOptionElement> option = do_QueryInterface(node); + if (!option) { + continue; + } + nsAutoString optionVal; + option->GetValue(optionVal); + if (optionVal.Equals(aValue)) { + SetSelectedIndexInternal(PRInt32(i), true); + break; } } - return rv; } NS_IMPL_BOOL_ATTR(nsHTMLSelectElement, Autofocus, autofocus) NS_IMPL_BOOL_ATTR(nsHTMLSelectElement, Disabled, disabled) NS_IMPL_BOOL_ATTR(nsHTMLSelectElement, Multiple, multiple) NS_IMPL_STRING_ATTR(nsHTMLSelectElement, Name, name) @@ -1322,17 +1310,17 @@ nsHTMLSelectElement::SelectSomething(boo { // If we're not done building the select, don't play with this yet. if (!mIsDoneAddingChildren) { return false; } PRUint32 count; GetLength(&count); - for (PRUint32 i=0; i<count; i++) { + for (PRUint32 i = 0; i < count; i++) { bool disabled; nsresult rv = IsOptionDisabled(i, &disabled); if (NS_FAILED(rv) || !disabled) { rv = SetSelectedIndexInternal(i, aNotify); NS_ENSURE_SUCCESS(rv, false); UpdateValueMissingValidityState(); @@ -1438,17 +1426,17 @@ nsHTMLSelectElement::UnsetAttr(PRInt32 a // We might have become a combobox; make sure _something_ gets // selected in that case CheckSelectSomething(aNotify); } return rv; } -nsresult +void nsHTMLSelectElement::DoneAddingChildren(bool aHaveNotified) { mIsDoneAddingChildren = true; nsISelectControlFrame* selectFrame = GetSelectFrame(); // If we foolishly tried to restore before we were done adding // content, restore the rest of the options proper-like @@ -1475,18 +1463,16 @@ nsHTMLSelectElement::DoneAddingChildren( // validity state to take this into account. UpdateValueMissingValidityState(); // And now make sure we update our content state too UpdateState(aHaveNotified); } mDefaultSelectionSet = true; - - return NS_OK; } bool nsHTMLSelectElement::ParseAttribute(PRInt32 aNamespaceID, nsIAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult) { @@ -1622,19 +1608,16 @@ nsHTMLSelectElement::IntrinsicState() co } // nsIFormControl NS_IMETHODIMP nsHTMLSelectElement::SaveState() { nsRefPtr<nsSelectState> state = new nsSelectState(); - if (!state) { - return NS_ERROR_OUT_OF_MEMORY; - } PRUint32 len; GetLength(&len); for (PRUint32 optIndex = 0; optIndex < len; optIndex++) { nsIDOMHTMLOptionElement *option = mOptions->ItemAsOption(optIndex); if (option) { bool isSelected; @@ -1694,28 +1677,26 @@ nsHTMLSelectElement::RestoreStateTo(nsSe PRUint32 len; GetLength(&len); // First clear all SetOptionsSelectedByIndex(-1, -1, true, true, true, true, nsnull); // Next set the proper ones - for (PRInt32 i = 0; i < (PRInt32)len; i++) { + for (PRInt32 i = 0; i < PRInt32(len); i++) { nsIDOMHTMLOptionElement *option = mOptions->ItemAsOption(i); if (option) { nsAutoString value; nsresult rv = option->GetValue(value); if (NS_SUCCEEDED(rv) && aNewSelected->ContainsOption(i, value)) { SetOptionsSelectedByIndex(i, i, true, false, true, true, nsnull); } } } - - //CheckSelectSomething(); } NS_IMETHODIMP nsHTMLSelectElement::Reset() { PRUint32 numSelected = 0; // @@ -1767,18 +1748,16 @@ nsHTMLSelectElement::Reset() return NS_OK; } static NS_DEFINE_CID(kFormProcessorCID, NS_FORMPROCESSOR_CID); NS_IMETHODIMP nsHTMLSelectElement::SubmitNamesValues(nsFormSubmission* aFormSubmission) { - nsresult rv = NS_OK; - // Disabled elements don't submit if (IsDisabled()) { return NS_OK; } // // Get the name (if no name, no submit) // @@ -1793,23 +1772,23 @@ nsHTMLSelectElement::SubmitNamesValues(n // PRUint32 len; GetLength(&len); nsAutoString mozType; nsCOMPtr<nsIFormProcessor> keyGenProcessor; if (GetAttr(kNameSpaceID_None, nsGkAtoms::_moz_type, mozType) && mozType.EqualsLiteral("-mozilla-keygen")) { - keyGenProcessor = do_GetService(kFormProcessorCID, &rv); + keyGenProcessor = do_GetService(kFormProcessorCID); } for (PRUint32 optIndex = 0; optIndex < len; optIndex++) { // Don't send disabled options bool disabled; - rv = IsOptionDisabled(optIndex, &disabled); + nsresult rv = IsOptionDisabled(optIndex, &disabled); if (NS_FAILED(rv) || disabled) { continue; } nsIDOMHTMLOptionElement *option = mOptions->ItemAsOption(optIndex); NS_ENSURE_TRUE(option, NS_ERROR_UNEXPECTED); bool isSelected; @@ -1842,17 +1821,19 @@ nsHTMLSelectElement::SubmitNamesValues(n NS_IMETHODIMP nsHTMLSelectElement::GetHasOptGroups(bool* aHasGroups) { *aHasGroups = (mOptGroupCount > 0); return NS_OK; } -void nsHTMLSelectElement::DispatchContentReset() { +void +nsHTMLSelectElement::DispatchContentReset() +{ nsIFormControlFrame* formControlFrame = GetFormControlFrame(false); if (formControlFrame) { // Only dispatch content reset notification if this is a list control // frame or combo box control frame. if (IsCombobox()) { nsIComboboxControlFrame* comboFrame = do_QueryFrame(formControlFrame); if (comboFrame) { comboFrame->OnContentReset(); @@ -1893,30 +1874,28 @@ nsHTMLSelectElement::RebuildOptionsArray bool nsHTMLSelectElement::IsValueMissing() { if (!HasAttr(kNameSpaceID_None, nsGkAtoms::required)) { return false; } PRUint32 length; - nsIDOMHTMLOptionElement* option = nsnull; - bool disabled; - bool selected; - mOptions->GetLength(&length); - for (PRUint32 i=0; i<length; ++i) { - option = mOptions->ItemAsOption(i); + for (PRUint32 i = 0; i < length; ++i) { + nsIDOMHTMLOptionElement* option = mOptions->ItemAsOption(i); + bool selected; NS_ENSURE_SUCCESS(option->GetSelected(&selected), false); if (!selected) { continue; } + bool disabled; IsOptionDisabled(i, &disabled); if (disabled) { continue; } nsAutoString value; NS_ENSURE_SUCCESS(option->GetValue(value), false); if (!value.IsEmpty()) { @@ -1930,38 +1909,31 @@ nsHTMLSelectElement::IsValueMissing() void nsHTMLSelectElement::UpdateValueMissingValidityState() { SetValidityState(VALIDITY_STATE_VALUE_MISSING, IsValueMissing()); } nsresult nsHTMLSelectElement::GetValidationMessage(nsAString& aValidationMessage, - ValidityStateType aType) + ValidityStateType aType) { - nsresult rv = NS_OK; - - switch (aType) - { - case VALIDITY_STATE_VALUE_MISSING: - { - nsXPIDLString message; - - rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES, - "FormValidationSelectMissing", - message); - - aValidationMessage = message; - } - break; - default: - rv = nsIConstraintValidation::GetValidationMessage(aValidationMessage, aType); + switch (aType) { + case VALIDITY_STATE_VALUE_MISSING: { + nsXPIDLString message; + nsresult rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES, + "FormValidationSelectMissing", + message); + aValidationMessage = message; + return rv; + } + default: { + return nsIConstraintValidation::GetValidationMessage(aValidationMessage, aType); + } } - - return rv; } #ifdef DEBUG static void VerifyOptionsRecurse(nsIContent* aRoot, PRInt32& aIndex, nsHTMLOptionCollection* aArray) { @@ -2297,9 +2269,8 @@ nsHTMLSelectElement::SetSelectionChanged bool previousSelectionChangedValue = mSelectionHasChanged; mSelectionHasChanged = aValue; if (mSelectionHasChanged != previousSelectionChangedValue) { UpdateState(aNotify); } } -
--- a/content/html/content/src/nsHTMLSelectElement.h +++ b/content/html/content/src/nsHTMLSelectElement.h @@ -393,17 +393,17 @@ public: virtual void UnbindFromTree(bool aDeep, bool aNullParent); virtual nsresult BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, const nsAString* aValue, bool aNotify); virtual nsresult AfterSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, const nsAString* aValue, bool aNotify); virtual nsresult UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aAttribute, bool aNotify); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual bool IsDoneAddingChildren() { return mIsDoneAddingChildren; } virtual bool ParseAttribute(PRInt32 aNamespaceID, nsIAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult);
--- a/content/html/content/src/nsHTMLSharedElement.cpp +++ b/content/html/content/src/nsHTMLSharedElement.cpp @@ -377,18 +377,18 @@ SetBaseTargetUsingFirstBaseWithTarget(ns aDocument->SetBaseTarget(EmptyString()); } nsresult nsHTMLSharedElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aValue, bool aNotify) { - nsresult rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, - aValue, aNotify); + nsresult rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, + aValue, aNotify); NS_ENSURE_SUCCESS(rv, rv); // If the href attribute of a <base> tag is changing, we may need to update // the document's base URI, which will cause all the links on the page to be // re-resolved given the new base. If the target attribute is changing, we // similarly need to change the base target. if (mNodeInfo->Equals(nsGkAtoms::base) && aNameSpaceID == kNameSpaceID_None &&
--- a/content/html/content/src/nsHTMLSharedObjectElement.cpp +++ b/content/html/content/src/nsHTMLSharedObjectElement.cpp @@ -45,23 +45,16 @@ #include "nsIDocument.h" #include "nsIDOMDocument.h" #include "nsIDOMHTMLAppletElement.h" #include "nsIDOMHTMLEmbedElement.h" #include "nsThreadUtils.h" #include "nsIDOMGetSVGDocument.h" #include "nsIDOMSVGDocument.h" -// XXX this is to get around conflicts with windows.h defines -// introduced through jni.h -#ifdef XP_WIN -#undef GetClassName -#undef GetObject -#endif - using namespace mozilla; using namespace mozilla::dom; class nsHTMLSharedObjectElement : public nsGenericHTMLElement , public nsObjectLoadingContent , public nsIDOMHTMLAppletElement , public nsIDOMHTMLEmbedElement , public nsIDOMGetSVGDocument @@ -122,17 +115,17 @@ public: bool aNullParent = true); virtual nsresult SetAttr(PRInt32 aNameSpaceID, nsIAtom *aName, nsIAtom *aPrefix, const nsAString &aValue, bool aNotify); virtual bool IsHTMLFocusable(bool aWithMouse, bool *aIsFocusable, PRInt32 *aTabIndex); virtual PRUint32 GetDesiredIMEState(); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual bool IsDoneAddingChildren(); virtual bool ParseAttribute(PRInt32 aNamespaceID, nsIAtom *aAttribute, const nsAString &aValue, nsAttrValue &aResult); virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const; NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom *aAttribute) const; @@ -210,30 +203,28 @@ nsHTMLSharedObjectElement::~nsHTMLShared } bool nsHTMLSharedObjectElement::IsDoneAddingChildren() { return mIsDoneAddingChildren; } -nsresult +void nsHTMLSharedObjectElement::DoneAddingChildren(bool aHaveNotified) { if (!mIsDoneAddingChildren) { mIsDoneAddingChildren = true; // If we're already in a document, we need to trigger the load // Otherwise, BindToTree takes care of that. if (IsInDoc()) { StartObjectLoad(aHaveNotified); } } - - return NS_OK; } NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLSharedObjectElement) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLSharedObjectElement, nsGenericHTMLElement) nsObjectLoadingContent::Traverse(tmp, cb); NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
--- a/content/html/content/src/nsHTMLStyleElement.cpp +++ b/content/html/content/src/nsHTMLStyleElement.cpp @@ -165,46 +165,34 @@ NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLA NS_IMPL_ELEMENT_CLONE(nsHTMLStyleElement) NS_IMETHODIMP nsHTMLStyleElement::GetDisabled(bool* aDisabled) { - nsresult result = NS_OK; - - if (GetStyleSheet()) { - nsCOMPtr<nsIDOMStyleSheet> ss(do_QueryInterface(GetStyleSheet())); - - if (ss) { - result = ss->GetDisabled(aDisabled); - } - } - else { + nsCOMPtr<nsIDOMStyleSheet> ss = do_QueryInterface(GetStyleSheet()); + if (!ss) { *aDisabled = false; + return NS_OK; } - return result; + return ss->GetDisabled(aDisabled); } NS_IMETHODIMP nsHTMLStyleElement::SetDisabled(bool aDisabled) { - nsresult result = NS_OK; - - if (GetStyleSheet()) { - nsCOMPtr<nsIDOMStyleSheet> ss(do_QueryInterface(GetStyleSheet())); - - if (ss) { - result = ss->SetDisabled(aDisabled); - } + nsCOMPtr<nsIDOMStyleSheet> ss = do_QueryInterface(GetStyleSheet()); + if (!ss) { + return NS_OK; } - return result; + return ss->SetDisabled(aDisabled); } NS_IMPL_STRING_ATTR(nsHTMLStyleElement, Media, media) NS_IMPL_STRING_ATTR(nsHTMLStyleElement, Type, type) void nsHTMLStyleElement::CharacterDataChanged(nsIDocument* aDocument, nsIContent* aContent, @@ -362,11 +350,9 @@ nsHTMLStyleElement::GetStyleSheetInfo(ns nsParserUtils::SplitMimeType(aType, mimeType, notUsed); if (!mimeType.IsEmpty() && !mimeType.LowerCaseEqualsLiteral("text/css")) { return; } // If we get here we assume that we're loading a css file, so set the // type to 'text/css' aType.AssignLiteral("text/css"); - - return; }
--- a/content/html/content/src/nsHTMLTableCellElement.cpp +++ b/content/html/content/src/nsHTMLTableCellElement.cpp @@ -83,20 +83,19 @@ public: virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const; NS_IMETHOD WalkContentStyleRules(nsRuleWalker* aRuleWalker); NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const; virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; virtual nsXPCClassInfo* GetClassInfo(); protected: - // This does not return a nsresult since all we care about is if we - // found the row element that this cell is in or not. - void GetRow(nsIDOMHTMLTableRowElement** aRow); - nsIContent * GetTable(); + nsHTMLTableElement* GetTable() const; + + already_AddRefed<nsIDOMHTMLTableRowElement> GetRow() const; }; NS_IMPL_NS_NEW_HTML_ELEMENT(TableCell) nsHTMLTableCellElement::nsHTMLTableCellElement(already_AddRefed<nsINodeInfo> aNodeInfo) : nsGenericHTMLElement(aNodeInfo) @@ -122,106 +121,99 @@ NS_INTERFACE_TABLE_HEAD(nsHTMLTableCellE nsGenericHTMLElement) NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLTableCellElement) NS_IMPL_ELEMENT_CLONE(nsHTMLTableCellElement) // protected method -void -nsHTMLTableCellElement::GetRow(nsIDOMHTMLTableRowElement** aRow) +already_AddRefed<nsIDOMHTMLTableRowElement> +nsHTMLTableCellElement::GetRow() const { - *aRow = nsnull; - - nsCOMPtr<nsIDOMNode> rowNode; - GetParentNode(getter_AddRefs(rowNode)); - - if (rowNode) { - CallQueryInterface(rowNode, aRow); - } + nsCOMPtr<nsIDOMHTMLTableRowElement> row = do_QueryInterface(GetParent()); + return row.forget(); } // protected method -nsIContent* -nsHTMLTableCellElement::GetTable() +nsHTMLTableElement* +nsHTMLTableCellElement::GetTable() const { - nsIContent *result = nsnull; - nsIContent *parent = GetParent(); - if (parent) { // GetParent() should be a row - nsIContent* section = parent->GetParent(); - if (section) { - if (section->IsHTML() && - section->NodeInfo()->Equals(nsGkAtoms::table)) { - // XHTML, without a row group - result = section; - } else { - // we have a row group. - result = section->GetParent(); - } - } + if (!parent) { + return nsnull; + } + + // parent should be a row. + nsIContent* section = parent->GetParent(); + if (!section) { + return nsnull; } - return result; + + if (section->IsHTML(nsGkAtoms::table)) { + // XHTML, without a row group. + return static_cast<nsHTMLTableElement*>(section); + } + + // We have a row group. + nsIContent* result = section->GetParent(); + if (result && result->IsHTML(nsGkAtoms::table)) { + return static_cast<nsHTMLTableElement*>(result); + } + + return nsnull; } NS_IMETHODIMP nsHTMLTableCellElement::GetCellIndex(PRInt32* aCellIndex) { *aCellIndex = -1; - nsCOMPtr<nsIDOMHTMLTableRowElement> row; - - GetRow(getter_AddRefs(row)); - + nsCOMPtr<nsIDOMHTMLTableRowElement> row = GetRow(); if (!row) { return NS_OK; } nsCOMPtr<nsIDOMHTMLCollection> cells; row->GetCells(getter_AddRefs(cells)); if (!cells) { return NS_OK; } PRUint32 numCells; cells->GetLength(&numCells); - bool found = false; - PRUint32 i; - - for (i = 0; (i < numCells) && !found; i++) { + for (PRUint32 i = 0; i < numCells; i++) { nsCOMPtr<nsIDOMNode> node; cells->Item(i, getter_AddRefs(node)); if (node.get() == static_cast<nsIDOMNode *>(this)) { *aCellIndex = i; - found = true; + break; } } return NS_OK; } NS_IMETHODIMP nsHTMLTableCellElement::WalkContentStyleRules(nsRuleWalker* aRuleWalker) { nsresult rv = nsGenericHTMLElement::WalkContentStyleRules(aRuleWalker); NS_ENSURE_SUCCESS(rv, rv); - nsIContent* node = GetTable(); - if (node && node->IsHTML(nsGkAtoms::table)) { - nsHTMLTableElement* table = static_cast<nsHTMLTableElement*>(node); + if (nsHTMLTableElement* table = GetTable()) { nsMappedAttributes* tableInheritedAttributes = table->GetAttributesMappedForCell(); - if (tableInheritedAttributes) + if (tableInheritedAttributes) { aRuleWalker->Forward(tableInheritedAttributes); + } } return NS_OK; } NS_IMPL_STRING_ATTR(nsHTMLTableCellElement, Abbr, abbr) NS_IMPL_STRING_ATTR(nsHTMLTableCellElement, Axis, axis) NS_IMPL_STRING_ATTR(nsHTMLTableCellElement, BgColor, bgcolor) @@ -237,20 +229,17 @@ NS_IMPL_STRING_ATTR(nsHTMLTableCellEleme NS_IMPL_STRING_ATTR(nsHTMLTableCellElement, Width, width) NS_IMETHODIMP nsHTMLTableCellElement::GetAlign(nsAString& aValue) { if (!GetAttr(kNameSpaceID_None, nsGkAtoms::align, aValue)) { // There's no align attribute, ask the row for the alignment. - - nsCOMPtr<nsIDOMHTMLTableRowElement> row; - GetRow(getter_AddRefs(row)); - + nsCOMPtr<nsIDOMHTMLTableRowElement> row = GetRow(); if (row) { return row->GetAlign(aValue); } } return NS_OK; }
--- a/content/html/content/src/nsHTMLTableElement.cpp +++ b/content/html/content/src/nsHTMLTableElement.cpp @@ -98,17 +98,17 @@ protected: nsHTMLTableElement* mParent; nsRefPtr<nsContentList> mOrphanRows; }; TableRowsCollection::TableRowsCollection(nsHTMLTableElement *aParent) : mParent(aParent) , mOrphanRows(new nsContentList(mParent, - mParent->NodeInfo()->NamespaceID(), + kNameSpaceID_XHTML, nsGkAtoms::tr, nsGkAtoms::tr, false)) { // Mark ourselves as a proxy SetIsProxy(); } @@ -378,37 +378,33 @@ NS_IMPL_STRING_ATTR(nsHTMLTableElement, NS_IMPL_STRING_ATTR(nsHTMLTableElement, CellPadding, cellpadding) NS_IMPL_STRING_ATTR(nsHTMLTableElement, CellSpacing, cellspacing) NS_IMPL_STRING_ATTR(nsHTMLTableElement, Frame, frame) NS_IMPL_STRING_ATTR(nsHTMLTableElement, Rules, rules) NS_IMPL_STRING_ATTR(nsHTMLTableElement, Summary, summary) NS_IMPL_STRING_ATTR(nsHTMLTableElement, Width, width) +already_AddRefed<nsIDOMHTMLTableCaptionElement> +nsHTMLTableElement::GetCaption() +{ + for (nsIContent* cur = nsINode::GetFirstChild(); cur; cur = cur->GetNextSibling()) { + nsCOMPtr<nsIDOMHTMLTableCaptionElement> caption = do_QueryInterface(cur); + if (caption) { + return caption.forget(); + } + } + return nsnull; +} + NS_IMETHODIMP nsHTMLTableElement::GetCaption(nsIDOMHTMLTableCaptionElement** aValue) { - *aValue = nsnull; - nsCOMPtr<nsIDOMNode> child; - GetFirstChild(getter_AddRefs(child)); - - while (child) { - nsCOMPtr<nsIDOMHTMLTableCaptionElement> caption(do_QueryInterface(child)); - - if (caption) { - *aValue = caption; - NS_ADDREF(*aValue); - - break; - } - - nsIDOMNode *temp = child.get(); - temp->GetNextSibling(getter_AddRefs(child)); - } - + nsCOMPtr<nsIDOMHTMLTableCaptionElement> caption = GetCaption(); + caption.forget(aValue); return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::SetCaption(nsIDOMHTMLTableCaptionElement* aValue) { nsresult rv = DeleteCaption(); @@ -420,32 +416,24 @@ nsHTMLTableElement::SetCaption(nsIDOMHTM } return rv; } already_AddRefed<nsIDOMHTMLTableSectionElement> nsHTMLTableElement::GetSection(nsIAtom *aTag) { - nsCOMPtr<nsIDOMHTMLTableSectionElement> section; - for (nsIContent* child = nsINode::GetFirstChild(); child; child = child->GetNextSibling()) { - - section = do_QueryInterface(child); - + nsCOMPtr<nsIDOMHTMLTableSectionElement> section = do_QueryInterface(child); if (section && child->NodeInfo()->Equals(aTag)) { - nsIDOMHTMLTableSectionElement *result = section; - NS_ADDREF(result); - - return result; + return section.forget(); } } - return nsnull; } NS_IMETHODIMP nsHTMLTableElement::GetTHead(nsIDOMHTMLTableSectionElement** aValue) { *aValue = GetTHead().get(); @@ -531,64 +519,57 @@ nsHTMLTableElement::GetTBodies(nsIDOMHTM } nsContentList* nsHTMLTableElement::TBodies() { if (!mTBodies) { // Not using NS_GetContentList because this should not be cached mTBodies = new nsContentList(this, - mNodeInfo->NamespaceID(), + kNameSpaceID_XHTML, nsGkAtoms::tbody, nsGkAtoms::tbody, false); } return mTBodies; } NS_IMETHODIMP nsHTMLTableElement::CreateTHead(nsIDOMHTMLElement** aValue) { *aValue = nsnull; - nsresult rv = NS_OK; - nsCOMPtr<nsIDOMHTMLTableSectionElement> head; - GetTHead(getter_AddRefs(head)); - - if (head) { // return the existing thead - CallQueryInterface(head, aValue); - - NS_ASSERTION(*aValue, "head must be a DOMHTMLElement"); - } - else - { // create a new head rowgroup - nsCOMPtr<nsINodeInfo> nodeInfo; - - nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::thead, - getter_AddRefs(nodeInfo)); - - nsCOMPtr<nsIContent> newHead = NS_NewHTMLTableSectionElement(nodeInfo.forget()); - - if (newHead) { - nsCOMPtr<nsIDOMNode> child; - - rv = GetFirstChild(getter_AddRefs(child)); - - if (NS_FAILED(rv)) { - return rv; - } - - CallQueryInterface(newHead, aValue); - - nsCOMPtr<nsIDOMNode> resultChild; - rv = InsertBefore(*aValue, child, getter_AddRefs(resultChild)); - } + nsRefPtr<nsIDOMHTMLTableSectionElement> head = GetTHead(); + if (head) { + // return the existing thead + head.forget(aValue); + return NS_OK; } + nsCOMPtr<nsINodeInfo> nodeInfo; + nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::thead, + getter_AddRefs(nodeInfo)); + + nsCOMPtr<nsIContent> newHead = + NS_NewHTMLTableSectionElement(nodeInfo.forget()); + + if (!newHead) { + return NS_OK; + } + + nsCOMPtr<nsIDOMNode> child; + nsresult rv = GetFirstChild(getter_AddRefs(child)); + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr<nsIDOMHTMLElement> newHeadAsDOMElement = do_QueryInterface(newHead); + + nsCOMPtr<nsIDOMNode> resultChild; + InsertBefore(newHeadAsDOMElement, child, getter_AddRefs(resultChild)); + newHeadAsDOMElement.forget(aValue); return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::DeleteTHead() { nsCOMPtr<nsIDOMHTMLTableSectionElement> childToDelete; nsresult rv = GetTHead(getter_AddRefs(childToDelete)); @@ -601,40 +582,36 @@ nsHTMLTableElement::DeleteTHead() return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::CreateTFoot(nsIDOMHTMLElement** aValue) { *aValue = nsnull; - nsresult rv = NS_OK; - nsCOMPtr<nsIDOMHTMLTableSectionElement> foot; - GetTFoot(getter_AddRefs(foot)); - - if (foot) { // return the existing tfoot - CallQueryInterface(foot, aValue); - - NS_ASSERTION(*aValue, "foot must be a DOMHTMLElement"); + nsRefPtr<nsIDOMHTMLTableSectionElement> foot = GetTFoot(); + if (foot) { + // return the existing tfoot + foot.forget(aValue); + return NS_OK; } - else - { // create a new foot rowgroup - nsCOMPtr<nsINodeInfo> nodeInfo; - nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::tfoot, - getter_AddRefs(nodeInfo)); + // create a new foot rowgroup + nsCOMPtr<nsINodeInfo> nodeInfo; + nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::tfoot, + getter_AddRefs(nodeInfo)); + + nsCOMPtr<nsIContent> newFoot = NS_NewHTMLTableSectionElement(nodeInfo.forget()); - nsCOMPtr<nsIContent> newFoot = NS_NewHTMLTableSectionElement(nodeInfo.forget()); - - if (newFoot) { - rv = AppendChildTo(newFoot, true); - CallQueryInterface(newFoot, aValue); - } + if (!newFoot) { + return NS_OK; } - + AppendChildTo(newFoot, true); + nsCOMPtr<nsIDOMHTMLElement> newFootAsDOMElement = do_QueryInterface(newFoot); + newFootAsDOMElement.forget(aValue); return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::DeleteTFoot() { nsCOMPtr<nsIDOMHTMLTableSectionElement> childToDelete; nsresult rv = GetTFoot(getter_AddRefs(childToDelete)); @@ -647,40 +624,38 @@ nsHTMLTableElement::DeleteTFoot() return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::CreateCaption(nsIDOMHTMLElement** aValue) { *aValue = nsnull; - nsresult rv = NS_OK; - nsCOMPtr<nsIDOMHTMLTableCaptionElement> caption; - GetCaption(getter_AddRefs(caption)); - - if (caption) { // return the existing thead - CallQueryInterface(caption, aValue); - - NS_ASSERTION(*aValue, "caption must be a DOMHTMLElement"); - } - else - { // create a new head rowgroup - nsCOMPtr<nsINodeInfo> nodeInfo; - nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::caption, - getter_AddRefs(nodeInfo)); - - nsCOMPtr<nsIContent> newCaption = NS_NewHTMLTableCaptionElement(nodeInfo.forget()); - - if (newCaption) { - rv = AppendChildTo(newCaption, true); - CallQueryInterface(newCaption, aValue); - } + if (nsRefPtr<nsIDOMHTMLTableCaptionElement> caption = GetCaption()) { + // return the existing caption + caption.forget(aValue); + return NS_OK; } + // create a new head rowgroup + nsCOMPtr<nsINodeInfo> nodeInfo; + nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::caption, + getter_AddRefs(nodeInfo)); + + nsCOMPtr<nsIContent> newCaption = NS_NewHTMLTableCaptionElement(nodeInfo.forget()); + + if (!newCaption) { + return NS_OK; + } + + AppendChildTo(newCaption, true); + nsCOMPtr<nsIDOMHTMLElement> captionAsDOMElement = + do_QueryInterface(newCaption); + captionAsDOMElement.forget(aValue); return NS_OK; } NS_IMETHODIMP nsHTMLTableElement::DeleteCaption() { nsCOMPtr<nsIDOMHTMLTableCaptionElement> childToDelete; nsresult rv = GetCaption(getter_AddRefs(childToDelete)); @@ -705,31 +680,30 @@ nsHTMLTableElement::InsertRow(PRInt32 aI insert the new row as its first child */ *aValue = nsnull; if (aIndex < -1) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } - nsresult rv; - nsCOMPtr<nsIDOMHTMLCollection> rows; GetRows(getter_AddRefs(rows)); PRUint32 rowCount; rows->GetLength(&rowCount); if ((PRUint32)aIndex > rowCount && aIndex != -1) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } // use local variable refIndex so we can remember original aIndex PRUint32 refIndex = (PRUint32)aIndex; + nsresult rv; if (rowCount > 0) { if (refIndex == rowCount || aIndex == -1) { // we set refIndex to the last row so we can get the last row's // parent we then do an AppendChild below if (rowCount<aIndex) refIndex = rowCount - 1; } @@ -761,29 +735,27 @@ nsHTMLTableElement::InsertRow(PRInt32 aI rv = parent->InsertBefore(newRowNode, refRow, getter_AddRefs(retChild)); } if (retChild) { CallQueryInterface(retChild, aValue); } } - } - else - { // the row count was 0, so + } else { + // the row count was 0, so // find the first row group and insert there as first child nsCOMPtr<nsIDOMNode> rowGroup; - PRInt32 namespaceID = mNodeInfo->NamespaceID(); for (nsIContent* child = nsINode::GetFirstChild(); child; child = child->GetNextSibling()) { nsINodeInfo *childInfo = child->NodeInfo(); nsIAtom *localName = childInfo->NameAtom(); - if (childInfo->NamespaceID() == namespaceID && + if (childInfo->NamespaceID() == kNameSpaceID_XHTML && (localName == nsGkAtoms::thead || localName == nsGkAtoms::tbody || localName == nsGkAtoms::tfoot)) { rowGroup = do_QueryInterface(child); NS_ASSERTION(rowGroup, "HTML node did not QI to nsIDOMNode"); break; } }
--- a/content/html/content/src/nsHTMLTableElement.h +++ b/content/html/content/src/nsHTMLTableElement.h @@ -95,16 +95,17 @@ public: nsGenericHTMLElement) nsMappedAttributes* GetAttributesMappedForCell(); already_AddRefed<nsIDOMHTMLTableSectionElement> GetTHead() { return GetSection(nsGkAtoms::thead); } already_AddRefed<nsIDOMHTMLTableSectionElement> GetTFoot() { return GetSection(nsGkAtoms::tfoot); } + already_AddRefed<nsIDOMHTMLTableCaptionElement> GetCaption(); nsContentList* TBodies(); protected: already_AddRefed<nsIDOMHTMLTableSectionElement> GetSection(nsIAtom *aTag); nsRefPtr<nsContentList> mTBodies; nsRefPtr<TableRowsCollection> mRows; // Sentinel value of TABLE_ATTRS_DIRTY indicates that this is dirty and needs // to be recalculated.
--- a/content/html/content/src/nsHTMLTableRowElement.cpp +++ b/content/html/content/src/nsHTMLTableRowElement.cpp @@ -129,116 +129,95 @@ NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLA NS_IMPL_ELEMENT_CLONE(nsHTMLTableRowElement) // protected method nsresult nsHTMLTableRowElement::GetSection(nsIDOMHTMLTableSectionElement** aSection) { NS_ENSURE_ARG_POINTER(aSection); - *aSection = nsnull; - - nsCOMPtr<nsIDOMNode> sectionNode; - nsresult rv = GetParentNode(getter_AddRefs(sectionNode)); - if (NS_SUCCEEDED(rv) && sectionNode) { - rv = CallQueryInterface(sectionNode, aSection); - } - - return rv; + nsCOMPtr<nsIDOMHTMLTableSectionElement> section = + do_QueryInterface(GetParent()); + section.forget(aSection); + return NS_OK; } // protected method nsresult nsHTMLTableRowElement::GetTable(nsIDOMHTMLTableElement** aTable) { NS_ENSURE_ARG_POINTER(aTable); *aTable = nsnull; - nsCOMPtr<nsIDOMNode> sectionNode; - nsresult rv = GetParentNode(getter_AddRefs(sectionNode)); - if (!sectionNode) { - return rv; + nsIContent* parent = GetParent(); + if (!parent) { + return NS_OK; } // We may not be in a section - rv = CallQueryInterface(sectionNode, aTable); - if (NS_SUCCEEDED(rv)) { - return rv; + nsCOMPtr<nsIDOMHTMLTableElement> table = do_QueryInterface(parent); + if (table) { + table.forget(aTable); + return NS_OK; } - nsCOMPtr<nsIDOMNode> tableNode; - rv = sectionNode->GetParentNode(getter_AddRefs(tableNode)); - if (!tableNode) { - return rv; + parent = parent->GetParent(); + if (!parent) { + return NS_OK; } - - return CallQueryInterface(tableNode, aTable); + table = do_QueryInterface(parent); + table.forget(aTable); + return NS_OK; } NS_IMETHODIMP nsHTMLTableRowElement::GetRowIndex(PRInt32* aValue) { *aValue = -1; nsCOMPtr<nsIDOMHTMLTableElement> table; - - nsresult result = GetTable(getter_AddRefs(table)); + nsresult rv = GetTable(getter_AddRefs(table)); + if (NS_FAILED(rv) || !table) { + return rv; + } - if (NS_SUCCEEDED(result) && table) { - nsCOMPtr<nsIDOMHTMLCollection> rows; - - table->GetRows(getter_AddRefs(rows)); - - PRUint32 numRows; - rows->GetLength(&numRows); + nsCOMPtr<nsIDOMHTMLCollection> rows; + table->GetRows(getter_AddRefs(rows)); - bool found = false; - - for (PRUint32 i = 0; (i < numRows) && !found; i++) { - nsCOMPtr<nsIDOMNode> node; + PRUint32 numRows; + rows->GetLength(&numRows); - rows->Item(i, getter_AddRefs(node)); - - if (node.get() == static_cast<nsIDOMNode *>(this)) { - *aValue = i; - found = true; - } + for (PRUint32 i = 0; i < numRows; i++) { + if (rows->GetNodeAt(i) == static_cast<nsIContent*>(this)) { + *aValue = i; + break; } } - - return result; + return NS_OK; } NS_IMETHODIMP nsHTMLTableRowElement::GetSectionRowIndex(PRInt32* aValue) { *aValue = -1; - nsCOMPtr<nsIDOMHTMLTableSectionElement> section; - - nsresult result = GetSection(getter_AddRefs(section)); - - if (NS_SUCCEEDED(result) && section) { - nsCOMPtr<nsIDOMHTMLCollection> rows; - - section->GetRows(getter_AddRefs(rows)); + nsresult rv = GetSection(getter_AddRefs(section)); + if (NS_FAILED(rv) || !section) { + return rv; + } - bool found = false; - PRUint32 numRows; - - rows->GetLength(&numRows); + nsCOMPtr<nsIDOMHTMLCollection> rows; + section->GetRows(getter_AddRefs(rows)); - for (PRUint32 i = 0; (i < numRows) && !found; i++) { - nsCOMPtr<nsIDOMNode> node; - rows->Item(i, getter_AddRefs(node)); - - if (node.get() == static_cast<nsIDOMNode *>(this)) { - *aValue = i; - found = true; - } - } + PRUint32 numRows; + rows->GetLength(&numRows); + for (PRUint32 i = 0; i < numRows; i++) { + if (rows->GetNodeAt(i) == static_cast<nsIContent*>(this)) { + *aValue = i; + break; + } } return NS_OK; } static bool IsCell(nsIContent *aContent, PRInt32 aNamespaceID, nsIAtom* aAtom, void *aData) @@ -256,18 +235,16 @@ nsHTMLTableRowElement::GetCells(nsIDOMHT mCells = new nsContentList(this, IsCell, nsnull, // destroy func nsnull, // closure data false, nsnull, kNameSpaceID_XHTML, false); - - NS_ENSURE_TRUE(mCells, NS_ERROR_OUT_OF_MEMORY); } NS_ADDREF(*aValue = mCells); return NS_OK; } NS_IMETHODIMP nsHTMLTableRowElement::InsertCell(PRInt32 aIndex, nsIDOMHTMLElement** aValue) @@ -465,9 +442,8 @@ nsHTMLTableRowElement::IsAttributeMapped return FindAttributeDependence(aAttribute, map, ArrayLength(map)); } nsMapRuleToAttributesFunc nsHTMLTableRowElement::GetAttributeMappingFunction() const { return &MapAttributesIntoRule; } -
--- a/content/html/content/src/nsHTMLTableSectionElement.cpp +++ b/content/html/content/src/nsHTMLTableSectionElement.cpp @@ -130,26 +130,22 @@ NS_IMPL_STRING_ATTR(nsHTMLTableSectionEl NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, VAlign, valign) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, Ch, _char) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, ChOff, charoff) NS_IMETHODIMP nsHTMLTableSectionElement::GetRows(nsIDOMHTMLCollection** aValue) { - *aValue = nsnull; - if (!mRows) { mRows = new nsContentList(this, mNodeInfo->NamespaceID(), nsGkAtoms::tr, nsGkAtoms::tr, false); - - NS_ENSURE_TRUE(mRows, NS_ERROR_OUT_OF_MEMORY); } NS_ADDREF(*aValue = mRows); return NS_OK; } NS_IMETHODIMP
--- a/content/html/content/src/nsHTMLTextAreaElement.cpp +++ b/content/html/content/src/nsHTMLTextAreaElement.cpp @@ -196,17 +196,17 @@ public: PRInt32 aModType) const; NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const; virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor); virtual nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor); virtual bool IsHTMLFocusable(bool aWithMouse, bool *aIsFocusable, PRInt32 *aTabIndex); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual bool IsDoneAddingChildren(); virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; nsresult CopyInnerTo(nsGenericElement* aDest) const; /** * Called when an attribute is about to be changed @@ -770,33 +770,31 @@ nsHTMLTextAreaElement::PostHandleEvent(n // Reset the flag for other content besides this text field aVisitor.mEvent->flags |= (aVisitor.mItemFlags & NS_NO_CONTENT_DISPATCH) ? NS_EVENT_FLAG_NO_CONTENT_DISPATCH : NS_EVENT_FLAG_NONE; return NS_OK; } -nsresult +void nsHTMLTextAreaElement::DoneAddingChildren(bool aHaveNotified) { if (!mValueChanged) { if (!mDoneAddingChildren) { // Reset now that we're done adding children if the content sink tried to // sneak some text in without calling AppendChildTo. Reset(); } if (!mInhibitStateRestoration) { RestoreFormControlState(this, this); } } mDoneAddingChildren = true; - - return NS_OK; } bool nsHTMLTextAreaElement::IsDoneAddingChildren() { return mDoneAddingChildren; } @@ -1032,18 +1030,16 @@ nsHTMLTextAreaElement::Reset() SetValueChanged(false); return NS_OK; } NS_IMETHODIMP nsHTMLTextAreaElement::SubmitNamesValues(nsFormSubmission* aFormSubmission) { - nsresult rv = NS_OK; - // Disabled elements don't submit if (IsDisabled()) { return NS_OK; } // // Get the name (if no name, no submit) // @@ -1057,19 +1053,17 @@ nsHTMLTextAreaElement::SubmitNamesValues // Get the value // nsAutoString value; GetValueInternal(value, false); // // Submit // - rv = aFormSubmission->AddNameValuePair(name, value); - - return rv; + return aFormSubmission->AddNameValuePair(name, value); } NS_IMETHODIMP nsHTMLTextAreaElement::SaveState() { nsresult rv = NS_OK; // Only save if value != defaultValue (bug 62713) @@ -1081,18 +1075,18 @@ nsHTMLTextAreaElement::SaveState() GetValueInternal(value, true); rv = nsLinebreakConverter::ConvertStringLineBreaks( value, nsLinebreakConverter::eLinebreakPlatform, nsLinebreakConverter::eLinebreakContent); NS_ASSERTION(NS_SUCCEEDED(rv), "Converting linebreaks failed!"); - nsCOMPtr<nsISupportsString> pState - (do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID)); + nsCOMPtr<nsISupportsString> pState = + do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID); if (!pState) { return NS_ERROR_OUT_OF_MEMORY; } pState->SetData(value); state->SetStateProperty(pState); } } @@ -1304,17 +1298,17 @@ nsHTMLTextAreaElement::AfterSetAttr(PRIn nsresult nsHTMLTextAreaElement::CopyInnerTo(nsGenericElement* aDest) const { nsresult rv = nsGenericHTMLFormElement::CopyInnerTo(aDest); NS_ENSURE_SUCCESS(rv, rv); if (aDest->OwnerDoc()->IsStaticDocument()) { nsAutoString value; - const_cast<nsHTMLTextAreaElement*>(this)->GetValue(value); + GetValueInternal(value, true); static_cast<nsHTMLTextAreaElement*>(aDest)->SetValue(value); } return NS_OK; } bool nsHTMLTextAreaElement::IsMutable() const { @@ -1564,9 +1558,8 @@ nsHTMLTextAreaElement::HasCachedSelectio void nsHTMLTextAreaElement::FieldSetDisabledChanged(bool aNotify) { UpdateValueMissingValidityState(); UpdateBarredFromConstraintValidation(); nsGenericHTMLFormElement::FieldSetDisabledChanged(aNotify); } -
--- a/content/html/content/src/nsHTMLTitleElement.cpp +++ b/content/html/content/src/nsHTMLTitleElement.cpp @@ -79,17 +79,17 @@ public: virtual nsresult BindToTree(nsIDocument *aDocument, nsIContent *aParent, nsIContent *aBindingParent, bool aCompileEventHandlers); virtual void UnbindFromTree(bool aDeep = true, bool aNullParent = true); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual nsXPCClassInfo* GetClassInfo(); private: void SendTitleChangeEvent(bool aBound); }; NS_IMPL_NS_NEW_HTML_ELEMENT(Title) @@ -195,23 +195,22 @@ void nsHTMLTitleElement::UnbindFromTree(bool aDeep, bool aNullParent) { SendTitleChangeEvent(false); // Let this fall through. nsGenericHTMLElement::UnbindFromTree(aDeep, aNullParent); } -nsresult +void nsHTMLTitleElement::DoneAddingChildren(bool aHaveNotified) { if (!aHaveNotified) { SendTitleChangeEvent(false); } - return NS_OK; } void nsHTMLTitleElement::SendTitleChangeEvent(bool aBound) { nsIDocument* doc = GetCurrentDoc(); if (doc) { doc->NotifyPossibleTitleChange(aBound);
--- a/content/html/content/src/nsHTMLVideoElement.cpp +++ b/content/html/content/src/nsHTMLVideoElement.cpp @@ -160,32 +160,32 @@ nsHTMLVideoElement::IsAttributeMapped(co nsMapRuleToAttributesFunc nsHTMLVideoElement::GetAttributeMappingFunction() const { return &MapAttributesIntoRule; } nsresult nsHTMLVideoElement::SetAcceptHeader(nsIHttpChannel* aChannel) { - nsCAutoString value( + nsCAutoString value( #ifdef MOZ_WEBM - "video/webm," + "video/webm," #endif #ifdef MOZ_OGG - "video/ogg," + "video/ogg," #endif - "video/*;q=0.9," + "video/*;q=0.9," #ifdef MOZ_OGG - "application/ogg;q=0.7," + "application/ogg;q=0.7," #endif - "audio/*;q=0.6,*/*;q=0.5"); + "audio/*;q=0.6,*/*;q=0.5"); - return aChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), - value, - false); + return aChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), + value, + false); } NS_IMPL_URI_ATTR(nsHTMLVideoElement, Poster, poster) NS_IMETHODIMP nsHTMLVideoElement::GetMozParsedFrames(PRUint32 *aMozParsedFrames) { NS_ASSERTION(NS_IsMainThread(), "Should be on main thread."); *aMozParsedFrames = mDecoder ? mDecoder->GetFrameStatistics().GetParsedFrames() : 0;
--- a/content/html/content/test/Makefile.in +++ b/content/html/content/test/Makefile.in @@ -265,16 +265,17 @@ include $(topsrcdir)/config/rules.mk test_bug649134.html \ test_bug658746.html \ test_bug659596.html \ test_bug659743.xml \ test_bug660663.html \ test_bug664299.html \ test_bug666200.html \ test_bug666666.html \ + test_bug669012.html \ test_bug674558.html \ test_bug583533.html \ test_restore_from_parser_fragment.html \ test_bug617528.html \ test_bug660959-1.html \ test_bug660959-2.html \ test_bug660959-3.html \ test_checked.html \
new file mode 100644 --- /dev/null +++ b/content/html/content/test/test_bug669012.html @@ -0,0 +1,45 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=669012 +--> +<head> + <title>Test for Bug 669012</title> + <script type="application/javascript" src="/MochiKit/packed.js"></script> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=669012">Mozilla Bug 669012</a> +<p id="display"></p> +<div id="content" style="display: none"> +<script> +var run = 0; +</script> +<svg> +<script> +run++; +ok(true, "Should run SVG script without attributes") +</script> +<script for=window event=onload> +run++; +ok(true, "Should run SVG script with for=window event=onload") +</script> +<script for=window event=foo> +run++; +ok(true, "Should run SVG script with for=window event=foo") +</script> +<script for=foo event=onload> +run++; +ok(true, "Should run SVG script with for=foo event=onload") +</script> +</svg> +</div> +<pre id="test"> +<script type="application/javascript"> +/** Test for Bug 669012 **/ +is(run, 4, "Should have run all tests") +</script> +</pre> +</body> +</html>
--- a/content/html/document/src/ImageDocument.cpp +++ b/content/html/document/src/ImageDocument.cpp @@ -647,34 +647,33 @@ ImageDocument::CreateSyntheticDocument() // We must declare the image as a block element. If we stay as // an inline element, our parent LineBox will be inline too and // ignore the available height during reflow. // This is bad during printing, it means tall image frames won't know // the size of the paper and cannot break into continuations along // multiple pages. Element* head = GetHeadElement(); - if (!head) { - NS_WARNING("no head on image document!"); - return NS_ERROR_FAILURE; - } + NS_ENSURE_TRUE(head, NS_ERROR_FAILURE); nsCOMPtr<nsINodeInfo> nodeInfo; - nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::style, nsnull, - kNameSpaceID_XHTML, - nsIDOMNode::ELEMENT_NODE); - NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); - nsRefPtr<nsGenericHTMLElement> styleContent = NS_NewHTMLStyleElement(nodeInfo.forget()); - if (!styleContent) { - return NS_ERROR_OUT_OF_MEMORY; + if (nsContentUtils::IsChildOfSameType(this)) { + nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::style, nsnull, + kNameSpaceID_XHTML, + nsIDOMNode::ELEMENT_NODE); + NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); + nsRefPtr<nsGenericHTMLElement> styleContent = NS_NewHTMLStyleElement(nodeInfo.forget()); + NS_ENSURE_TRUE(styleContent, NS_ERROR_OUT_OF_MEMORY); + + styleContent->SetTextContent(NS_LITERAL_STRING("img { display: block; }")); + head->AppendChildTo(styleContent, false); + } else { + LinkStylesheet(NS_LITERAL_STRING("resource://gre/res/TopLevelImageDocument.css")); } - styleContent->SetTextContent(NS_LITERAL_STRING("img { display: block; }")); - head->AppendChildTo(styleContent, false); - // Add the image element Element* body = GetBodyElement(); if (!body) { NS_WARNING("no body on image document!"); return NS_ERROR_FAILURE; } nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::img, nsnull,
--- a/content/html/document/src/MediaDocument.cpp +++ b/content/html/document/src/MediaDocument.cpp @@ -238,45 +238,38 @@ MediaDocument::CreateSyntheticDocument() nsCOMPtr<nsINodeInfo> nodeInfo; nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::html, nsnull, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); nsRefPtr<nsGenericHTMLElement> root = NS_NewHTMLHtmlElement(nodeInfo.forget()); - if (!root) { - return NS_ERROR_OUT_OF_MEMORY; - } + NS_ENSURE_TRUE(root, NS_ERROR_OUT_OF_MEMORY); NS_ASSERTION(GetChildCount() == 0, "Shouldn't have any kids"); rv = AppendChildTo(root, false); NS_ENSURE_SUCCESS(rv, rv); nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::head, nsnull, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); // Create a <head> so our title has somewhere to live nsRefPtr<nsGenericHTMLElement> head = NS_NewHTMLHeadElement(nodeInfo.forget()); - if (!head) { - return NS_ERROR_OUT_OF_MEMORY; - } + NS_ENSURE_TRUE(head, NS_ERROR_OUT_OF_MEMORY); - nsCOMPtr<nsINodeInfo> nodeInfoMeta; - nodeInfoMeta = mNodeInfoManager->GetNodeInfo(nsGkAtoms::meta, nsnull, - kNameSpaceID_XHTML, - nsIDOMNode::ELEMENT_NODE); - NS_ENSURE_TRUE(nodeInfoMeta, NS_ERROR_OUT_OF_MEMORY); + nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::meta, nsnull, + kNameSpaceID_XHTML, + nsIDOMNode::ELEMENT_NODE); + NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); - nsRefPtr<nsGenericHTMLElement> metaContent = NS_NewHTMLMetaElement(nodeInfoMeta.forget()); - if (!metaContent) { - return NS_ERROR_OUT_OF_MEMORY; - } + nsRefPtr<nsGenericHTMLElement> metaContent = NS_NewHTMLMetaElement(nodeInfo.forget()); + NS_ENSURE_TRUE(metaContent, NS_ERROR_OUT_OF_MEMORY); metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, NS_LITERAL_STRING("viewport"), true); metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::content, NS_LITERAL_STRING("width=device-width; height=device-height;"), true); head->AppendChildTo(metaContent, false); @@ -284,19 +277,17 @@ MediaDocument::CreateSyntheticDocument() root->AppendChildTo(head, false); nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::body, nsnull, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); nsRefPtr<nsGenericHTMLElement> body = NS_NewHTMLBodyElement(nodeInfo.forget()); - if (!body) { - return NS_ERROR_OUT_OF_MEMORY; - } + NS_ENSURE_TRUE(body, NS_ERROR_OUT_OF_MEMORY); root->AppendChildTo(body, false); return NS_OK; } nsresult MediaDocument::StartLayout() @@ -349,16 +340,37 @@ MediaDocument::GetFileName(nsAString& aR if (NS_SUCCEEDED(rv)) { // UnEscapeURIForUI always succeeds textToSubURI->UnEscapeURIForUI(docCharset, fileName, aResult); } else { CopyUTF8toUTF16(fileName, aResult); } } +nsresult +MediaDocument::LinkStylesheet(const nsAString& aStylesheet) +{ + nsCOMPtr<nsINodeInfo> nodeInfo; + nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::link, nsnull, + kNameSpaceID_XHTML, + nsIDOMNode::ELEMENT_NODE); + NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); + + nsRefPtr<nsGenericHTMLElement> link = NS_NewHTMLLinkElement(nodeInfo.forget()); + NS_ENSURE_TRUE(link, NS_ERROR_OUT_OF_MEMORY); + + link->SetAttr(kNameSpaceID_None, nsGkAtoms::rel, + NS_LITERAL_STRING("stylesheet"), true); + + link->SetAttr(kNameSpaceID_None, nsGkAtoms::href, aStylesheet, true); + + Element* head = GetHeadElement(); + return head->AppendChildTo(link, false); +} + void MediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr, const char* const* aFormatNames, PRInt32 aWidth, PRInt32 aHeight, const nsAString& aStatus) { nsXPIDLString fileStr; GetFileName(fileStr);
--- a/content/html/document/src/MediaDocument.h +++ b/content/html/document/src/MediaDocument.h @@ -67,16 +67,18 @@ public: protected: virtual nsresult CreateSyntheticDocument(); friend class MediaDocumentStreamListener; nsresult StartLayout(); void GetFileName(nsAString& aResult); + nsresult LinkStylesheet(const nsAString& aStylesheet); + // |aFormatNames[]| needs to have four elements in the following order: // a format name with neither dimension nor file, a format name with // filename but w/o dimension, a format name with dimension but w/o filename, // a format name with both of them. For instance, it can have // "ImageTitleWithNeitherDimensionsNorFile", "ImageTitleWithoutDimensions", // "ImageTitleWithDimesions", "ImageTitleWithDimensionsAndFile". // // Also see MediaDocument.properties if you want to define format names
--- a/content/html/document/src/VideoDocument.cpp +++ b/content/html/document/src/VideoDocument.cpp @@ -129,34 +129,17 @@ VideoDocument::CreateSyntheticVideoDocum if (nsContentUtils::IsChildOfSameType(this)) { // Video documents that aren't toplevel should fill their frames and // not have margins element->SetAttr(kNameSpaceID_None, nsGkAtoms::style, NS_LITERAL_STRING("position:absolute; top:0; left:0; width:100%; height:100%"), true); } else { - Element* head = GetHeadElement(); - if (!head) { - NS_WARNING("no head on video document!"); - return NS_ERROR_FAILURE; - } - - nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::style, nsnull, - kNameSpaceID_XHTML, - nsIDOMNode::ELEMENT_NODE); - NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); - nsRefPtr<nsGenericHTMLElement> styleContent = NS_NewHTMLStyleElement(nodeInfo.forget()); - NS_ENSURE_TRUE(styleContent, NS_ERROR_OUT_OF_MEMORY); - - styleContent->SetTextContent( - NS_LITERAL_STRING("body { background: url(chrome://global/skin/icons/tabprompts-bgtexture.png) #333; height: 100%; width: 100%; margin: 0; padding: 0; } ") + - NS_LITERAL_STRING("video { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; box-shadow: 0 0 15px #000; } ") + - NS_LITERAL_STRING("video:focus { outline-width: 0; } ")); - head->AppendChildTo(styleContent, false); + LinkStylesheet(NS_LITERAL_STRING("resource://gre/res/TopLevelVideoDocument.css")); } return body->AppendChildTo(element, false); } void VideoDocument::UpdateTitle(nsIChannel* aChannel) { @@ -170,19 +153,17 @@ VideoDocument::UpdateTitle(nsIChannel* a } // namespace dom } // namespace mozilla nsresult NS_NewVideoDocument(nsIDocument** aResult) { mozilla::dom::VideoDocument* doc = new mozilla::dom::VideoDocument(); - if (!doc) { - return NS_ERROR_OUT_OF_MEMORY; - } + NS_ENSURE_TRUE(doc, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF(doc); nsresult rv = doc->Init(); if (NS_FAILED(rv)) { NS_RELEASE(doc); }
--- a/content/html/document/src/nsHTMLContentSink.cpp +++ b/content/html/document/src/nsHTMLContentSink.cpp @@ -2795,42 +2795,40 @@ HTMLContentSink::ProcessSCRIPTEndTag(nsG if (mFrameset) { sele->PreventExecution(); } // Notify our document that we're loading this script. mHTMLDocument->ScriptLoading(sele); // Now tell the script that it's ready to go. This may execute the script - // or return NS_ERROR_HTMLPARSER_BLOCK. Or neither if the script doesn't - // need executing. - nsresult rv = content->DoneAddingChildren(true); + // or return true, or neither if the script doesn't need executing. + bool block = sele->AttemptToExecute(); // If the act of insertion evaluated the script, we're fine. // Else, block the parser till the script has loaded. - if (rv == NS_ERROR_HTMLPARSER_BLOCK) { + if (block) { // If this append fails we'll never unblock the parser, but the UI will // still remain responsive. There are other ways to deal with this, but // the end result is always that the page gets botched, so there is no // real point in making it more complicated. mScriptElements.AppendObject(sele); - } - else { + } else { // This may have already happened if the script executed, but in case // it didn't then remove the element so that it doesn't get stuck forever. mHTMLDocument->ScriptExecuted(sele); } // If the parser got blocked, make sure to return the appropriate rv. // I'm not sure if this is actually needed or not. if (mParser && !mParser->IsParserEnabled()) { - rv = NS_ERROR_HTMLPARSER_BLOCK; + block = true; } - return rv; + return block ? NS_ERROR_HTMLPARSER_BLOCK : NS_OK; } // 3 ways to load a style sheet: inline, style src=, link tag // XXX What does nav do if we have SRC= and some style data inline? nsresult HTMLContentSink::ProcessSTYLEEndTag(nsGenericHTMLElement* content) {
--- a/content/html/document/src/nsHTMLDocument.cpp +++ b/content/html/document/src/nsHTMLDocument.cpp @@ -945,20 +945,18 @@ nsHTMLDocument::StartDocumentLoad(const "How did those end up different here? wyciwyg channels are " "not nsICachingChannel"); rv = cachingChan->SetCacheTokenCachedCharset(charset); NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "cannot SetMetaDataElement"); } // Set the parser as the stream listener for the document loader... if (mParser) { - rv = mParser->GetStreamListener(aDocListener); - if (NS_FAILED(rv)) { - return rv; - } + nsCOMPtr<nsIStreamListener> listener = mParser->GetStreamListener(); + listener.forget(aDocListener); #ifdef DEBUG_charset printf(" charset = %s source %d\n", charset.get(), charsetSource); #endif mParser->SetDocumentCharset(parserCharset, parserCharsetSource); mParser->SetCommand(aCommand);
new file mode 100644 --- /dev/null +++ b/content/smil/crashtests/691337-1.svg @@ -0,0 +1,8 @@ +<?xml version="1.0"?> +<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"> + <rect width="100" height="100" fill="blue"> + <animate attributeName="fill" + begin="999999999999999999999999999999999999999999999999999999999999999999999999999999999" + dur="5s" from="blue" to="red" repeatCount="indefinite" additive="sum"/> + </rect> +</svg>
new file mode 100644 --- /dev/null +++ b/content/smil/crashtests/691337-2.svg @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"> + <rect width="100" height="100" fill="blue"> + <animate attributeName="fill" id="a" + begin="4999999999999999" dur="5s" from="blue" to="red" + repeatCount="indefinite" additive="sum"/> + <animate attributeName="fill" + begin="a.begin+4999999999999999" + dur="5s" from="blue" to="red" repeatCount="indefinite" additive="sum"/> + </rect> +</svg>
--- a/content/smil/crashtests/crashtests.list +++ b/content/smil/crashtests/crashtests.list @@ -38,10 +38,12 @@ load 650732-1.svg load 665334-1.svg load 669225-1.svg load 669225-2.svg load 670313-1.svg load 678822-1.svg load 678847-1.svg load 678938-1.svg load 690994-1.svg +load 691337-1.svg +load 691337-2.svg load 697640-1.svg load 699325-1.svg
--- a/content/smil/nsSMILParserUtils.cpp +++ b/content/smil/nsSMILParserUtils.cpp @@ -725,17 +725,16 @@ nsSMILParserUtils::ParseClockValue(const { nsSMILTime offset = 0L; double component = 0.0; PRInt8 sign = 0; PRUint8 colonCount = 0; bool started = false; - bool isValid = true; PRInt32 metricMultiplicand = MSEC_PER_SEC; bool numIsReal = false; bool prevNumCouldBeMin = false; bool numCouldBeMin = false; bool numCouldBeSec = false; bool isIndefinite = false; @@ -754,147 +753,139 @@ nsSMILParserUtils::ParseClockValue(const ++start; break; } // else, we haven't started yet, ignore initial whitespace ++start; } else if ((aFlags & kClockValueAllowSign) && (*start == '+' || *start == '-')) { + // check sign has not already been set if (sign != 0) { - // sign has already been set - isValid = false; - break; + return NS_ERROR_FAILURE; } + // check sign is not in middle of string if (started) { - // sign appears in the middle of the string - isValid = false; - break; + return NS_ERROR_FAILURE; } sign = (*start == '+') ? 1 : -1; ++start; // The NS_IS_DIGIT etc. macros are not locale-specific } else if (NS_IS_DIGIT(*start)) { prevNumCouldBeMin = numCouldBeMin; if (!ParseClockComponent(start, end, component, numIsReal, numCouldBeMin, - numCouldBeSec)) { - isValid = false; - break; - } + numCouldBeSec)) + return NS_ERROR_FAILURE; started = true; } else if (*start == ':') { ++colonCount; // Neither minutes nor hours can be reals if (numIsReal) { - isValid = false; - break; + return NS_ERROR_FAILURE; } // Clock value can't start with a ':' if (!started) { - isValid = false; - break; + return NS_ERROR_FAILURE; } // Can't have more than two colons if (colonCount > 2) { - isValid = false; - break; + return NS_ERROR_FAILURE; } // Multiply the offset by 60 and add the last accumulated component - offset = offset * 60 + PRInt64(component); + offset = offset * 60 + nsSMILTime(component); component = 0.0; ++start; } else if (NS_IS_ALPHA(*start)) { if (colonCount > 0) { - isValid = false; - break; + return NS_ERROR_FAILURE; } if ((aFlags & kClockValueAllowIndefinite) && ConsumeSubstring(start, end, "indefinite")) { // We set a separate flag because we don't know what the state of the // passed in time value is and we shouldn't change it in the case of a // bad input string (so we can't initialise it to 0ms for example). isIndefinite = true; if (aResult) { aResult->SetIndefinite(); } } else if (aIsMedia && ConsumeSubstring(start, end, "media")) { *aIsMedia = true; } else if (!ParseMetricMultiplicand(start, end, metricMultiplicand)) { - isValid = false; - break; + return NS_ERROR_FAILURE; } // Nothing must come after the string except whitespace break; } else { - isValid = false; - break; + return NS_ERROR_FAILURE; } } if (!started) { - isValid = false; + return NS_ERROR_FAILURE; } // Process remainder of string (if any) to ensure it is only trailing // whitespace (embedded whitespace is not allowed) SkipBeginWsp(start, end); if (start != end) { - isValid = false; + return NS_ERROR_FAILURE; } // No more processing required if the value was "indefinite" or "media". - if (isIndefinite || (aIsMedia && *aIsMedia)) + if (isIndefinite || (aIsMedia && *aIsMedia)) { return NS_OK; + } // If there is more than one colon then the previous component must be a // correctly formatted minute (i.e. two digits between 00 and 59) and the // latest component must be a correctly formatted second (i.e. two digits // before the .) if (colonCount > 0 && (!prevNumCouldBeMin || !numCouldBeSec)) { - isValid = false; + return NS_ERROR_FAILURE; } - if (isValid) { - // Tack on the last component - if (colonCount > 0) { - offset = offset * 60 * 1000; - component *= 1000; - // rounding - component = (component >= 0) ? component + 0.5 : component - 0.5; - offset += PRInt64(component); - } else { - component *= metricMultiplicand; - // rounding - component = (component >= 0) ? component + 0.5 : component - 0.5; - offset = PRInt64(component); - } - - if (aResult) { - nsSMILTime millis = offset; - - if (sign == -1) { - millis = -offset; - } - - aResult->SetMillis(millis); - } + // Tack on the last component + if (colonCount > 0) { + offset = offset * 60 * 1000; + component *= 1000; + // rounding + component = (component >= 0) ? component + 0.5 : component - 0.5; + offset += nsSMILTime(component); + } else { + component *= metricMultiplicand; + // rounding + component = (component >= 0) ? component + 0.5 : component - 0.5; + offset = nsSMILTime(component); } - return (isValid) ? NS_OK : NS_ERROR_FAILURE; + // we haven't applied the sign yet so if the result is negative we must have + // overflowed + if (offset < 0) { + return NS_ERROR_FAILURE; + } + + if (aResult) { + if (sign == -1) { + offset = -offset; + } + aResult->SetMillis(offset); + } + + return NS_OK; } PRInt32 nsSMILParserUtils::CheckForNegativeNumber(const nsAString& aStr) { PRInt32 absValLocation = -1; nsAString::const_iterator start, end;
--- a/content/smil/nsSMILTimeValueSpec.cpp +++ b/content/smil/nsSMILTimeValueSpec.cpp @@ -43,16 +43,17 @@ #include "nsSMILInstanceTime.h" #include "nsSMILParserUtils.h" #include "nsISMILAnimationElement.h" #include "nsContentUtils.h" #include "nsEventListenerManager.h" #include "nsGUIEvent.h" #include "nsIDOMTimeEvent.h" #include "nsString.h" +#include <limits> using namespace mozilla::dom; //---------------------------------------------------------------------- // Nested class: EventListener NS_IMPL_ISUPPORTS1(nsSMILTimeValueSpec::EventListener, nsIDOMEventListener) @@ -177,18 +178,19 @@ nsSMILTimeValueSpec::HandleNewInterval(n const nsSMILTimeContainer* aSrcContainer) { const nsSMILInstanceTime& baseInstance = mParams.mSyncBegin ? *aInterval.Begin() : *aInterval.End(); nsSMILTimeValue newTime = ConvertBetweenTimeContainers(baseInstance.Time(), aSrcContainer); // Apply offset - if (newTime.IsDefinite()) { - newTime.SetMillis(newTime.GetMillis() + mParams.mOffset.GetMillis()); + if (!ApplyOffset(newTime)) { + NS_WARNING("New time overflows nsSMILTime, ignoring"); + return; } // Create the instance time and register it with the interval nsRefPtr<nsSMILInstanceTime> newInstance = new nsSMILInstanceTime(newTime, nsSMILInstanceTime::SOURCE_SYNCBASE, this, &aInterval); mOwner->AddInstanceTime(newInstance, mIsBegin); } @@ -213,19 +215,19 @@ nsSMILTimeValueSpec::HandleChangedInstan // time of an active or postactive interval) we just ignore the change. if (aInstanceTimeToUpdate.IsFixedTime()) return; nsSMILTimeValue updatedTime = ConvertBetweenTimeContainers(aBaseTime.Time(), aSrcContainer); // Apply offset - if (updatedTime.IsDefinite()) { - updatedTime.SetMillis(updatedTime.GetMillis() + - mParams.mOffset.GetMillis()); + if (!ApplyOffset(updatedTime)) { + NS_WARNING("Updated time overflows nsSMILTime, ignoring"); + return; } // The timed element that owns the instance time does the updating so it can // re-sort its array of instance times more efficiently if (aInstanceTimeToUpdate.Time() != updatedTime || aObjectChanged) { mOwner->UpdateInstanceTime(&aInstanceTimeToUpdate, updatedTime, mIsBegin); } } @@ -334,17 +336,17 @@ nsSMILTimeValueSpec::RegisterEventListen if (!mEventListener) { mEventListener = new EventListener(this); } nsEventListenerManager* elm = GetEventListenerManager(aTarget); if (!elm) return; - + elm->AddEventListenerByType(mEventListener, nsDependentAtomString(mParams.mEventSymbol), NS_EVENT_FLAG_BUBBLE | NS_PRIV_EVENT_UNTRUSTED_PERMITTED | NS_EVENT_FLAG_SYSTEM_EVENT); } void @@ -402,17 +404,21 @@ nsSMILTimeValueSpec::HandleEvent(nsIDOME nsSMILTimeContainer* container = mOwner->GetTimeContainer(); if (!container) return; if (!CheckEventDetail(aEvent)) return; nsSMILTime currentTime = container->GetCurrentTime(); - nsSMILTimeValue newTime(currentTime + mParams.mOffset.GetMillis()); + nsSMILTimeValue newTime(currentTime); + if (!ApplyOffset(newTime)) { + NS_WARNING("New time generated from event overflows nsSMILTime, ignoring"); + return; + } nsRefPtr<nsSMILInstanceTime> newInstance = new nsSMILInstanceTime(newTime, nsSMILInstanceTime::SOURCE_EVENT); mOwner->AddInstanceTime(newInstance, mIsBegin); } bool nsSMILTimeValueSpec::CheckEventDetail(nsIDOMEvent *aEvent) @@ -530,8 +536,26 @@ nsSMILTimeValueSpec::ConvertBetweenTimeC // time. Just return the indefinite time. return docTime; NS_ABORT_IF_FALSE(docTime.IsDefinite(), "ContainerToParentTime gave us an unresolved or indefinite time"); return dstContainer->ParentToContainerTime(docTime.GetMillis()); } + +bool +nsSMILTimeValueSpec::ApplyOffset(nsSMILTimeValue& aTime) const +{ + // indefinite + offset = indefinite. Likewise for unresolved times. + if (!aTime.IsDefinite()) { + return true; + } + + double resultAsDouble = + (double)aTime.GetMillis() + mParams.mOffset.GetMillis(); + if (resultAsDouble > std::numeric_limits<nsSMILTime>::max() || + resultAsDouble < std::numeric_limits<nsSMILTime>::min()) { + return false; + } + aTime.SetMillis(aTime.GetMillis() + mParams.mOffset.GetMillis()); + return true; +}
--- a/content/smil/nsSMILTimeValueSpec.h +++ b/content/smil/nsSMILTimeValueSpec.h @@ -97,16 +97,17 @@ protected: void UnregisterEventListener(Element* aElement); nsEventListenerManager* GetEventListenerManager(Element* aElement); void HandleEvent(nsIDOMEvent* aEvent); bool CheckEventDetail(nsIDOMEvent* aEvent); bool CheckRepeatEventDetail(nsIDOMEvent* aEvent); bool CheckAccessKeyEventDetail(nsIDOMEvent* aEvent); nsSMILTimeValue ConvertBetweenTimeContainers(const nsSMILTimeValue& aSrcTime, const nsSMILTimeContainer* aSrcContainer); + bool ApplyOffset(nsSMILTimeValue& aTime) const; nsSMILTimedElement* mOwner; bool mIsBegin; // Indicates if *we* are a begin spec, // not to be confused with // mParams.mSyncBegin which indicates // if we're synced with the begin of // the target. nsSMILTimeValueSpecParams mParams;
--- a/content/smil/nsSMILTimedElement.cpp +++ b/content/smil/nsSMILTimedElement.cpp @@ -1883,19 +1883,19 @@ nsSMILTimedElement::ApplyMinAndMax(const } nsSMILTime nsSMILTimedElement::ActiveTimeToSimpleTime(nsSMILTime aActiveTime, PRUint32& aRepeatIteration) { nsSMILTime result; - NS_ASSERTION(mSimpleDur.IsResolved(), + NS_ABORT_IF_FALSE(mSimpleDur.IsResolved(), "Unresolved simple duration in ActiveTimeToSimpleTime"); - NS_ASSERTION(aActiveTime >= 0, "Expecting non-negative active time"); + NS_ABORT_IF_FALSE(aActiveTime >= 0, "Expecting non-negative active time"); // Note that a negative aActiveTime will give us a negative value for // aRepeatIteration, which is bad because aRepeatIteration is unsigned if (mSimpleDur.IsIndefinite() || mSimpleDur.GetMillis() == 0L) { aRepeatIteration = 0; result = aActiveTime; } else { result = aActiveTime % mSimpleDur.GetMillis();
--- a/content/smil/test/test_smilDynamicDelayedBeginElement.xhtml +++ b/content/smil/test/test_smilDynamicDelayedBeginElement.xhtml @@ -23,17 +23,25 @@ https://bugzilla.mozilla.org/show_bug.cg /** Test for Bug 699143 **/ SimpleTest.waitForExplicitFinish(); // Values for 'width' attr on the <rect> above const INITIAL_VAL = "500px" const FROM_VAL = "20px"; const TO_VAL = "80px"; -// Helper function +// Helper functions + +// This function allows 10ms to pass +function allowTimeToPass() { + var initialDate = new Date(); + while (new Date() - initialDate < 10) {} +} + +// This function returns a newly created <animate> element for use in this test function createAnim() { var a = document.createElementNS('http://www.w3.org/2000/svg', 'animate'); a.setAttribute('attributeName', 'width'); a.setAttribute('from', FROM_VAL); a.setAttribute('to', TO_VAL); a.setAttribute('begin', 'indefinite'); a.setAttribute('dur', '3s'); a.setAttribute('fill', 'freeze'); @@ -45,23 +53,28 @@ function main() { if (!SMILUtil.isSMILEnabled()) { ok(false, "SMIL dosn't seem to be enabled"); SimpleTest.finish(); return; } // In unpatched Firefox builds, we'll only trigger Bug 699143 if we insert // an animation and call beginElement() **after** the document start-time. - // Hence, we use executeSoon here to allow some time to pass. + // Hence, we use executeSoon here to allow some time to pass. (And then + // we'll use a short busy-loop, for good measure.) SimpleTest.executeSoon(runTest); } function runTest() { var svg = SMILUtil.getSVGRoot(); + // In case our executeSoon fired immediately, we force a very small amount + // of time to pass here, using a 10ms busy-loop. + allowTimeToPass(); + is(svg.getCurrentTime(), 0, "even though we've allowed time to pass, we shouldn't have bothered " + "updating the current time, since there aren't any animation elements"); // Insert an animation elem (should affect currentTime but not targeted attr) var r = document.getElementById("r"); var a = createAnim(); r.appendChild(a);
--- a/content/svg/content/src/nsSVGScriptElement.cpp +++ b/content/svg/content/src/nsSVGScriptElement.cpp @@ -89,18 +89,16 @@ public: // nsScriptElement virtual bool HasScriptContent(); // nsSVGElement specializations: virtual void DidChangeString(PRUint8 aAttrEnum); // nsIContent specializations: - virtual nsresult DoneAddingChildren(bool aHaveNotified); - virtual bool IsDoneAddingChildren(); virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent, nsIContent* aBindingParent, bool aCompileEventHandlers); virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; virtual nsXPCClassInfo* GetClassInfo(); protected: @@ -270,35 +268,16 @@ nsSVGScriptElement::GetStringInfo() return StringAttributesInfo(mStringAttributes, sStringInfo, ArrayLength(sStringInfo)); } //---------------------------------------------------------------------- // nsIContent methods nsresult -nsSVGScriptElement::DoneAddingChildren(bool aHaveNotified) -{ - mDoneAddingChildren = true; - nsresult rv = MaybeProcessScript(); - if (!mAlreadyStarted) { - // Need to lose parser-insertedness here to allow another script to cause - // execution later. - LoseParserInsertedness(); - } - return rv; -} - -bool -nsSVGScriptElement::IsDoneAddingChildren() -{ - return mDoneAddingChildren; -} - -nsresult nsSVGScriptElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent, nsIContent* aBindingParent, bool aCompileEventHandlers) { nsresult rv = nsSVGScriptElementBase::BindToTree(aDocument, aParent, aBindingParent, aCompileEventHandlers); NS_ENSURE_SUCCESS(rv, rv);
--- a/content/svg/content/src/nsSVGTitleElement.cpp +++ b/content/svg/content/src/nsSVGTitleElement.cpp @@ -72,17 +72,17 @@ public: virtual nsresult BindToTree(nsIDocument *aDocument, nsIContent *aParent, nsIContent *aBindingParent, bool aCompileEventHandlers); virtual void UnbindFromTree(bool aDeep = true, bool aNullParent = true); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual nsXPCClassInfo* GetClassInfo(); private: void SendTitleChangeEvent(bool aBound); }; NS_IMPL_NS_NEW_SVG_ELEMENT(Title) @@ -175,23 +175,22 @@ void nsSVGTitleElement::UnbindFromTree(bool aDeep, bool aNullParent) { SendTitleChangeEvent(false); // Let this fall through. nsSVGTitleElementBase::UnbindFromTree(aDeep, aNullParent); } -nsresult +void nsSVGTitleElement::DoneAddingChildren(bool aHaveNotified) { if (!aHaveNotified) { SendTitleChangeEvent(false); } - return NS_OK; } void nsSVGTitleElement::SendTitleChangeEvent(bool aBound) { nsIDocument* doc = GetCurrentDoc(); if (doc) { doc->NotifyPossibleTitleChange(aBound);
--- a/content/xbl/src/nsXBLBinding.cpp +++ b/content/xbl/src/nsXBLBinding.cpp @@ -1203,29 +1203,27 @@ nsXBLBinding::WalkRules(nsIStyleRuleProc // Internal helper methods //////////////////////////////////////////////////////////////// // static nsresult nsXBLBinding::DoInitJSClass(JSContext *cx, JSObject *global, JSObject *obj, const nsAFlatCString& aClassName, nsXBLPrototypeBinding* aProtoBinding, - void **aClassObject) + JSObject** aClassObject) { // First ensure our JS class is initialized. - jsval val; - JSObject* proto = NULL; - nsCAutoString className(aClassName); JSObject* parent_proto = nsnull; // If we have an "obj" we can set this JSAutoRequest ar(cx); JSAutoEnterCompartment ac; - if (!ac.enter(cx, global)) - return NS_ERROR_FAILURE; + if (!ac.enter(cx, global)) { + return NS_ERROR_FAILURE; + } if (obj) { // Retrieve the current prototype of obj. parent_proto = ::JS_GetPrototype(cx, obj); if (parent_proto) { // We need to create a unique classname based on aClassName and // parent_proto. Append a space (an invalid URI character) to ensure that // we don't have accidental collisions with the case when parent_proto is @@ -1241,16 +1239,18 @@ nsXBLBinding::DoInitJSClass(JSContext *c // string representation of what we're printing does not fit in the buffer // provided). char buf[20]; PR_snprintf(buf, sizeof(buf), " %lx", parent_proto_id); className.Append(buf); } } + jsval val; + JSObject* proto = NULL; if ((!::JS_LookupPropertyWithFlags(cx, global, className.get(), JSRESOLVE_CLASSNAME, &val)) || JSVAL_IS_PRIMITIVE(val)) { // We need to initialize the class. nsXBLJSClass* c; void* classObject; @@ -1331,17 +1331,17 @@ nsXBLBinding::DoInitJSClass(JSContext *c if (!::JS_SetReservedSlot(cx, proto, 0, PRIVATE_TO_JSVAL(aProtoBinding))) { (nsXBLService::gClassTable)->Remove(&key); // |c| will get dropped when |proto| is finalized return NS_ERROR_OUT_OF_MEMORY; } - *aClassObject = (void*)proto; + *aClassObject = proto; } else { proto = JSVAL_TO_OBJECT(val); } if (obj) { // Set the prototype of our object to be the new class. if (!::JS_SetPrototype(cx, obj, proto)) {
--- a/content/xbl/src/nsXBLBinding.h +++ b/content/xbl/src/nsXBLBinding.h @@ -141,17 +141,17 @@ public: void WalkRules(nsIStyleRuleProcessor::EnumFunc aFunc, void* aData); nsINodeList* GetAnonymousNodes(); static nsresult DoInitJSClass(JSContext *cx, JSObject *global, JSObject *obj, const nsAFlatCString& aClassName, nsXBLPrototypeBinding* aProtoBinding, - void **aClassObject); + JSObject** aClassObject); bool AllowScripts(); // XXX make const void RemoveInsertionParent(nsIContent* aParent); bool HasInsertionParent(nsIContent* aParent); // MEMBER VARIABLES protected:
--- a/content/xbl/src/nsXBLDocumentInfo.cpp +++ b/content/xbl/src/nsXBLDocumentInfo.cpp @@ -306,19 +306,17 @@ nsXBLDocGlobalObject::EnsureScriptEnviro nsCOMPtr<nsIDOMScriptObjectFactory> factory = do_GetService(kDOMScriptObjectFactoryCID); NS_ENSURE_TRUE(factory, nsnull); nsresult rv; nsCOMPtr<nsIScriptRuntime> scriptRuntime; rv = NS_GetScriptRuntimeByID(aLangID, getter_AddRefs(scriptRuntime)); NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr<nsIScriptContext> newCtx; - rv = scriptRuntime->CreateContext(getter_AddRefs(newCtx)); - NS_ENSURE_SUCCESS(rv, rv); + nsCOMPtr<nsIScriptContext> newCtx = scriptRuntime->CreateContext(); rv = SetScriptContext(aLangID, newCtx); JSContext *cx = mScriptContext->GetNativeContext(); JSAutoRequest ar(cx); // nsJSEnvironment set the error reporter to NS_ScriptErrorReporter so // we must apparently override that with our own (although it isn't clear // why - see bug 339647)
--- a/content/xbl/src/nsXBLProtoImpl.cpp +++ b/content/xbl/src/nsXBLProtoImpl.cpp @@ -90,17 +90,17 @@ nsXBLProtoImpl::InstallImplementation(ns nsCOMPtr<nsIScriptContext> context = global->GetContext(); if (!context) return NS_OK; // InitTarget objects gives us back the JS object that represents the bound element and the // class object in the bound document that represents the concrete version of this implementation. // This function also has the side effect of building up the prototype implementation if it has // not been built already. nsCOMPtr<nsIXPConnectJSObjectHolder> holder; - void * targetClassObject = nsnull; + JSObject* targetClassObject = nsnull; nsresult rv = InitTargetObjects(aBinding, context, aBoundElement, getter_AddRefs(holder), &targetClassObject); NS_ENSURE_SUCCESS(rv, rv); // kick out if we were unable to properly intialize our target objects JSObject * targetScriptObject; holder->GetJSObject(&targetScriptObject); JSContext *cx = context->GetNativeContext(); @@ -117,17 +117,17 @@ nsXBLProtoImpl::InstallImplementation(ns return NS_OK; } nsresult nsXBLProtoImpl::InitTargetObjects(nsXBLPrototypeBinding* aBinding, nsIScriptContext* aContext, nsIContent* aBoundElement, nsIXPConnectJSObjectHolder** aScriptObjectHolder, - void** aTargetClassObject) + JSObject** aTargetClassObject) { nsresult rv = NS_OK; *aScriptObjectHolder = nsnull; if (!mClassObject) { rv = CompilePrototypeMembers(aBinding); // This is the first time we've ever installed this binding on an element. // We need to go ahead and compile all methods and properties on a class // in our prototype binding. @@ -156,18 +156,19 @@ nsXBLProtoImpl::InitTargetObjects(nsXBLP NS_ENSURE_SUCCESS(rv, rv); // All of the above code was just obtaining the bound element's script object and its immediate // concrete base class. We need to alter the object so that our concrete class is interposed // between the object and its base class. We become the new base class of the object, and the // object's old base class becomes the new class' base class. rv = aBinding->InitClass(mClassName, jscontext, global, JSVAL_TO_OBJECT(v), aTargetClassObject); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return rv; + } nsContentUtils::PreserveWrapper(aBoundElement, aBoundElement); wrapper.swap(*aScriptObjectHolder); return rv; } @@ -184,23 +185,23 @@ nsXBLProtoImpl::CompilePrototypeMembers( nsIScriptContext *context = globalObject->GetContext(); NS_ENSURE_TRUE(context, NS_ERROR_OUT_OF_MEMORY); JSContext *cx = context->GetNativeContext(); JSObject *global = globalObject->GetGlobalJSObject(); - void* classObject; + JSObject* classObject; nsresult rv = aBinding->InitClass(mClassName, cx, global, global, &classObject); if (NS_FAILED(rv)) return rv; - mClassObject = (JSObject*) classObject; + mClassObject = classObject; if (!mClassObject) return NS_ERROR_FAILURE; AutoVersionChecker avc(cx); // Now that we have a class object installed, we walk our member list and compile each of our // properties and methods in turn. for (nsXBLProtoImplMember* curr = mMembers; @@ -302,25 +303,25 @@ nsXBLProtoImpl::DestroyMembers() nsresult nsXBLProtoImpl::Read(nsIScriptContext* aContext, nsIObjectInputStream* aStream, nsXBLPrototypeBinding* aBinding, nsIScriptGlobalObject* aGlobal) { // Set up a class object first so that deserialization is possible - JSContext *cx = static_cast<JSContext *>(aContext->GetNativeContext()); + JSContext *cx = aContext->GetNativeContext(); JSObject *global = aGlobal->GetGlobalJSObject(); - void* classObject; + JSObject* classObject; nsresult rv = aBinding->InitClass(mClassName, cx, global, global, &classObject); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(classObject, NS_ERROR_FAILURE); - mClassObject = (JSObject*) classObject; + mClassObject = classObject; nsXBLProtoImplField* previousField = nsnull; nsXBLProtoImplMember* previousMember = nsnull; do { XBLBindingSerializeDetails type; rv = aStream->Read8(&type); NS_ENSURE_SUCCESS(rv, rv);
--- a/content/xbl/src/nsXBLProtoImpl.h +++ b/content/xbl/src/nsXBLProtoImpl.h @@ -68,17 +68,17 @@ public: delete mMembers; delete mFields; } nsresult InstallImplementation(nsXBLPrototypeBinding* aBinding, nsIContent* aBoundElement); nsresult InitTargetObjects(nsXBLPrototypeBinding* aBinding, nsIScriptContext* aContext, nsIContent* aBoundElement, nsIXPConnectJSObjectHolder** aScriptObjectHolder, - void** aTargetClassObject); + JSObject** aTargetClassObject); nsresult CompilePrototypeMembers(nsXBLPrototypeBinding* aBinding); void SetMemberList(nsXBLProtoImplMember* aMemberList) { delete mMembers; mMembers = aMemberList; } @@ -126,18 +126,18 @@ protected: } void DestroyMembers(); public: nsCString mClassName; // The name of the class. protected: - void* mClassObject; // The class object for the binding. We'll use this to pre-compile properties - // and methods for the binding. + JSObject* mClassObject; // The class object for the binding. We'll use this to pre-compile properties + // and methods for the binding. nsXBLProtoImplMember* mMembers; // The members of an implementation are chained in this singly-linked list. nsXBLProtoImplField* mFields; // Our fields public: nsXBLProtoImplAnonymousMethod* mConstructor; // Our class constructor. nsXBLProtoImplAnonymousMethod* mDestructor; // Our class destructor.
--- a/content/xbl/src/nsXBLProtoImplField.cpp +++ b/content/xbl/src/nsXBLProtoImplField.cpp @@ -143,19 +143,20 @@ nsXBLProtoImplField::InstallField(nsIScr JSAutoRequest ar(cx); jsval result = JSVAL_NULL; rv = context->EvaluateStringWithValue(nsDependentString(mFieldText, mFieldTextLength), aBoundNode, aPrincipal, uriSpec.get(), mLineNumber, JSVERSION_LATEST, - (void*) &result, &undefined); - if (NS_FAILED(rv)) + &result, &undefined); + if (NS_FAILED(rv)) { return rv; + } if (undefined) { result = JSVAL_VOID; } // Define the evaluated result as a JS property nsDependentString name(mName); if (!::JS_DefineUCProperty(cx, aBoundNode,
--- a/content/xbl/src/nsXBLProtoImplMethod.cpp +++ b/content/xbl/src/nsXBLProtoImplMethod.cpp @@ -267,19 +267,17 @@ nsXBLProtoImplMethod::Trace(TraceCallbac aCallback(nsIProgrammingLanguage::JAVASCRIPT, mJSMethodObject, "mJSMethodObject", aClosure); } } nsresult nsXBLProtoImplMethod::Read(nsIScriptContext* aContext, nsIObjectInputStream* aStream) { - void* methodCode; - nsresult rv = XBL_DeserializeFunction(aContext, aStream, this, &methodCode); - mJSMethodObject = (JSObject *)methodCode; + nsresult rv = XBL_DeserializeFunction(aContext, aStream, &mJSMethodObject); if (NS_FAILED(rv)) { SetUncompiledMethod(nsnull); return rv; } #ifdef DEBUG mIsCompiled = true; #endif
--- a/content/xbl/src/nsXBLProtoImplMethod.h +++ b/content/xbl/src/nsXBLProtoImplMethod.h @@ -175,14 +175,15 @@ public: virtual nsresult InstallMember(nsIScriptContext* aContext, nsIContent* aBoundElement, void* aScriptObject, void* aTargetClassObject, const nsCString& aClassStr) { return NS_OK; } + using nsXBLProtoImplMethod::Write; nsresult Write(nsIScriptContext* aContext, nsIObjectOutputStream* aStream, XBLBindingSerializeDetails aType); }; #endif // nsXBLProtoImplMethod_h__
--- a/content/xbl/src/nsXBLProtoImplProperty.cpp +++ b/content/xbl/src/nsXBLProtoImplProperty.cpp @@ -355,34 +355,33 @@ nsXBLProtoImplProperty::Trace(TraceCallb } } nsresult nsXBLProtoImplProperty::Read(nsIScriptContext* aContext, nsIObjectInputStream* aStream, XBLBindingSerializeDetails aType) { - nsresult rv; - void* scriptObject; - if (aType == XBLBinding_Serialize_GetterProperty || aType == XBLBinding_Serialize_GetterSetterProperty) { - rv = XBL_DeserializeFunction(aContext, aStream, this, &scriptObject); + JSObject* getterObject; + nsresult rv = XBL_DeserializeFunction(aContext, aStream, &getterObject); NS_ENSURE_SUCCESS(rv, rv); - mJSGetterObject = (JSObject *)scriptObject; + mJSGetterObject = getterObject; mJSAttributes |= JSPROP_GETTER | JSPROP_SHARED; } if (aType == XBLBinding_Serialize_SetterProperty || aType == XBLBinding_Serialize_GetterSetterProperty) { - rv = XBL_DeserializeFunction(aContext, aStream, this, &scriptObject); + JSObject* setterObject; + nsresult rv = XBL_DeserializeFunction(aContext, aStream, &setterObject); NS_ENSURE_SUCCESS(rv, rv); - mJSSetterObject = (JSObject *)scriptObject; + mJSSetterObject = setterObject; mJSAttributes |= JSPROP_SETTER | JSPROP_SHARED; } #ifdef DEBUG mIsCompiled = true; #endif return NS_OK;
--- a/content/xbl/src/nsXBLPrototypeBinding.cpp +++ b/content/xbl/src/nsXBLPrototypeBinding.cpp @@ -73,22 +73,21 @@ #include "nsIScriptContext.h" #include "nsIScriptError.h" #include "nsIStyleRuleProcessor.h" #include "nsXBLResourceLoader.h" #include "mozilla/dom/Element.h" -using namespace mozilla; - #ifdef MOZ_XUL #include "nsXULElement.h" #endif +using namespace mozilla; using namespace mozilla::dom; // Helper Classes ===================================================================== // Internal helper class for managing our IID table. class nsIIDKey : public nsHashKey { public: nsIID mKey; @@ -864,17 +863,17 @@ nsXBLPrototypeBinding::GetImmediateChild return nsnull; } nsresult nsXBLPrototypeBinding::InitClass(const nsCString& aClassName, JSContext * aContext, JSObject * aGlobal, JSObject * aScriptObject, - void ** aClassObject) + JSObject** aClassObject) { NS_ENSURE_ARG_POINTER(aClassObject); *aClassObject = nsnull; return nsXBLBinding::DoInitJSClass(aContext, aGlobal, aScriptObject, aClassName, this, aClassObject); } @@ -1899,19 +1898,17 @@ nsXBLPrototypeBinding::ReadContentNode(n } rv = prototype->SetAttrAt(i, val, documentURI); NS_ENSURE_SUCCESS(rv, rv); } } else { #endif - nsCOMPtr<nsINodeInfo> ni = nodeInfo; - NS_NewElement(getter_AddRefs(content), nodeInfo->NamespaceID(), - ni.forget(), mozilla::dom::NOT_FROM_PARSER); + NS_NewElement(getter_AddRefs(content), nodeInfo.forget(), NOT_FROM_PARSER); for (PRUint32 i = 0; i < attrCount; i++) { rv = ReadNamespace(aStream, namespaceID); NS_ENSURE_SUCCESS(rv, rv); nsAutoString prefix, name, val; rv = aStream->ReadString(prefix); NS_ENSURE_SUCCESS(rv, rv);
--- a/content/xbl/src/nsXBLPrototypeBinding.h +++ b/content/xbl/src/nsXBLPrototypeBinding.h @@ -150,17 +150,17 @@ public: } const nsCString& ClassName() const { return mImplementation ? mImplementation->mClassName : EmptyCString(); } nsresult InitClass(const nsCString& aClassName, JSContext * aContext, JSObject * aGlobal, JSObject * aScriptObject, - void ** aClassObject); + JSObject** aClassObject); nsresult ConstructInterfaceTable(const nsAString& aImpls); void SetImplementation(nsXBLProtoImpl* aImpl) { mImplementation = aImpl; } nsresult InstallImplementation(nsIContent* aBoundElement); bool HasImplementation() const { return mImplementation != nsnull; } void AttributeChanged(nsIAtom* aAttribute, PRInt32 aNameSpaceID,
--- a/content/xbl/src/nsXBLSerialize.cpp +++ b/content/xbl/src/nsXBLSerialize.cpp @@ -10,17 +10,17 @@ * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is - * Mozilla Corporation. + * the Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), @@ -40,84 +40,75 @@ #include "nsContentUtils.h" #include "jsxdrapi.h" nsresult XBL_SerializeFunction(nsIScriptContext* aContext, nsIObjectOutputStream* aStream, JSObject* aFunctionObject) { - nsresult rv; - - JSContext* cx = (JSContext*) aContext->GetNativeContext(); + JSContext* cx = aContext->GetNativeContext(); JSXDRState *xdr = ::JS_XDRNewMem(cx, JSXDR_ENCODE); if (!xdr) return NS_ERROR_OUT_OF_MEMORY; - xdr->userdata = (void*) aStream; - - jsval funval = OBJECT_TO_JSVAL(aFunctionObject); + xdr->userdata = static_cast<void*>(aStream); JSAutoRequest ar(cx); - if (! ::JS_XDRFunctionObject(xdr, &aFunctionObject)) { + nsresult rv; + if (!JS_XDRFunctionObject(xdr, &aFunctionObject)) { rv = NS_ERROR_FAILURE; } else { uint32 size; const char* data = reinterpret_cast<const char*> - (::JS_XDRMemGetData(xdr, &size)); + (JS_XDRMemGetData(xdr, &size)); NS_ASSERTION(data, "no decoded JSXDRState data!"); rv = aStream->Write32(size); if (NS_SUCCEEDED(rv)) rv = aStream->WriteBytes(data, size); } - ::JS_XDRDestroy(xdr); + JS_XDRDestroy(xdr); return rv; } // static nsresult XBL_DeserializeFunction(nsIScriptContext* aContext, nsIObjectInputStream* aStream, - void* aHolder, - void **aScriptObject) + JSObject** aFunctionObject) { - *aScriptObject = nsnull; - - JSObject* functionObject = nsnull; + *aFunctionObject = nsnull; PRUint32 size; nsresult rv = aStream->Read32(&size); if (NS_FAILED(rv)) return rv; char* data; rv = aStream->ReadBytes(size, &data); if (NS_FAILED(rv)) return rv; - JSContext* cx = (JSContext*) aContext->GetNativeContext(); - JSXDRState *xdr = ::JS_XDRNewMem(cx, JSXDR_DECODE); + JSContext* cx = aContext->GetNativeContext(); + JSXDRState *xdr = JS_XDRNewMem(cx, JSXDR_DECODE); if (!xdr) { rv = NS_ERROR_OUT_OF_MEMORY; } else { - xdr->userdata = (void*) aStream; + xdr->userdata = static_cast<void*>(aStream); JSAutoRequest ar(cx); - ::JS_XDRMemSetData(xdr, data, size); + JS_XDRMemSetData(xdr, data, size); - if (! ::JS_XDRFunctionObject(xdr, &functionObject)) { + if (!JS_XDRFunctionObject(xdr, aFunctionObject)) { rv = NS_ERROR_FAILURE; } uint32 junk; - data = (char*) ::JS_XDRMemGetData(xdr, &junk); - ::JS_XDRMemSetData(xdr, NULL, 0); - ::JS_XDRDestroy(xdr); + data = static_cast<char*>(JS_XDRMemGetData(xdr, &junk)); + JS_XDRMemSetData(xdr, NULL, 0); + JS_XDRDestroy(xdr); } nsMemory::Free(data); NS_ENSURE_SUCCESS(rv, rv); - - *aScriptObject = functionObject; - return rv; }
--- a/content/xbl/src/nsXBLSerialize.h +++ b/content/xbl/src/nsXBLSerialize.h @@ -10,17 +10,17 @@ * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is - * Mozilla Corporation. + * the Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), @@ -108,12 +108,11 @@ PR_STATIC_ASSERT(XBLBinding_Serialize_Cu nsresult XBL_SerializeFunction(nsIScriptContext* aContext, nsIObjectOutputStream* aStream, JSObject* aFunctionObject); nsresult XBL_DeserializeFunction(nsIScriptContext* aContext, nsIObjectInputStream* aStream, - void* aHolder, - void **aScriptObject); + JSObject** aFunctionObject); #endif // nsXBLSerialize_h__
--- a/content/xml/document/src/nsXMLContentSink.cpp +++ b/content/xml/document/src/nsXMLContentSink.cpp @@ -492,18 +492,17 @@ nsXMLContentSink::CreateElement(const PR NS_ASSERTION(aNodeInfo, "can't create element without nodeinfo"); *aResult = nsnull; *aAppendContent = true; nsresult rv = NS_OK; nsCOMPtr<nsINodeInfo> ni = aNodeInfo; nsCOMPtr<nsIContent> content; - rv = NS_NewElement(getter_AddRefs(content), aNodeInfo->NamespaceID(), - ni.forget(), aFromParser); + rv = NS_NewElement(getter_AddRefs(content), ni.forget(), aFromParser); NS_ENSURE_SUCCESS(rv, rv); if (aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML) || aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_SVG) ) { nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(content); sele->SetScriptLineNumber(aLineNumber); sele->SetCreatorParser(mParser); @@ -581,53 +580,49 @@ nsXMLContentSink::CloseElement(nsIConten mInMonolithicContainer--; } if (!nodeInfo->NamespaceEquals(kNameSpaceID_XHTML) && !nodeInfo->NamespaceEquals(kNameSpaceID_SVG)) { return NS_OK; } - nsresult rv = NS_OK; - if (nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML) || nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_SVG) ) { mConstrainSize = true; + nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent); if (mPreventScriptExecution) { - nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent); - NS_ASSERTION(sele, "script did QI correctly!"); sele->PreventExecution(); - return rv; + return NS_OK; } // Now tell the script that it's ready to go. This may execute the script - // or return NS_ERROR_HTMLPARSER_BLOCK. Or neither if the script doesn't - // need executing. - rv = aContent->DoneAddingChildren(true); + // or return true, or neither if the script doesn't need executing. + bool block = sele->AttemptToExecute(); // If the act of insertion evaluated the script, we're fine. // Else, block the parser till the script has loaded. - if (rv == NS_ERROR_HTMLPARSER_BLOCK) { - nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent); + if (block) { mScriptElements.AppendObject(sele); } // If the parser got blocked, make sure to return the appropriate rv. // I'm not sure if this is actually needed or not. if (mParser && !mParser->IsParserEnabled()) { // XXX The HTML sink doesn't call BlockParser here, why do we? mParser->BlockParser(); - rv = NS_ERROR_HTMLPARSER_BLOCK; + block = true; } - return rv; + return block ? NS_ERROR_HTMLPARSER_BLOCK : NS_OK; } + nsresult rv = NS_OK; if (nodeInfo->Equals(nsGkAtoms::meta, kNameSpaceID_XHTML) && // Need to check here to make sure this meta tag does not set // mPrettyPrintXML to false when we have a special root! (!mPrettyPrintXML || !mPrettyPrintHasSpecialRoot)) { rv = ProcessMETATag(aContent); } else if (nodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML) || nodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_XHTML) ||
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp +++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp @@ -58,16 +58,17 @@ #include "nsINameSpaceManager.h" #include "nsCSSStyleSheet.h" #include "txStringUtils.h" #include "txURIUtils.h" #include "nsIHTMLDocument.h" #include "nsIStyleSheetLinkingElement.h" #include "nsIDocumentTransformer.h" #include "mozilla/css/Loader.h" +#include "mozilla/dom/Element.h" #include "nsICharsetAlias.h" #include "nsIHTMLContentSink.h" #include "nsContentUtils.h" #include "txXMLUtils.h" #include "nsContentSink.h" #include "nsINode.h" #include "nsContentCreatorFunctions.h" #include "txError.h" @@ -298,46 +299,44 @@ txMozillaXMLOutput::endElement() --mTreeDepth; nsresult rv = closePrevious(true); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(mCurrentNode->IsElement(), "borked mCurrentNode"); NS_ENSURE_TRUE(mCurrentNode->IsElement(), NS_ERROR_UNEXPECTED); - nsIContent* element = static_cast<nsIContent*> - (static_cast<nsINode*> - (mCurrentNode)); + Element* element = mCurrentNode->AsElement(); // Handle html-elements if (!mNoFixup) { if (element->IsHTML()) { rv = endHTMLElement(element); NS_ENSURE_SUCCESS(rv, rv); } // Handle elements that are different when parser-created PRInt32 ns = element->GetNameSpaceID(); nsIAtom* localName = element->Tag(); - if ((ns == kNameSpaceID_XHTML && (localName == nsGkAtoms::script || - localName == nsGkAtoms::title || + if ((ns == kNameSpaceID_XHTML && (localName == nsGkAtoms::title || localName == nsGkAtoms::object || localName == nsGkAtoms::applet || localName == nsGkAtoms::select || localName == nsGkAtoms::textarea)) || - (ns == kNameSpaceID_SVG && (localName == nsGkAtoms::script || - localName == nsGkAtoms::title))) { - - rv = element->DoneAddingChildren(true); - + (ns == kNameSpaceID_SVG && localName == nsGkAtoms::title)) { + element->DoneAddingChildren(true); + } else if ((ns == kNameSpaceID_XHTML || ns == kNameSpaceID_SVG) && + localName == nsGkAtoms::script) { + nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(element); + NS_ABORT_IF_FALSE(sele, "script elements need to implement nsIScriptElement"); + bool block = sele->AttemptToExecute(); // If the act of insertion evaluated the script, we're fine. // Else, add this script element to the array of loading scripts. - if (rv == NS_ERROR_HTMLPARSER_BLOCK) { - nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(element); + if (block) { rv = mNotifier->AddScriptElement(sele); NS_ENSURE_SUCCESS(rv, rv); } } else if (ns == kNameSpaceID_XHTML && (localName == nsGkAtoms::input || localName == nsGkAtoms::button || localName == nsGkAtoms::menuitem)) { element->DoneCreatingElement(); @@ -551,22 +550,22 @@ txMozillaXMLOutput::startElementInternal if (!mCurrentNodeStack.AppendObject(mCurrentNode)) { return NS_ERROR_OUT_OF_MEMORY; } mTableState = NORMAL; mOpenedElementIsHTML = false; // Create the element - nsCOMPtr<nsINodeInfo> ni; - ni = mNodeInfoManager->GetNodeInfo(aLocalName, aPrefix, aNsID, - nsIDOMNode::ELEMENT_NODE); + nsCOMPtr<nsINodeInfo> ni = + mNodeInfoManager->GetNodeInfo(aLocalName, aPrefix, aNsID, + nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY); - NS_NewElement(getter_AddRefs(mOpenedElement), aNsID, ni.forget(), + NS_NewElement(getter_AddRefs(mOpenedElement), ni.forget(), mCreatingNewDocument ? FROM_PARSER_XSLT : FROM_PARSER_FRAGMENT); // Set up the element and adjust state if (!mNoFixup) { if (aNsID == kNameSpaceID_XHTML) { mOpenedElementIsHTML = (mOutputFormat.mMethod == eHTMLOutput); rv = startHTMLElement(mOpenedElement, mOpenedElementIsHTML);
--- a/content/xtf/src/nsXTFElementWrapper.cpp +++ b/content/xtf/src/nsXTFElementWrapper.cpp @@ -513,23 +513,21 @@ nsXTFElementWrapper::GetAttrCount() cons void nsXTFElementWrapper::BeginAddingChildren() { if (mNotificationMask & nsIXTFElement::NOTIFY_BEGIN_ADDING_CHILDREN) GetXTFElement()->BeginAddingChildren(); } -nsresult +void nsXTFElementWrapper::DoneAddingChildren(bool aHaveNotified) { if (mNotificationMask & nsIXTFElement::NOTIFY_DONE_ADDING_CHILDREN) GetXTFElement()->DoneAddingChildren(); - - return NS_OK; } already_AddRefed<nsINodeInfo> nsXTFElementWrapper::GetExistingAttrNameFromQName(const nsAString& aStr) const { nsINodeInfo* nodeInfo = nsXTFElementWrapperBase::GetExistingAttrNameFromQName(aStr).get(); // Maybe this attribute is handled by our inner element:
--- a/content/xtf/src/nsXTFElementWrapper.h +++ b/content/xtf/src/nsXTFElementWrapper.h @@ -106,17 +106,17 @@ public: bool aNotify); const nsAttrName* GetAttrNameAt(PRUint32 aIndex) const; PRUint32 GetAttrCount() const; virtual already_AddRefed<nsINodeInfo> GetExistingAttrNameFromQName(const nsAString& aStr) const; virtual nsEventStates IntrinsicState() const; virtual void BeginAddingChildren(); - virtual nsresult DoneAddingChildren(bool aHaveNotified); + virtual void DoneAddingChildren(bool aHaveNotified); virtual nsIAtom *GetClassAttributeName() const; virtual const nsAttrValue* DoGetClasses() const; virtual void PerformAccesskey(bool aKeyCausesActivation, bool aIsTrustedEvent); // nsIDOMElement specializations:
--- a/content/xul/content/src/nsXULContextMenuBuilder.cpp +++ b/content/xul/content/src/nsXULContextMenuBuilder.cpp @@ -34,16 +34,18 @@ * * ***** END LICENSE BLOCK ***** */ #include "nsContentCreatorFunctions.h" #include "nsIDOMHTMLElement.h" #include "nsIDOMHTMLMenuItemElement.h" #include "nsXULContextMenuBuilder.h" +using namespace mozilla; +using namespace mozilla::dom; nsXULContextMenuBuilder::nsXULContextMenuBuilder() : mCurrentGeneratedItemId(0) { } nsXULContextMenuBuilder::~nsXULContextMenuBuilder() { @@ -242,18 +244,17 @@ nsXULContextMenuBuilder::CreateElement(n nsIContent** aResult) { *aResult = nsnull; nsCOMPtr<nsINodeInfo> nodeInfo = mDocument->NodeInfoManager()->GetNodeInfo( aTag, nsnull, kNameSpaceID_XUL, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = NS_NewElement(aResult, kNameSpaceID_XUL, nodeInfo.forget(), - mozilla::dom::NOT_FROM_PARSER); + nsresult rv = NS_NewElement(aResult, nodeInfo.forget(), NOT_FROM_PARSER); if (NS_FAILED(rv)) { return rv; } nsAutoString generateditemid; if (aHTMLElement) { mElements.AppendObject(aHTMLElement);
--- a/content/xul/content/src/nsXULElement.cpp +++ b/content/xul/content/src/nsXULElement.cpp @@ -3136,17 +3136,16 @@ nsXULPrototypeScript::Compile(const PRUn nsCAutoString urlspec; nsContentUtils::GetWrapperSafeScriptFilename(aDocument, aURI, urlspec); // Ok, compile it to create a prototype script object! nsScriptObjectHolder newScriptObject(context); rv = context->CompileScript(aText, aTextLength, - nsnull, // Use the enclosing document's principal // XXX is this right? or should we use the // protodoc's? // If we start using the protodoc's, make sure // the DowngradePrincipalIfNeeded stuff in // nsXULDocument::OnStreamComplete still works! aDocument->NodePrincipal(), urlspec.get(),
--- a/content/xul/document/src/nsXULDocument.cpp +++ b/content/xul/document/src/nsXULDocument.cpp @@ -3698,19 +3698,18 @@ nsXULDocument::CreateElementFromPrototyp // for this node. nsCOMPtr<nsINodeInfo> newNodeInfo; newNodeInfo = mNodeInfoManager->GetNodeInfo(aPrototype->mNodeInfo->NameAtom(), aPrototype->mNodeInfo->GetPrefixAtom(), aPrototype->mNodeInfo->NamespaceID(), nsIDOMNode::ELEMENT_NODE); if (!newNodeInfo) return NS_ERROR_OUT_OF_MEMORY; nsCOMPtr<nsIContent> content; - PRInt32 ns = newNodeInfo->NamespaceID(); nsCOMPtr<nsINodeInfo> xtfNi = newNodeInfo; - rv = NS_NewElement(getter_AddRefs(content), ns, newNodeInfo.forget(), + rv = NS_NewElement(getter_AddRefs(content), newNodeInfo.forget(), NOT_FROM_PARSER); if (NS_FAILED(rv)) return rv; result = content->AsElement(); #ifdef MOZ_XTF if (result && xtfNi->NamespaceID() > kNameSpaceID_LastBuiltin) {
--- a/content/xul/document/src/nsXULPrototypeDocument.cpp +++ b/content/xul/document/src/nsXULPrototypeDocument.cpp @@ -718,18 +718,17 @@ nsXULPDGlobalObject::EnsureScriptEnviron } NS_ASSERTION(!mJSObject, "Have global without context?"); nsCOMPtr<nsIScriptRuntime> languageRuntime; nsresult rv = NS_GetScriptRuntimeByID(nsIProgrammingLanguage::JAVASCRIPT, getter_AddRefs(languageRuntime)); NS_ENSURE_SUCCESS(rv, NS_OK); - nsCOMPtr<nsIScriptContext> ctxNew; - rv = languageRuntime->CreateContext(getter_AddRefs(ctxNew)); + nsCOMPtr<nsIScriptContext> ctxNew = languageRuntime->CreateContext(); // We have to setup a special global object. We do this then // attach it as the global for this context. Then, ::SetScriptContext // will re-fetch the global and set it up in our language globals array. { JSContext *cx = ctxNew->GetNativeContext(); JSAutoRequest ar(cx); nsIPrincipal *principal = GetPrincipal();
--- a/content/xul/templates/src/nsXULContentBuilder.cpp +++ b/content/xul/templates/src/nsXULContentBuilder.cpp @@ -1394,30 +1394,27 @@ nsXULContentBuilder::CreateElement(PRInt nsIAtom* aTag, nsIContent** aResult) { nsCOMPtr<nsIDocument> doc = mRoot->GetDocument(); NS_ASSERTION(doc != nsnull, "not initialized"); if (! doc) return NS_ERROR_NOT_INITIALIZED; - nsresult rv; nsCOMPtr<nsIContent> result; + nsCOMPtr<nsINodeInfo> nodeInfo = + doc->NodeInfoManager()->GetNodeInfo(aTag, nsnull, aNameSpaceID, + nsIDOMNode::ELEMENT_NODE); - nsCOMPtr<nsINodeInfo> nodeInfo; - nodeInfo = doc->NodeInfoManager()->GetNodeInfo(aTag, nsnull, aNameSpaceID, - nsIDOMNode::ELEMENT_NODE); - - rv = NS_NewElement(getter_AddRefs(result), aNameSpaceID, nodeInfo.forget(), - NOT_FROM_PARSER); + nsresult rv = NS_NewElement(getter_AddRefs(result), nodeInfo.forget(), + NOT_FROM_PARSER); if (NS_FAILED(rv)) return rv; - *aResult = result; - NS_ADDREF(*aResult); + result.forget(aResult); return NS_OK; } nsresult nsXULContentBuilder::SetContainerAttrs(nsIContent *aElement, nsIXULTemplateResult* aResult, bool aIgnoreNonContainers, bool aNotify)
--- a/docshell/base/Makefile.in +++ b/docshell/base/Makefile.in @@ -114,11 +114,10 @@ CPPSRCS = \ FORCE_STATIC_LIB = 1 include $(topsrcdir)/config/rules.mk LOCAL_INCLUDES += \ -I$(srcdir)/../shistory/src \ -I$(topsrcdir)/dom/base \ -I$(topsrcdir)/layout/base \ - -I$(topsrcdir)/js/xpconnect/src \ -I$(topsrcdir)/xpcom/ds \ $(NULL)
--- a/docshell/base/nsDocShell.cpp +++ b/docshell/base/nsDocShell.cpp @@ -660,16 +660,21 @@ DispatchPings(nsIContent *content, nsIUR info.referrer = referrer; ForEachPing(content, SendPing, &info); } static nsDOMPerformanceNavigationType ConvertLoadTypeToNavigationType(PRUint32 aLoadType) { + // Not initialized, assume it's normal load. + if (aLoadType == 0) { + aLoadType = LOAD_NORMAL; + } + nsDOMPerformanceNavigationType result = nsIDOMPerformanceNavigation::TYPE_RESERVED; switch (aLoadType) { case LOAD_NORMAL: case LOAD_NORMAL_EXTERNAL: case LOAD_NORMAL_BYPASS_CACHE: case LOAD_NORMAL_BYPASS_PROXY: case LOAD_NORMAL_BYPASS_PROXY_AND_CACHE: case LOAD_NORMAL_REPLACE: @@ -5869,22 +5874,17 @@ nsDocShell::OnStateChange(nsIWebProgress if ((~aStateFlags & (STATE_START | STATE_IS_NETWORK)) == 0) { // Save timing statistics. nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest)); nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); nsCAutoString aURI; uri->GetAsciiSpec(aURI); - // If load type is not set, this is not a 'normal' load. - // No need to collect timing. - if (mLoadType == 0) { - mTiming = nsnull; - } - else if (this == aProgress){ + if (this == aProgress){ rv = MaybeInitTiming(); if (mTiming) { mTiming->NotifyFetchStart(uri, ConvertLoadTypeToNavigationType(mLoadType)); } } nsCOMPtr<nsIWyciwygChannel> wcwgChannel(do_QueryInterface(aRequest)); nsCOMPtr<nsIWebProgress> webProgress =
--- a/docshell/test/Makefile.in +++ b/docshell/test/Makefile.in @@ -119,16 +119,17 @@ include $(topsrcdir)/config/rules.mk test_bug669671.html \ file_bug669671.sjs \ test_bug675587.html \ test_bfcache_plus_hash.html \ test_bug680257.html \ file_bug680257.html \ test_bug691547.html \ bug691547_frame.html \ + test_bug694612.html \ $(NULL) ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa) _TEST_FILES += \ test_bug511449.html \ file_bug511449.html \ $(NULL) endif
new file mode 100644 --- /dev/null +++ b/docshell/test/test_bug694612.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=694612 +--> +<head> + <title>Test for Bug 694612</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=694612">Mozilla Bug 694612</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> +/** Test for Bug 694612 **/ +SimpleTest.waitForExplicitFinish(); +</script> +<object type="text/html" + data="data:text/html,<script>parent.isnot(performance, null, 'should have performance API in an <object>'); parent.SimpleTest.finish();</script>"> +</object> +</pre> +</body> +</html>
--- a/dom/base/nsDOMWindowUtils.cpp +++ b/dom/base/nsDOMWindowUtils.cpp @@ -1543,71 +1543,40 @@ nsDOMWindowUtils::LeaveModalStateWithWin NS_IMETHODIMP nsDOMWindowUtils::IsInModalState(bool *retval) { *retval = mWindow->IsInModalState(); return NS_OK; } NS_IMETHODIMP -nsDOMWindowUtils::GetParent() +nsDOMWindowUtils::GetParent(const JS::Value& aObject, + JSContext* aCx, + JS::Value* aParent) { // This wasn't privileged in the past, but better to expose less than more. if (!IsUniversalXPConnectCapable()) { return NS_ERROR_DOM_SECURITY_ERR; } - nsCOMPtr<nsIXPConnect> xpc = nsContentUtils::XPConnect(); - - // get the xpconnect native call context - nsAXPCNativeCallContext *cc = nsnull; - xpc->GetCurrentNativeCallContext(&cc); - if(!cc) - return NS_ERROR_FAILURE; - - // Get JSContext of current call - JSContext* cx; - nsresult rv = cc->GetJSContext(&cx); - if(NS_FAILED(rv) || !cx) - return NS_ERROR_FAILURE; - - // get place for return value - jsval *rval = nsnull; - rv = cc->GetRetValPtr(&rval); - if(NS_FAILED(rv) || !rval) - return NS_ERROR_FAILURE; + // First argument must be an object. + if (JSVAL_IS_PRIMITIVE(aObject)) { + return NS_ERROR_XPC_BAD_CONVERT_JS; + } - // get argc and argv and verify arg count - PRUint32 argc; - rv = cc->GetArgc(&argc); - if(NS_FAILED(rv)) - return NS_ERROR_FAILURE; - - if(argc != 1) - return NS_ERROR_XPC_NOT_ENOUGH_ARGS; - - jsval* argv; - rv = cc->GetArgvPtr(&argv); - if(NS_FAILED(rv) || !argv) - return NS_ERROR_FAILURE; - - // first argument must be an object - if(JSVAL_IS_PRIMITIVE(argv[0])) - return NS_ERROR_XPC_BAD_CONVERT_JS; - - JSObject *parent = JS_GetParent(cx, JSVAL_TO_OBJECT(argv[0])); - *rval = OBJECT_TO_JSVAL(parent); + JSObject* parent = JS_GetParent(aCx, JSVAL_TO_OBJECT(aObject)); + *aParent = OBJECT_TO_JSVAL(parent); // Outerize if necessary. if (parent) { - if (JSObjectOp outerize = js::GetObjectClass(parent)->ext.outerObject) - *rval = OBJECT_TO_JSVAL(outerize(cx, parent)); + if (JSObjectOp outerize = js::GetObjectClass(parent)->ext.outerObject) { + *aParent = OBJECT_TO_JSVAL(outerize(aCx, parent)); + } } - cc->SetReturnValueWasSet(true); return NS_OK; } NS_IMETHODIMP nsDOMWindowUtils::GetOuterWindowID(PRUint64 *aWindowID) { NS_ASSERTION(mWindow->IsOuterWindow(), "How did that happen?"); *aWindowID = mWindow->WindowID();
--- a/dom/base/nsGlobalWindow.cpp +++ b/dom/base/nsGlobalWindow.cpp @@ -1553,20 +1553,17 @@ nsGlobalWindow::EnsureScriptEnvironment( NS_ASSERTION(!GetCurrentInnerWindowInternal(), "mJSObject is null, but we have an inner window?"); nsCOMPtr<nsIScriptRuntime> scriptRuntime; nsresult rv = NS_GetScriptRuntimeByID(aLangID, getter_AddRefs(scriptRuntime)); NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr<nsIScriptContext> context; - rv = scriptRuntime->CreateContext(getter_AddRefs(context)); - NS_ENSURE_SUCCESS(rv, rv); - + nsCOMPtr<nsIScriptContext> context = scriptRuntime->CreateContext(); return SetScriptContext(aLangID, context); } nsIScriptContext * nsGlobalWindow::GetScriptContext(PRUint32 lang) { NS_ASSERTION(lang == nsIProgrammingLanguage::JAVASCRIPT, "We don't support this language ID");
--- a/dom/base/nsIScriptContext.h +++ b/dom/base/nsIScriptContext.h @@ -69,18 +69,18 @@ public: virtual nsIScriptObjectPrincipal* GetObjectPrincipal() = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIScriptContextPrincipal, NS_ISCRIPTCONTEXTPRINCIPAL_IID) #define NS_ISCRIPTCONTEXT_IID \ -{ 0x2e583bf4, 0x3c1f, 0x432d, \ - { 0x82, 0x83, 0x8d, 0xee, 0x7e, 0xcc, 0xc8, 0x8b } } +{ 0x164ea909, 0x5cee, 0x4e20, \ + { 0x9f, 0xed, 0x43, 0x13, 0xab, 0xac, 0x1c, 0xd3 } } /* This MUST match JSVERSION_DEFAULT. This version stuff if we don't know what language we have is a little silly... */ #define SCRIPTVERSION_DEFAULT JSVERSION_DEFAULT /** * It is used by the application to initialize a runtime and run scripts. * A script runtime would implement this interface. @@ -116,47 +116,42 @@ public: JSObject* aScopeObject, nsIPrincipal *aPrincipal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, nsAString *aRetValue, bool* aIsUndefined) = 0; - // Note JS bigotry remains here - 'void *aRetValue' is assumed to be a - // jsval. This must move to JSObject before it can be made agnostic. virtual nsresult EvaluateStringWithValue(const nsAString& aScript, - void *aScopeObject, + JSObject* aScopeObject, nsIPrincipal *aPrincipal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, - void* aRetValue, + JS::Value* aRetValue, bool* aIsUndefined) = 0; /** * Compile a script. * * @param aText a PRUnichar buffer containing script source * @param aTextLength number of characters in aText - * @param aScopeObject an object telling the scope in which to execute, - * or nsnull to use a default scope * @param aPrincipal the principal that produced the script * @param aURL the URL or filename for error messages * @param aLineNo the starting line number of the script for error messages * @param aVersion the script language version to use when executing * @param aScriptObject an executable object that's the result of compiling * the script. * * @return NS_OK if the script source was valid and got compiled. * **/ virtual nsresult CompileScript(const PRUnichar* aText, PRInt32 aTextLength, - void* aScopeObject, nsIPrincipal* aPrincipal, const char* aURL, PRUint32 aLineNo, PRUint32 aVersion, nsScriptObjectHolder &aScriptObject) = 0; /** * Execute a precompiled script object.
--- a/dom/base/nsIScriptRuntime.h +++ b/dom/base/nsIScriptRuntime.h @@ -34,20 +34,19 @@ * * ***** END LICENSE BLOCK ***** */ #ifndef nsIScriptRuntime_h__ #define nsIScriptRuntime_h__ #include "nsIScriptContext.h" -// {47032A4D-0C22-4125-94B7-864A4B744335} #define NS_ISCRIPTRUNTIME_IID \ -{ 0x47032a4d, 0xc22, 0x4125, { 0x94, 0xb7, 0x86, 0x4a, 0x4b, 0x74, 0x43, 0x35 } } - +{ 0x2c8d774e, 0xb52a, 0x43ec, \ + { 0x8e, 0xbc, 0x82, 0x75, 0xb9, 0x34, 0x20, 0x57 } } /** * A singleton language environment for an application. Responsible for * initializing and cleaning up the global language environment, and a factory * for language contexts */ class nsIScriptRuntime : public nsISupports { @@ -61,17 +60,17 @@ public: /* Parses a "version string" for the language into a bit-mask used by * the language implementation. If the specified version is not supported * an error should be returned. If the specified version is blank, a default * version should be assumed */ virtual nsresult ParseVersion(const nsString &aVersionStr, PRUint32 *verFlags) = 0; /* Factory for a new context for this language */ - virtual nsresult CreateContext(nsIScriptContext **ret) = 0; + virtual already_AddRefed<nsIScriptContext> CreateContext() = 0; /* Memory managment for script objects returned from various * nsIScriptContext methods. These are identical to those in * nsIScriptContext, but are useful when a script context is not known. */ virtual nsresult DropScriptObject(void *object) = 0; virtual nsresult HoldScriptObject(void *object) = 0; };
--- a/dom/base/nsJSEnvironment.cpp +++ b/dom/base/nsJSEnvironment.cpp @@ -1191,46 +1191,46 @@ nsJSContext::GetCCRefcnt() nsrefcnt refcnt = mRefCnt.get(); if (NS_LIKELY(mContext)) refcnt += mContext->outstandingRequests; return refcnt; } nsresult nsJSContext::EvaluateStringWithValue(const nsAString& aScript, - void *aScopeObject, + JSObject* aScopeObject, nsIPrincipal *aPrincipal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, - void* aRetValue, + JS::Value* aRetValue, bool* aIsUndefined) { NS_TIME_FUNCTION_MIN_FMT(1.0, "%s (line %d) (url: %s, line: %d)", MOZ_FUNCTION_NAME, __LINE__, aURL, aLineNo); + NS_ABORT_IF_FALSE(aScopeObject, + "Shouldn't call EvaluateStringWithValue with null scope object."); + NS_ENSURE_TRUE(mIsInitialized, NS_ERROR_NOT_INITIALIZED); if (!mScriptsEnabled) { if (aIsUndefined) { *aIsUndefined = true; } return NS_OK; } - nsresult rv; - if (!aScopeObject) - aScopeObject = ::JS_GetGlobalObject(mContext); - // Safety first: get an object representing the script's principals, i.e., // the entities who signed this script, or the fully-qualified-domain-name // or "codebase" from which it was loaded. JSPrincipals *jsprin; nsIPrincipal *principal = aPrincipal; + nsresult rv; if (!aPrincipal) { nsIScriptGlobalObject *global = GetGlobalObject(); if (!global) return NS_ERROR_FAILURE; nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal = do_QueryInterface(global, &rv); if (NS_FAILED(rv)) return NS_ERROR_FAILURE; @@ -1272,28 +1272,28 @@ nsJSContext::EvaluateStringWithValue(con // SecurityManager said "ok", but don't compile if aVersion is unknown. // Since the caller is responsible for parsing the version strings, we just // check it isn't JSVERSION_UNKNOWN. if (ok && ((JSVersion)aVersion) != JSVERSION_UNKNOWN) { JSAutoRequest ar(mContext); JSAutoEnterCompartment ac; - if (!ac.enter(mContext, (JSObject *)aScopeObject)) { + if (!ac.enter(mContext, aScopeObject)) { JSPRINCIPALS_DROP(mContext, jsprin); stack->Pop(nsnull); return NS_ERROR_FAILURE; } ++mExecuteDepth; ok = ::JS_EvaluateUCScriptForPrincipalsVersion(mContext, - (JSObject *)aScopeObject, + aScopeObject, jsprin, - (jschar*)PromiseFlatString(aScript).get(), + static_cast<const jschar*>(PromiseFlatString(aScript).get()), aScript.Length(), aURL, aLineNo, &val, JSVersion(aVersion)); --mExecuteDepth; @@ -1310,17 +1310,17 @@ nsJSContext::EvaluateStringWithValue(con JSPRINCIPALS_DROP(mContext, jsprin); // If all went well, convert val to a string (XXXbe unless undefined?). if (ok) { if (aIsUndefined) { *aIsUndefined = JSVAL_IS_VOID(val); } - *static_cast<jsval*>(aRetValue) = val; + *aRetValue = val; // XXX - nsScriptObjectHolder should be used once this method moves to // the new world order. However, use of 'jsval' appears to make this // tricky... } else { if (aIsUndefined) { *aIsUndefined = true; } @@ -1540,56 +1540,53 @@ nsJSContext::EvaluateString(const nsAStr ScriptEvaluated(true); return rv; } nsresult nsJSContext::CompileScript(const PRUnichar* aText, PRInt32 aTextLength, - void *aScopeObject, nsIPrincipal *aPrincipal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, nsScriptObjectHolder &aScriptObject) { NS_ENSURE_TRUE(mIsInitialized, NS_ERROR_NOT_INITIALIZED); - nsresult rv; NS_ENSURE_ARG_POINTER(aPrincipal); - if (!aScopeObject) - aScopeObject = ::JS_GetGlobalObject(mContext); + JSObject* scopeObject = ::JS_GetGlobalObject(mContext); JSPrincipals *jsprin; aPrincipal->GetJSPrincipals(mContext, &jsprin); // From here on, we must JSPRINCIPALS_DROP(jsprin) before returning... bool ok = false; - rv = sSecurityManager->CanExecuteScripts(mContext, aPrincipal, &ok); + nsresult rv = sSecurityManager->CanExecuteScripts(mContext, aPrincipal, &ok); if (NS_FAILED(rv)) { JSPRINCIPALS_DROP(mContext, jsprin); return NS_ERROR_FAILURE; } aScriptObject.drop(); // ensure old object not used on failure... // SecurityManager said "ok", but don't compile if aVersion is unknown. // Since the caller is responsible for parsing the version strings, we just // check it isn't JSVERSION_UNKNOWN. if (ok && ((JSVersion)aVersion) != JSVERSION_UNKNOWN) { JSAutoRequest ar(mContext); JSScript* script = ::JS_CompileUCScriptForPrincipalsVersion(mContext, - (JSObject *)aScopeObject, + scopeObject, jsprin, - (jschar*) aText, + static_cast<const jschar*>(aText), aTextLength, aURL, aLineNo, JSVersion(aVersion)); if (script) { NS_ASSERTION(aScriptObject.getScriptTypeID()==JAVASCRIPT, "Expecting JS script object holder"); rv = aScriptObject.set(script); @@ -3507,25 +3504,21 @@ nsJSContext::ReportPendingException() NS_INTERFACE_MAP_BEGIN(nsJSRuntime) NS_INTERFACE_MAP_ENTRY(nsIScriptRuntime) NS_INTERFACE_MAP_END NS_IMPL_ADDREF(nsJSRuntime) NS_IMPL_RELEASE(nsJSRuntime) -nsresult -nsJSRuntime::CreateContext(nsIScriptContext **aContext) +already_AddRefed<nsIScriptContext> +nsJSRuntime::CreateContext() { - nsCOMPtr<nsIScriptContext> scriptContext; - - *aContext = new nsJSContext(sRuntime); - NS_ENSURE_TRUE(*aContext, NS_ERROR_OUT_OF_MEMORY); - NS_ADDREF(*aContext); - return NS_OK; + nsCOMPtr<nsIScriptContext> scriptContext = new nsJSContext(sRuntime); + return scriptContext.forget(); } nsresult nsJSRuntime::ParseVersion(const nsString &aVersionStr, PRUint32 *flags) { NS_PRECONDITION(flags, "Null flags param?"); JSVersion jsVersion = JSVERSION_UNKNOWN; if (aVersionStr.Length() != 3 || aVersionStr[0] != '1' || aVersionStr[1] != '.')
--- a/dom/base/nsJSEnvironment.h +++ b/dom/base/nsJSEnvironment.h @@ -76,27 +76,26 @@ public: JSObject* aScopeObject, nsIPrincipal *principal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, nsAString *aRetValue, bool* aIsUndefined); virtual nsresult EvaluateStringWithValue(const nsAString& aScript, - void *aScopeObject, - nsIPrincipal *aPrincipal, - const char *aURL, - PRUint32 aLineNo, - PRUint32 aVersion, - void* aRetValue, - bool* aIsUndefined); + JSObject* aScopeObject, + nsIPrincipal* aPrincipal, + const char* aURL, + PRUint32 aLineNo, + PRUint32 aVersion, + JS::Value* aRetValue, + bool* aIsUndefined); virtual nsresult CompileScript(const PRUnichar* aText, PRInt32 aTextLength, - void *aScopeObject, nsIPrincipal *principal, const char *aURL, PRUint32 aLineNo, PRUint32 aVersion, nsScriptObjectHolder &aScriptObject); virtual nsresult ExecuteScript(JSScript* aScriptObject, JSObject* aScopeObject, nsAString* aRetValue, @@ -308,20 +307,20 @@ public: // let people who can see us use our runtime for convenience. static JSRuntime *sRuntime; public: // nsISupports NS_DECL_ISUPPORTS virtual PRUint32 GetScriptTypeID() { - return nsIProgrammingLanguage::JAVASCRIPT; + return nsIProgrammingLanguage::JAVASCRIPT; } - virtual nsresult CreateContext(nsIScriptContext **ret); + virtual already_AddRefed<nsIScriptContext> CreateContext(); virtual nsresult ParseVersion(const nsString &aVersionStr, PRUint32 *flags); virtual nsresult DropScriptObject(void *object); virtual nsresult HoldScriptObject(void *object); static void Startup(); static void Shutdown();
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl +++ b/dom/interfaces/base/nsIDOMWindowUtils.idl @@ -63,17 +63,17 @@ interface nsIDOMElement; interface nsIDOMHTMLCanvasElement; interface nsIDOMEvent; interface nsITransferable; interface nsIQueryContentEventResult; interface nsIDOMWindow; interface nsIDOMFile; interface nsIFile; -[scriptable, uuid(910484d7-219c-4c72-b999-7a7e9c954646)] +[scriptable, uuid(c5cf91b3-0b89-4417-b13c-5540ba6ebde8)] interface nsIDOMWindowUtils : nsISupports { /** * Image animation mode of the window. When this attribute's value * is changed, the implementation should set all images in the window * to the given value. That is, when set to kDontAnimMode, all images * will stop animating. The attribute's value must be one of the * animationMode values from imgIContainer. @@ -769,17 +769,17 @@ interface nsIDOMWindowUtils : nsISupport in AString aPropertyName); /** * Returns the parent of obj. * * @param obj The JavaScript object whose parent is to be gotten. * @return the parent. */ - void getParent(/* obj */); + [implicit_jscontext] jsval getParent(in jsval obj); /** * Get the id of the outer window of this window. This will never throw. */ readonly attribute unsigned long long outerWindowID; /** * Get the id of the current inner window of this window. If there
--- a/dom/plugins/base/nsNPAPIPlugin.cpp +++ b/dom/plugins/base/nsNPAPIPlugin.cpp @@ -1641,16 +1641,18 @@ bool NP_CALLBACK JSObject *obj = nsNPObjWrapper::GetNewOrUsed(npp, cx, npobj); if (!obj) { return false; } obj = JS_ObjectToInnerObject(cx, obj); + NS_ABORT_IF_FALSE(obj, + "JS_ObjectToInnerObject should never return null with non-null input."); // Root obj and the rval (below). jsval vec[] = { OBJECT_TO_JSVAL(obj), JSVAL_NULL }; js::AutoArrayRooter tvr(cx, ArrayLength(vec), vec); jsval *rval = &vec[1]; if (result) { // Initialize the out param to void
--- a/dom/plugins/ipc/PluginUtilsOSX.h +++ b/dom/plugins/ipc/PluginUtilsOSX.h @@ -89,18 +89,17 @@ public: bool InitFrontSurface(size_t aWidth, size_t aHeight, AllowOfflineRendererEnum aAllowOfflineRenderer); void Render(); void SwapSurfaces(); void ClearFrontSurface(); void ClearBackSurface(); private: void *mCALayer; - nsRefPtr<nsCARenderer> mFrontRenderer; - nsRefPtr<nsCARenderer> mBackRenderer; + nsRefPtr<nsCARenderer> mCARenderer; nsRefPtr<nsIOSurface> mFrontSurface; nsRefPtr<nsIOSurface> mBackSurface; }; } // namespace PluginUtilsOSX } // namespace plugins } // namespace mozilla
--- a/dom/plugins/ipc/PluginUtilsOSX.mm +++ b/dom/plugins/ipc/PluginUtilsOSX.mm @@ -340,75 +340,74 @@ void nsDoubleBufferCARenderer::SetCALaye bool nsDoubleBufferCARenderer::InitFrontSurface(size_t aWidth, size_t aHeight, AllowOfflineRendererEnum aAllowOfflineRenderer) { if (!mCALayer) { return false; } mFrontSurface = nsIOSurface::CreateIOSurface(aWidth, aHeight); if (!mFrontSurface) { - return false; - } - - mFrontRenderer = new nsCARenderer(); - if (!mFrontRenderer) { - mFrontSurface = nsnull; - return false; - } - - nsRefPtr<nsIOSurface> ioSurface = nsIOSurface::LookupSurface(mFrontSurface->GetIOSurfaceID()); - if (!ioSurface) { - mFrontRenderer = nsnull; - mFrontSurface = nsnull; + mCARenderer = nsnull; return false; } - mFrontRenderer->AttachIOSurface(ioSurface); + if (!mCARenderer) { + mCARenderer = new nsCARenderer(); + if (!mCARenderer) { + mFrontSurface = nsnull; + return false; + } - nsresult result = mFrontRenderer->SetupRenderer(mCALayer, - ioSurface->GetWidth(), - ioSurface->GetHeight(), + mCARenderer->AttachIOSurface(mFrontSurface); + + nsresult result = mCARenderer->SetupRenderer(mCALayer, + mFrontSurface->GetWidth(), + mFrontSurface->GetHeight(), aAllowOfflineRenderer); - return result == NS_OK; + if (result != NS_OK) { + mCARenderer = nsnull; + mFrontSurface = nsnull; + return false; + } + } else { + mCARenderer->AttachIOSurface(mFrontSurface); + } + + return true; } void nsDoubleBufferCARenderer::Render() { - if (!HasFrontSurface()) { + if (!HasFrontSurface() || !mCARenderer) { return; } - mFrontRenderer->Render(GetFrontSurfaceWidth(), GetFrontSurfaceHeight(), nsnull); + mCARenderer->Render(GetFrontSurfaceWidth(), GetFrontSurfaceHeight(), nsnull); } void nsDoubleBufferCARenderer::SwapSurfaces() { - if (mFrontRenderer) { - mFrontRenderer->DettachCALayer(); - } - - nsRefPtr<nsCARenderer> prevFrontRenderer = mFrontRenderer; nsRefPtr<nsIOSurface> prevFrontSurface = mFrontSurface; - - mFrontRenderer = mBackRenderer; mFrontSurface = mBackSurface; - - mBackRenderer = prevFrontRenderer; mBackSurface = prevFrontSurface; - if (mFrontRenderer) { - mFrontRenderer->AttachCALayer(mCALayer); + if (mFrontSurface) { + mCARenderer->AttachIOSurface(mFrontSurface); } } void nsDoubleBufferCARenderer::ClearFrontSurface() { - mFrontRenderer = nsnull; mFrontSurface = nsnull; + if (!mFrontSurface && !mBackSurface) { + mCARenderer = nsnull; + } } void nsDoubleBufferCARenderer::ClearBackSurface() { - mBackRenderer = nsnull; mBackSurface = nsnull; + if (!mFrontSurface && !mBackSurface) { + mCARenderer = nsnull; + } } } //PluginUtilsOSX } //plugins } //mozilla
--- a/editor/libeditor/html/nsHTMLEditor.cpp +++ b/editor/libeditor/html/nsHTMLEditor.cpp @@ -96,16 +96,18 @@ #include "nsEditorUtils.h" #include "nsWSRunObject.h" #include "nsGkAtoms.h" #include "nsIFrame.h" #include "nsIParserService.h" #include "mozilla/dom/Element.h" +using namespace mozilla; + // Some utilities to handle annoying overloading of "A" tag for link and named anchor static char hrefText[] = "href"; static char anchorTxt[] = "anchor"; static char namedanchorText[] = "namedanchor"; nsIRangeUtils* nsHTMLEditor::sRangeHelper; #define IsLinkTag(s) (s.EqualsIgnoreCase(hrefText)) @@ -3713,67 +3715,55 @@ nsHTMLEditor::GetURLForStyleSheet(nsCSSS * nsIEditorMailSupport methods */ NS_IMETHODIMP nsHTMLEditor::GetEmbeddedObjects(nsISupportsArray** aNodeList) { NS_ENSURE_TRUE(aNodeList, NS_ERROR_NULL_POINTER); - nsresult res; - - res = NS_NewISupportsArray(aNodeList); - NS_ENSURE_SUCCESS(res, res); + nsresult rv = NS_NewISupportsArray(aNodeList); + NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(*aNodeList, NS_ERROR_NULL_POINTER); nsCOMPtr<nsIContentIterator> iter = - do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &res); + do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv); NS_ENSURE_TRUE(iter, NS_ERROR_NULL_POINTER); - if ((NS_SUCCEEDED(res))) - { - nsCOMPtr<nsIDOMDocument> domdoc; - nsEditor::GetDocument(getter_AddRefs(domdoc)); - NS_ENSURE_TRUE(domdoc, NS_ERROR_UNEXPECTED); - - nsCOMPtr<nsIDocument> doc (do_QueryInterface(domdoc)); - NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED); - - iter->Init(doc->GetRootElement()); - - // loop through the content iterator for each content node - while (!iter->IsDone()) - { - nsCOMPtr<nsIDOMNode> node (do_QueryInterface(iter->GetCurrentNode())); - if (node) - { - nsAutoString tagName; - node->GetNodeName(tagName); - ToLowerCase(tagName); - - // See if it's an image or an embed and also include all links. - // Let mail decide which link to send or not - if (tagName.EqualsLiteral("img") || tagName.EqualsLiteral("embed") || - tagName.EqualsLiteral("a")) - (*aNodeList)->AppendElement(node); - else if (tagName.EqualsLiteral("body")) - { - nsCOMPtr<nsIDOMElement> element = do_QueryInterface(node); - if (element) - { - bool hasBackground = false; - if (NS_SUCCEEDED(element->HasAttribute(NS_LITERAL_STRING("background"), &hasBackground)) && hasBackground) - (*aNodeList)->AppendElement(node); - } - } + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr<nsIDOMDocument> domdoc; + nsEditor::GetDocument(getter_AddRefs(domdoc)); + NS_ENSURE_TRUE(domdoc, NS_ERROR_UNEXPECTED); + + nsCOMPtr<nsIDocument> doc = do_QueryInterface(domdoc); + NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED); + + iter->Init(doc->GetRootElement()); + + // Loop through the content iterator for each content node. + while (!iter->IsDone()) { + nsINode* node = iter->GetCurrentNode(); + if (node->IsElement()) { + dom::Element* element = node->AsElement(); + + // See if it's an image or an embed and also include all links. + // Let mail decide which link to send or not + if (element->IsHTML(nsGkAtoms::img) || + element->IsHTML(nsGkAtoms::embed) || + element->IsHTML(nsGkAtoms::a) || + (element->IsHTML(nsGkAtoms::body) && + element->HasAttr(kNameSpaceID_None, nsGkAtoms::background))) { + nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(node); + (*aNodeList)->AppendElement(domNode); } - iter->Next(); } - } - - return res; + iter->Next(); + } + + return rv; } NS_IMETHODIMP nsHTMLEditor::DeleteNode(nsIDOMNode * aNode) { // do nothing if the node is read-only if (!IsModifiableNode(aNode) && !IsMozEditorBogusNode(aNode)) { return NS_ERROR_FAILURE;
deleted file mode 100644 --- a/gfx/2d/Blur.cpp +++ /dev/null @@ -1,526 +0,0 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Mozilla gfx. - * - * The Initial Developer of the Original Code is Mozilla Foundation. - * Portions created by the Initial Developer are Copyright (C) 2011 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#include <algorithm> -#include <math.h> - -#include "CheckedInt.h" -#include "mozilla/Util.h" - -#include "mozilla/gfx/Blur.h" - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -using namespace std; - -namespace mozilla { -namespace gfx { - -/** - * Box blur involves looking at one pixel, and setting its value to the average - * of its neighbouring pixels. - * @param aInput The input buffer. - * @param aOutput The output buffer. - * @param aLeftLobe The number of pixels to blend on the left. - * @param aRightLobe The number of pixels to blend on the right. - * @param aWidth The number of columns in the buffers. - * @param aRows The number of rows in the buffers. - * @param aSkipRect An area to skip blurring in. - * XXX shouldn't we pass stride in separately here? - */ -static void -BoxBlurHorizontal(unsigned char* aInput, - unsigned char* aOutput, - int32_t aLeftLobe, - int32_t aRightLobe, - int32_t aWidth, - int32_t aRows, - const IntRect& aSkipRect) -{ - MOZ_ASSERT(aWidth > 0); - - int32_t boxSize = aLeftLobe + aRightLobe + 1; - bool skipRectCoversWholeRow = 0 >= aSkipRect.x && - aWidth <= aSkipRect.XMost(); - - for (int32_t y = 0; y < aRows; y++) { - // Check whether the skip rect intersects this row. If the skip - // rect covers the whole surface in this row, we can avoid - // this row entirely (and any others along the skip rect). - bool inSkipRectY = y >= aSkipRect.y && - y < aSkipRect.YMost(); - if (inSkipRectY && skipRectCoversWholeRow) { - y = aSkipRect.YMost() - 1; - continue; - } - - int32_t alphaSum = 0; - for (int32_t i = 0; i < boxSize; i++) { - int32_t pos = i - aLeftLobe; - // See assertion above; if aWidth is zero, then we would have no - // valid position to clamp to. - pos = max(pos, 0); - pos = min(pos, aWidth - 1); - alphaSum += aInput[aWidth * y + pos]; - } - for (int32_t x = 0; x < aWidth; x++) { - // Check whether we are within the skip rect. If so, go - // to the next point outside the skip rect. - if (inSkipRectY && x >= aSkipRect.x && - x < aSkipRect.XMost()) { - x = aSkipRect.XMost(); - if (x >= aWidth) - break; - - // Recalculate the neighbouring alpha values for - // our new point on the surface. - alphaSum = 0; - for (int32_t i = 0; i < boxSize; i++) { - int32_t pos = x + i - aLeftLobe; - // See assertion above; if aWidth is zero, then we would have no - // valid position to clamp to. - pos = max(pos, 0); - pos = min(pos, aWidth - 1); - alphaSum += aInput[aWidth * y + pos]; - } - } - int32_t tmp = x - aLeftLobe; - int32_t last = max(tmp, 0); - int32_t next = min(tmp + boxSize, aWidth - 1); - - aOutput[aWidth * y + x] = alphaSum / boxSize; - - alphaSum += aInput[aWidth * y + next] - - aInput[aWidth * y + last]; - } - } -} - -/** - * Identical to BoxBlurHorizontal, except it blurs top and bottom instead of - * left and right. - * XXX shouldn't we pass stride in separately here? - */ -static void -BoxBlurVertical(unsigned char* aInput, - unsigned char* aOutput, - int32_t aTopLobe, - int32_t aBottomLobe, - int32_t aWidth, - int32_t aRows, - const IntRect& aSkipRect) -{ - MOZ_ASSERT(aRows > 0); - - int32_t boxSize = aTopLobe + aBottomLobe + 1; - bool skipRectCoversWholeColumn = 0 >= aSkipRect.y && - aRows <= aSkipRect.YMost(); - - for (int32_t x = 0; x < aWidth; x++) { - bool inSkipRectX = x >= aSkipRect.x && - x < aSkipRect.XMost(); - if (inSkipRectX && skipRectCoversWholeColumn) { - x = aSkipRect.XMost() - 1; - continue; - } - - int32_t alphaSum = 0; - for (int32_t i = 0; i < boxSize; i++) { - int32_t pos = i - aTopLobe; - // See assertion above; if aRows is zero, then we would have no - // valid position to clamp to. - pos = max(pos, 0); - pos = min(pos, aRows - 1); - alphaSum += aInput[aWidth * pos + x]; - } - for (int32_t y = 0; y < aRows; y++) { - if (inSkipRectX && y >= aSkipRect.y && - y < aSkipRect.YMost()) { - y = aSkipRect.YMost(); - if (y >= aRows) - break; - - alphaSum = 0; - for (int32_t i = 0; i < boxSize; i++) { - int32_t pos = y + i - aTopLobe; - // See assertion above; if aRows is zero, then we would have no - // valid position to clamp to. - pos = max(pos, 0); - pos = min(pos, aRows - 1); - alphaSum += aInput[aWidth * pos + x]; - } - } - int32_t tmp = y - aTopLobe; - int32_t last = max(tmp, 0); - int32_t next = min(tmp + boxSize, aRows - 1); - - aOutput[aWidth * y + x] = alphaSum/boxSize; - - alphaSum += aInput[aWidth * next + x] - - aInput[aWidth * last + x]; - } - } -} - -static void ComputeLobes(int32_t aRadius, int32_t aLobes[3][2]) -{ - int32_t major, minor, final; - - /* See http://www.w3.org/TR/SVG/filters.html#feGaussianBlur for - * some notes about approximating the Gaussian blur with box-blurs. - * The comments below are in the terminology of that page. - */ - int32_t z = aRadius / 3; - switch (aRadius % 3) { - case 0: - // aRadius = z*3; choose d = 2*z + 1 - major = minor = final = z; - break; - case 1: - // aRadius = z*3 + 1 - // This is a tricky case since there is no value of d which will - // yield a radius of exactly aRadius. If d is odd, i.e. d=2*k + 1 - // for some integer k, then the radius will be 3*k. If d is even, - // i.e. d=2*k, then the radius will be 3*k - 1. - // So we have to choose values that don't match the standard - // algorithm. - major = z + 1; - minor = final = z; - break; - case 2: - // aRadius = z*3 + 2; choose d = 2*z + 2 - major = final = z + 1; - minor = z; - break; - default: - // Mathematical impossibility! - MOZ_ASSERT(false); - major = minor = final = 0; - } - MOZ_ASSERT(major + minor + final == aRadius); - - aLobes[0][0] = major; - aLobes[0][1] = minor; - aLobes[1][0] = minor; - aLobes[1][1] = major; - aLobes[2][0] = final; - aLobes[2][1] = final; -} - -static void -SpreadHorizontal(unsigned char* aInput, - unsigned char* aOutput, - int32_t aRadius, - int32_t aWidth, - int32_t aRows, - int32_t aStride, - const IntRect& aSkipRect) -{ - if (aRadius == 0) { - memcpy(aOutput, aInput, aStride * aRows); - return; - } - - bool skipRectCoversWholeRow = 0 >= aSkipRect.x && - aWidth <= aSkipRect.XMost(); - for (int32_t y = 0; y < aRows; y++) { - // Check whether the skip rect intersects this row. If the skip - // rect covers the whole surface in this row, we can avoid - // this row entirely (and any others along the skip rect). - bool inSkipRectY = y >= aSkipRect.y && - y < aSkipRect.YMost(); - if (inSkipRectY && skipRectCoversWholeRow) { - y = aSkipRect.YMost() - 1; - continue; - } - - for (int32_t x = 0; x < aWidth; x++) { - // Check whether we are within the skip rect. If so, go - // to the next point outside the skip rect. - if (inSkipRectY && x >= aSkipRect.x && - x < aSkipRect.XMost()) { - x = aSkipRect.XMost(); - if (x >= aWidth) - break; - } - - int32_t sMin = max(x - aRadius, 0); - int32_t sMax = min(x + aRadius, aWidth - 1); - int32_t v = 0; - for (int32_t s = sMin; s <= sMax; ++s) { - v = max<int32_t>(v, aInput[aStride * y + s]); - } - aOutput[aStride * y + x] = v; - } - } -} - -static void -SpreadVertical(unsigned char* aInput, - unsigned char* aOutput, - int32_t aRadius, - int32_t aWidth, - int32_t aRows, - int32_t aStride, - const IntRect& aSkipRect) -{ - if (aRadius == 0) { - memcpy(aOutput, aInput, aStride * aRows); - return; - } - - bool skipRectCoversWholeColumn = 0 >= aSkipRect.y && - aRows <= aSkipRect.YMost(); - for (int32_t x = 0; x < aWidth; x++) { - bool inSkipRectX = x >= aSkipRect.x && - x < aSkipRect.XMost(); - if (inSkipRectX && skipRectCoversWholeColumn) { - x = aSkipRect.XMost() - 1; - continue; - } - - for (int32_t y = 0; y < aRows; y++) { - // Check whether we are within the skip rect. If so, go - // to the next point outside the skip rect. - if (inSkipRectX && y >= aSkipRect.y && - y < aSkipRect.YMost()) { - y = aSkipRect.YMost(); - if (y >= aRows) - break; - } - - int32_t sMin = max(y - aRadius, 0); - int32_t sMax = min(y + aRadius, aRows - 1); - int32_t v = 0; - for (int32_t s = sMin; s <= sMax; ++s) { - v = max<int32_t>(v, aInput[aStride * s + x]); - } - aOutput[aStride * y + x] = v; - } - } -} - -static CheckedInt<int32_t> -RoundUpToMultipleOf4(int32_t aVal) -{ - CheckedInt<int32_t> val(aVal); - - val += 3; - val /= 4; - val *= 4; - - return val; -} - -AlphaBoxBlur::AlphaBoxBlur(const Rect& aRect, - const IntSize& aSpreadRadius, - const IntSize& aBlurRadius, - const Rect* aDirtyRect, - const Rect* aSkipRect) - : mSpreadRadius(aSpreadRadius), - mBlurRadius(aBlurRadius), - mData(NULL) -{ - Rect rect(aRect); - rect.Inflate(Size(aBlurRadius + aSpreadRadius)); - rect.RoundOut(); - - if (aDirtyRect) { - // If we get passed a dirty rect from layout, we can minimize the - // shadow size and make painting faster. - mHasDirtyRect = true; - mDirtyRect = *aDirtyRect; - Rect requiredBlurArea = mDirtyRect.Intersect(rect); - requiredBlurArea.Inflate(Size(aBlurRadius + aSpreadRadius)); - rect = requiredBlurArea.Intersect(rect); - } else { - mHasDirtyRect = false; - } - - if (rect.IsEmpty()) { - return; - } - - if (aSkipRect) { - // If we get passed a skip rect, we can lower the amount of - // blurring/spreading we need to do. We convert it to IntRect to avoid - // expensive int<->float conversions if we were to use Rect instead. - Rect skipRect = *aSkipRect; - skipRect.RoundIn(); - skipRect.Deflate(Size(aBlurRadius + aSpreadRadius)); - mSkipRect = IntRect(skipRect.x, skipRect.y, skipRect.width, skipRect.height); - - IntRect shadowIntRect(rect.x, rect.y, rect.width, rect.height); - mSkipRect.IntersectRect(mSkipRect, shadowIntRect); - - if (mSkipRect.IsEqualInterior(shadowIntRect)) - return; - - mSkipRect -= shadowIntRect.TopLeft(); - } else { - mSkipRect = IntRect(0, 0, 0, 0); - } - - mRect = IntRect(rect.x, rect.y, rect.width, rect.height); - - CheckedInt<int32_t> stride = RoundUpToMultipleOf4(mRect.width); - if (stride.valid()) { - mStride = stride.value(); - - CheckedInt<int32_t> size = CheckedInt<int32_t>(mStride) * mRect.height * - sizeof(unsigned char); - if (size.valid()) { - mData = static_cast<unsigned char*>(malloc(size.value())); - memset(mData, 0, size.value()); - } - } -} - -AlphaBoxBlur::~AlphaBoxBlur() -{ - free(mData); -} - -unsigned char* -AlphaBoxBlur::GetData() -{ - return mData; -} - -IntSize -AlphaBoxBlur::GetSize() -{ - IntSize size(mRect.width, mRect.height); - return size; -} - -int32_t -AlphaBoxBlur::GetStride() -{ - return mStride; -} - -IntRect -AlphaBoxBlur::GetRect() -{ - return mRect; -} - -Rect* -AlphaBoxBlur::GetDirtyRect() -{ - if (mHasDirtyRect) { - return &mDirtyRect; - } - - return NULL; -} - -void -AlphaBoxBlur::Blur() -{ - if (!mData) { - return; - } - - // no need to do all this if not blurring or spreading - if (mBlurRadius != IntSize(0,0) || mSpreadRadius != IntSize(0,0)) { - int32_t stride = GetStride(); - - // No need to use CheckedInt here - we have validated it in the constructor. - size_t szB = stride * GetSize().height * sizeof(unsigned char); - unsigned char* tmpData = static_cast<unsigned char*>(malloc(szB)); - if (!tmpData) - return; // OOM - - memset(tmpData, 0, szB); - - if (mSpreadRadius.width > 0 || mSpreadRadius.height > 0) { - SpreadHorizontal(mData, tmpData, mSpreadRadius.width, GetSize().width, GetSize().height, stride, mSkipRect); - SpreadVertical(tmpData, mData, mSpreadRadius.height, GetSize().width, GetSize().height, stride, mSkipRect); - } - - if (mBlurRadius.width > 0) { - int32_t lobes[3][2]; - ComputeLobes(mBlurRadius.width, lobes); - BoxBlurHorizontal(mData, tmpData, lobes[0][0], lobes[0][1], stride, GetSize().height, mSkipRect); - BoxBlurHorizontal(tmpData, mData, lobes[1][0], lobes[1][1], stride, GetSize().height, mSkipRect); - BoxBlurHorizontal(mData, tmpData, lobes[2][0], lobes[2][1], stride, GetSize().height, mSkipRect); - } else { - memcpy(tmpData, mData, stride * GetSize().height); - } - - if (mBlurRadius.height > 0) { - int32_t lobes[3][2]; - ComputeLobes(mBlurRadius.height, lobes); - BoxBlurVertical(tmpData, mData, lobes[0][0], lobes[0][1], stride, GetSize().height, mSkipRect); - BoxBlurVertical(mData, tmpData, lobes[1][0], lobes[1][1], stride, GetSize().height, mSkipRect); - BoxBlurVertical(tmpData, mData, lobes[2][0], lobes[2][1], stride, GetSize().height, mSkipRect); - } else { - memcpy(mData, tmpData, stride * GetSize().height); - } - - free(tmpData); - } - -} - -/** - * Compute the box blur size (which we're calling the blur radius) from - * the standard deviation. - * - * Much of this, the 3 * sqrt(2 * pi) / 4, is the known value for - * approximating a Gaussian using box blurs. This yields quite a good - * approximation for a Gaussian. Then we multiply this by 1.5 since our - * code wants the radius of the entire triple-box-blur kernel instead of - * the diameter of an individual box blur. For more details, see: - * http://www.w3.org/TR/SVG11/filters.html#feGaussianBlurElement - * https://bugzilla.mozilla.org/show_bug.cgi?id=590039#c19 - */ -static const Float GAUSSIAN_SCALE_FACTOR = (3 * sqrt(2 * M_PI) / 4) * 1.5; - -IntSize -AlphaBoxBlur::CalculateBlurRadius(const Point& aStd) -{ - IntSize size(static_cast<int32_t>(floor(aStd.x * GAUSSIAN_SCALE_FACTOR + 0.5)), - static_cast<int32_t>(floor(aStd.y * GAUSSIAN_SCALE_FACTOR + 0.5))); - - return size; -} - -} -}
deleted file mode 100644 --- a/gfx/2d/Blur.h +++ /dev/null @@ -1,180 +0,0 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Mozilla gfx. - * - * The Initial Developer of the Original Code is Mozilla Foundation. - * Portions created by the Initial Developer are Copyright (C) 2011 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#include "mozilla/gfx/Rect.h" -#include "mozilla/gfx/Point.h" - -namespace mozilla { -namespace gfx { - -/** - * Implementation of a triple box blur approximation of a Gaussian blur. - * - * A Gaussian blur is good for blurring because, when done independently - * in the horizontal and vertical directions, it matches the result that - * would be obtained using a different (rotated) set of axes. A triple - * box blur is a very close approximation of a Gaussian. - * - * Creates an 8-bit alpha channel context for callers to draw in, - * spreads the contents of that context, and blurs the contents. - * - * A spread N makes each output pixel the maximum value of all source - * pixels within a square of side length 2N+1 centered on the output pixel. - * - * A temporary surface is created in the Init function. The caller then draws - * any desired content onto the context acquired through GetContext, and lastly - * calls Paint to apply the blurred content as an alpha mask. - */ -class AlphaBoxBlur -{ -public: - - /** Constructs a box blur and initializes the backing surface. - * - * @param aRect The coordinates of the surface to create in device units. - * - * @param aBlurRadius The blur radius in pixels. This is the radius of the - * entire (triple) kernel function. Each individual box blur has radius - * approximately 1/3 this value, or diameter approximately 2/3 this value. - * This parameter should nearly always be computed using CalculateBlurRadius, - * below. - * - * @param aDirtyRect A pointer to a dirty rect, measured in device units, if - * available. This will be used for optimizing the blur operation. It is - * safe to pass NULL here. - * - * @param aSkipRect A pointer to a rect, measured in device units, that - * represents an area where blurring is unnecessary and shouldn't be done for - * speed reasons. It is safe to pass NULL here. - */ - AlphaBoxBlur(const Rect& aRect, - const IntSize& aSpreadRadius, - const IntSize& aBlurRadius, - const Rect* aDirtyRect, - const Rect* aSkipRect); - - ~AlphaBoxBlur(); - - /** - * Return the pointer to memory allocated by the constructor for the 8-bit - * alpha surface you need to be blurred. After you draw to this surface, call - * Blur(), below, to have its contents blurred. - */ - unsigned char* GetData(); - - /** - * Return the size, in pixels, of the 8-bit alpha surface backed by the - * pointer returned by GetData(). - */ - IntSize GetSize(); - - /** - * Return the stride, in bytes, of the 8-bit alpha surface backed by the - * pointer returned by GetData(). - */ - int32_t GetStride(); - - /** - * Returns the device-space rectangle the 8-bit alpha surface covers. - */ - IntRect GetRect(); - - /** - * Return a pointer to a dirty rect, as passed in to the constructor, or NULL - * if none was passed in. - */ - Rect* GetDirtyRect(); - - /** - * Perform the blur in-place on the surface backed by the pointer returned by - * GetData(). - */ - void Blur(); - - /** - * Calculates a blur radius that, when used with box blur, approximates a - * Gaussian blur with the given standard deviation. The result of this - * function should be used as the aBlurRadius parameter to AlphaBoxBlur's - * constructor, above. - */ - static IntSize CalculateBlurRadius(const Point& aStandardDeviation); - -private: - - /** - * A rect indicating the area where blurring is unnecessary, and the blur - * algorithm should skip over it. - */ - IntRect mSkipRect; - - /** - * The device-space rectangle the the backing 8-bit alpha surface covers. - */ - IntRect mRect; - - /** - * A copy of the dirty rect passed to the constructor. This will only be valid if - * mHasDirtyRect is true. - */ - Rect mDirtyRect; - - /** - * The spread radius, in pixels. - */ - IntSize mSpreadRadius; - - /** - * The blur radius, in pixels. - */ - IntSize mBlurRadius; - - /** - * A pointer to the backing 8-bit alpha surface. - */ - unsigned char* mData; - - /** - * The stride of the data contained in mData. - */ - int32_t mStride; - - /** - * Whether mDirtyRect contains valid data. - */ - bool mHasDirtyRect; -}; - -} -}
--- a/gfx/2d/Makefile.in +++ b/gfx/2d/Makefile.in @@ -51,30 +51,28 @@ EXPORTS_NAMESPACES = mozilla/gfx EXPORTS_mozilla/gfx = \ 2D.h \ BasePoint.h \ BasePoint3D.h \ BasePoint4D.h \ BaseMargin.h \ BaseRect.h \ BaseSize.h \ - Blur.h \ PathHelpers.h \ Point.h \ Matrix.h \ Rect.h \ Types.h \ $(NULL) CPPSRCS = \ Factory.cpp \ Matrix.cpp \ DrawTargetCairo.cpp \ SourceSurfaceCairo.cpp \ - Blur.cpp \ $(NULL) DEFINES += -DMOZ_GFX -DUSE_CAIRO ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT)) CPPSRCS += \ SourceSurfaceSkia.cpp \
--- a/gfx/layers/basic/BasicLayers.cpp +++ b/gfx/layers/basic/BasicLayers.cpp @@ -38,16 +38,18 @@ #include "gfxSharedImageSurface.h" #include "mozilla/layers/PLayerChild.h" #include "mozilla/layers/PLayersChild.h" #include "mozilla/layers/PLayersParent.h" #include "mozilla/gfx/2D.h" +#include "mozilla/Types.h" + #include "ipc/ShadowLayerChild.h" #include "BasicLayers.h" #include "ImageLayers.h" #include "nsTArray.h" #include "nsGUIEvent.h" #include "gfxContext.h" @@ -2204,27 +2206,27 @@ public: virtual void SyncFrontBufferToBackBuffer(); private: BasicShadowLayerManager* BasicManager() { return static_cast<BasicShadowLayerManager*>(mManager); } - NS_OVERRIDE virtual void + virtual void PaintBuffer(gfxContext* aContext, const nsIntRegion& aRegionToDraw, const nsIntRegion& aExtendedRegionToDraw, const nsIntRegion& aRegionToInvalidate, bool aDidSelfCopy, LayerManager::DrawThebesLayerCallback aCallback, - void* aCallbackData); - - NS_OVERRIDE virtual already_AddRefed<gfxASurface> - CreateBuffer(Buffer::ContentType aType, const nsIntSize& aSize); + void* aCallbackData) MOZ_OVERRIDE; + + virtual already_AddRefed<gfxASurface> + CreateBuffer(Buffer::ContentType aType, const nsIntSize& aSize) MOZ_OVERRIDE; void DestroyBackBuffer() { if (IsSurfaceDescriptorValid(mBackBuffer)) { BasicManager()->ShadowLayerForwarder::DestroySharedSurface(&mBackBuffer); } }
--- a/gfx/ots/src/layout.cc +++ b/gfx/ots/src/layout.cc @@ -142,17 +142,17 @@ bool ParseFeatureTable(const uint8_t *da uint16_t offset_feature_params = 0; uint16_t lookup_count = 0; if (!subtable.ReadU16(&offset_feature_params) || !subtable.ReadU16(&lookup_count)) { return OTS_FAILURE(); } const unsigned feature_table_end = - 2 * static_cast<unsigned>(num_lookups) + 4; + 2 * static_cast<unsigned>(lookup_count) + 4; if (feature_table_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } // |offset_feature_params| is generally set to NULL. if (offset_feature_params != 0 && (offset_feature_params < feature_table_end || offset_feature_params >= length)) { return OTS_FAILURE();
--- a/gfx/qcms/transform.c +++ b/gfx/qcms/transform.c @@ -1073,17 +1073,18 @@ qcms_transform* qcms_transform_precacheL } } } //XXX: qcms_modular_transform_data may return either the src or dest buffer. If so it must not be free-ed if (src && lut != src) { free(src); - } else if (dest && lut != src) { + } + if (dest && lut != dest) { free(dest); } if (lut == NULL) { return NULL; } return transform; }