michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=2 sw=2 et tw=79: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * Base class for all element classes; this provides an implementation michael@0: * of DOM Core's nsIDOMElement, implements nsIContent, provides michael@0: * utility methods for subclasses, and so forth. michael@0: */ michael@0: michael@0: #include "mozilla/dom/ElementInlines.h" michael@0: michael@0: #include "mozilla/DebugOnly.h" michael@0: #include "mozilla/dom/Attr.h" michael@0: #include "nsDOMAttributeMap.h" michael@0: #include "nsIAtom.h" michael@0: #include "nsIContentInlines.h" michael@0: #include "nsINodeInfo.h" michael@0: #include "nsIDocumentInlines.h" michael@0: #include "nsIDOMNodeList.h" michael@0: #include "nsIDOMDocument.h" michael@0: #include "nsIContentIterator.h" michael@0: #include "nsFocusManager.h" michael@0: #include "nsILinkHandler.h" michael@0: #include "nsIScriptGlobalObject.h" michael@0: #include "nsIURL.h" michael@0: #include "nsNetUtil.h" michael@0: #include "nsIFrame.h" michael@0: #include "nsIAnonymousContentCreator.h" michael@0: #include "nsIPresShell.h" michael@0: #include "nsPresContext.h" michael@0: #include "nsStyleConsts.h" michael@0: #include "nsString.h" michael@0: #include "nsUnicharUtils.h" michael@0: #include "nsIDOMEvent.h" michael@0: #include "nsDOMCID.h" michael@0: #include "nsIServiceManager.h" michael@0: #include "nsIDOMCSSStyleDeclaration.h" michael@0: #include "nsDOMCSSAttrDeclaration.h" michael@0: #include "nsNameSpaceManager.h" michael@0: #include "nsContentList.h" michael@0: #include "nsDOMTokenList.h" michael@0: #include "nsXBLPrototypeBinding.h" michael@0: #include "nsError.h" michael@0: #include "nsDOMString.h" michael@0: #include "nsIScriptSecurityManager.h" michael@0: #include "nsIDOMMutationEvent.h" michael@0: #include "mozilla/AsyncEventDispatcher.h" michael@0: #include "mozilla/ContentEvents.h" michael@0: #include "mozilla/EventDispatcher.h" michael@0: #include "mozilla/EventListenerManager.h" michael@0: #include "mozilla/EventStateManager.h" michael@0: #include "mozilla/EventStates.h" michael@0: #include "mozilla/InternalMutationEvent.h" michael@0: #include "mozilla/MouseEvents.h" michael@0: #include "mozilla/TextEvents.h" michael@0: #include "nsNodeUtils.h" michael@0: #include "mozilla/dom/DirectionalityUtils.h" michael@0: #include "nsDocument.h" michael@0: #include "nsAttrValueOrString.h" michael@0: #include "nsAttrValueInlines.h" michael@0: #ifdef MOZ_XUL michael@0: #include "nsXULElement.h" michael@0: #endif /* MOZ_XUL */ michael@0: #include "nsFrameManager.h" michael@0: #include "nsFrameSelection.h" michael@0: #ifdef DEBUG michael@0: #include "nsRange.h" michael@0: #endif michael@0: michael@0: #include "nsBindingManager.h" michael@0: #include "nsXBLBinding.h" michael@0: #include "nsPIDOMWindow.h" michael@0: #include "nsPIBoxObject.h" michael@0: #include "mozilla/dom/DOMRect.h" michael@0: #include "nsSVGUtils.h" michael@0: #include "nsLayoutUtils.h" michael@0: #include "nsGkAtoms.h" michael@0: #include "nsContentUtils.h" michael@0: #include "ChildIterator.h" michael@0: michael@0: #include "nsIDOMEventListener.h" michael@0: #include "nsIWebNavigation.h" michael@0: #include "nsIBaseWindow.h" michael@0: #include "nsIWidget.h" michael@0: michael@0: #include "nsNodeInfoManager.h" michael@0: #include "nsICategoryManager.h" michael@0: #include "nsIDOMDocumentType.h" michael@0: #include "nsIDOMUserDataHandler.h" michael@0: #include "nsGenericHTMLElement.h" michael@0: #include "nsIEditor.h" michael@0: #include "nsIEditorIMESupport.h" michael@0: #include "nsContentCreatorFunctions.h" michael@0: #include "nsIControllers.h" michael@0: #include "nsView.h" michael@0: #include "nsViewManager.h" michael@0: #include "nsIScrollableFrame.h" michael@0: #include "mozilla/css/StyleRule.h" /* For nsCSSSelectorList */ michael@0: #include "nsCSSRuleProcessor.h" michael@0: #include "nsRuleProcessorData.h" michael@0: #include "nsTextNode.h" michael@0: michael@0: #ifdef MOZ_XUL michael@0: #include "nsIXULDocument.h" michael@0: #endif /* MOZ_XUL */ michael@0: michael@0: #include "nsCycleCollectionParticipant.h" michael@0: #include "nsCCUncollectableMarker.h" michael@0: michael@0: #include "mozAutoDocUpdate.h" michael@0: michael@0: #include "nsCSSParser.h" michael@0: #include "prprf.h" michael@0: #include "nsDOMMutationObserver.h" michael@0: #include "nsSVGFeatures.h" michael@0: #include "nsWrapperCacheInlines.h" michael@0: #include "xpcpublic.h" michael@0: #include "nsIScriptError.h" michael@0: #include "mozilla/Telemetry.h" michael@0: michael@0: #include "mozilla/CORSMode.h" michael@0: #include "mozilla/dom/ShadowRoot.h" michael@0: michael@0: #include "nsStyledElement.h" michael@0: #include "nsXBLService.h" michael@0: #include "nsITextControlElement.h" michael@0: #include "nsITextControlFrame.h" michael@0: #include "nsISupportsImpl.h" michael@0: #include "mozilla/dom/DocumentFragment.h" michael@0: #include "mozilla/IntegerPrintfMacros.h" michael@0: michael@0: using namespace mozilla; michael@0: using namespace mozilla::dom; michael@0: michael@0: NS_IMETHODIMP michael@0: Element::QueryInterface(REFNSIID aIID, void** aInstancePtr) michael@0: { michael@0: NS_ASSERTION(aInstancePtr, michael@0: "QueryInterface requires a non-NULL destination!"); michael@0: nsresult rv = FragmentOrElement::QueryInterface(aIID, aInstancePtr); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Give the binding manager a chance to get an interface for this element. michael@0: return OwnerDoc()->BindingManager()->GetBindingImplementation(this, aIID, michael@0: aInstancePtr); michael@0: } michael@0: michael@0: EventStates michael@0: Element::IntrinsicState() const michael@0: { michael@0: return IsEditable() ? NS_EVENT_STATE_MOZ_READWRITE : michael@0: NS_EVENT_STATE_MOZ_READONLY; michael@0: } michael@0: michael@0: void michael@0: Element::NotifyStateChange(EventStates aStates) michael@0: { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc) { michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: doc->ContentStateChanged(this, aStates); michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::UpdateLinkState(EventStates aState) michael@0: { michael@0: NS_ABORT_IF_FALSE(!aState.HasAtLeastOneOfStates(~(NS_EVENT_STATE_VISITED | michael@0: NS_EVENT_STATE_UNVISITED)), michael@0: "Unexpected link state bits"); michael@0: mState = michael@0: (mState & ~(NS_EVENT_STATE_VISITED | NS_EVENT_STATE_UNVISITED)) | michael@0: aState; michael@0: } michael@0: michael@0: void michael@0: Element::UpdateState(bool aNotify) michael@0: { michael@0: EventStates oldState = mState; michael@0: mState = IntrinsicState() | (oldState & ESM_MANAGED_STATES); michael@0: if (aNotify) { michael@0: EventStates changedStates = oldState ^ mState; michael@0: if (!changedStates.IsEmpty()) { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc) { michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: doc->ContentStateChanged(this, changedStates); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsIContent::UpdateEditableState(bool aNotify) michael@0: { michael@0: // Guaranteed to be non-element content michael@0: NS_ASSERTION(!IsElement(), "What happened here?"); michael@0: nsIContent *parent = GetParent(); michael@0: michael@0: // Skip over unknown native anonymous content to avoid setting a flag we michael@0: // can't clear later michael@0: bool isUnknownNativeAnon = false; michael@0: if (IsInNativeAnonymousSubtree()) { michael@0: isUnknownNativeAnon = true; michael@0: nsCOMPtr root = this; michael@0: while (root && !root->IsRootOfNativeAnonymousSubtree()) { michael@0: root = root->GetParent(); michael@0: } michael@0: // root should always be true here, but isn't -- bug 999416 michael@0: if (root) { michael@0: nsIFrame* rootFrame = root->GetPrimaryFrame(); michael@0: if (rootFrame) { michael@0: nsIFrame* parentFrame = rootFrame->GetParent(); michael@0: nsITextControlFrame* textCtrl = do_QueryFrame(parentFrame); michael@0: isUnknownNativeAnon = !textCtrl; michael@0: } michael@0: } michael@0: } michael@0: michael@0: SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE) && michael@0: !isUnknownNativeAnon); michael@0: } michael@0: michael@0: void michael@0: Element::UpdateEditableState(bool aNotify) michael@0: { michael@0: nsIContent *parent = GetParent(); michael@0: michael@0: SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE)); michael@0: if (aNotify) { michael@0: UpdateState(aNotify); michael@0: } else { michael@0: // Avoid calling UpdateState in this very common case, because michael@0: // this gets called for pretty much every single element on michael@0: // insertion into the document and UpdateState can be slow for michael@0: // some kinds of elements even when not notifying. michael@0: if (IsEditable()) { michael@0: RemoveStatesSilently(NS_EVENT_STATE_MOZ_READONLY); michael@0: AddStatesSilently(NS_EVENT_STATE_MOZ_READWRITE); michael@0: } else { michael@0: RemoveStatesSilently(NS_EVENT_STATE_MOZ_READWRITE); michael@0: AddStatesSilently(NS_EVENT_STATE_MOZ_READONLY); michael@0: } michael@0: } michael@0: } michael@0: michael@0: EventStates michael@0: Element::StyleStateFromLocks() const michael@0: { michael@0: EventStates locks = LockedStyleStates(); michael@0: EventStates state = mState | locks; michael@0: michael@0: if (locks.HasState(NS_EVENT_STATE_VISITED)) { michael@0: return state & ~NS_EVENT_STATE_UNVISITED; michael@0: } michael@0: if (locks.HasState(NS_EVENT_STATE_UNVISITED)) { michael@0: return state & ~NS_EVENT_STATE_VISITED; michael@0: } michael@0: return state; michael@0: } michael@0: michael@0: EventStates michael@0: Element::LockedStyleStates() const michael@0: { michael@0: EventStates* locks = michael@0: static_cast(GetProperty(nsGkAtoms::lockedStyleStates)); michael@0: if (locks) { michael@0: return *locks; michael@0: } michael@0: return EventStates(); michael@0: } michael@0: michael@0: void michael@0: Element::NotifyStyleStateChange(EventStates aStates) michael@0: { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc) { michael@0: nsIPresShell *presShell = doc->GetShell(); michael@0: if (presShell) { michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: presShell->ContentStateChanged(doc, this, aStates); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::LockStyleStates(EventStates aStates) michael@0: { michael@0: EventStates* locks = new EventStates(LockedStyleStates()); michael@0: michael@0: *locks |= aStates; michael@0: michael@0: if (aStates.HasState(NS_EVENT_STATE_VISITED)) { michael@0: *locks &= ~NS_EVENT_STATE_UNVISITED; michael@0: } michael@0: if (aStates.HasState(NS_EVENT_STATE_UNVISITED)) { michael@0: *locks &= ~NS_EVENT_STATE_VISITED; michael@0: } michael@0: michael@0: SetProperty(nsGkAtoms::lockedStyleStates, locks, michael@0: nsINode::DeleteProperty); michael@0: SetHasLockedStyleStates(); michael@0: michael@0: NotifyStyleStateChange(aStates); michael@0: } michael@0: michael@0: void michael@0: Element::UnlockStyleStates(EventStates aStates) michael@0: { michael@0: EventStates* locks = new EventStates(LockedStyleStates()); michael@0: michael@0: *locks &= ~aStates; michael@0: michael@0: if (locks->IsEmpty()) { michael@0: DeleteProperty(nsGkAtoms::lockedStyleStates); michael@0: ClearHasLockedStyleStates(); michael@0: delete locks; michael@0: } michael@0: else { michael@0: SetProperty(nsGkAtoms::lockedStyleStates, locks, michael@0: nsINode::DeleteProperty); michael@0: } michael@0: michael@0: NotifyStyleStateChange(aStates); michael@0: } michael@0: michael@0: void michael@0: Element::ClearStyleStateLocks() michael@0: { michael@0: EventStates locks = LockedStyleStates(); michael@0: michael@0: DeleteProperty(nsGkAtoms::lockedStyleStates); michael@0: ClearHasLockedStyleStates(); michael@0: michael@0: NotifyStyleStateChange(locks); michael@0: } michael@0: michael@0: bool michael@0: Element::GetBindingURL(nsIDocument *aDocument, css::URLValue **aResult) michael@0: { michael@0: // If we have a frame the frame has already loaded the binding. And michael@0: // otherwise, don't do anything else here unless we're dealing with michael@0: // XUL or an HTML element that may have a plugin-related overlay michael@0: // (i.e. object, embed, or applet). michael@0: bool isXULorPluginElement = (IsXUL() || michael@0: IsHTML(nsGkAtoms::object) || michael@0: IsHTML(nsGkAtoms::embed) || michael@0: IsHTML(nsGkAtoms::applet)); michael@0: nsIPresShell *shell = aDocument->GetShell(); michael@0: if (!shell || GetPrimaryFrame() || !isXULorPluginElement) { michael@0: *aResult = nullptr; michael@0: michael@0: return true; michael@0: } michael@0: michael@0: // Get the computed -moz-binding directly from the style context michael@0: nsPresContext *pctx = shell->GetPresContext(); michael@0: NS_ENSURE_TRUE(pctx, false); michael@0: michael@0: nsRefPtr sc = pctx->StyleSet()->ResolveStyleFor(this, michael@0: nullptr); michael@0: NS_ENSURE_TRUE(sc, false); michael@0: michael@0: *aResult = sc->StyleDisplay()->mBinding; michael@0: michael@0: return true; michael@0: } michael@0: michael@0: JSObject* michael@0: Element::WrapObject(JSContext *aCx) michael@0: { michael@0: JS::Rooted obj(aCx, nsINode::WrapObject(aCx)); michael@0: if (!obj) { michael@0: return nullptr; michael@0: } michael@0: michael@0: // Custom element prototype swizzling. michael@0: CustomElementData* data = GetCustomElementData(); michael@0: if (obj && data) { michael@0: // If this is a registered custom element then fix the prototype. michael@0: JSAutoCompartment ac(aCx, obj); michael@0: nsDocument* document = static_cast(OwnerDoc()); michael@0: JS::Rooted prototype(aCx); michael@0: document->GetCustomPrototype(NodeInfo()->NamespaceID(), data->mType, &prototype); michael@0: if (prototype) { michael@0: if (!JS_WrapObject(aCx, &prototype) || !JS_SetPrototype(aCx, obj, prototype)) { michael@0: dom::Throw(aCx, NS_ERROR_FAILURE); michael@0: return nullptr; michael@0: } michael@0: } michael@0: } michael@0: michael@0: nsIDocument* doc; michael@0: if (HasFlag(NODE_FORCE_XBL_BINDINGS)) { michael@0: doc = OwnerDoc(); michael@0: } michael@0: else { michael@0: doc = GetCurrentDoc(); michael@0: } michael@0: michael@0: if (!doc) { michael@0: // There's no baseclass that cares about this call so we just michael@0: // return here. michael@0: return obj; michael@0: } michael@0: michael@0: // We must ensure that the XBL Binding is installed before we hand michael@0: // back this object. michael@0: michael@0: if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR) && GetXBLBinding()) { michael@0: // There's already a binding for this element so nothing left to michael@0: // be done here. michael@0: michael@0: // In theory we could call ExecuteAttachedHandler here when it's safe to michael@0: // run script if we also removed the binding from the PAQ queue, but that michael@0: // seems like a scary change that would mosly just add more michael@0: // inconsistencies. michael@0: return obj; michael@0: } michael@0: michael@0: // Make sure the style context goes away _before_ we load the binding michael@0: // since that can destroy the relevant presshell. michael@0: mozilla::css::URLValue *bindingURL; michael@0: bool ok = GetBindingURL(doc, &bindingURL); michael@0: if (!ok) { michael@0: dom::Throw(aCx, NS_ERROR_FAILURE); michael@0: return nullptr; michael@0: } michael@0: michael@0: if (!bindingURL) { michael@0: // No binding, nothing left to do here. michael@0: return obj; michael@0: } michael@0: michael@0: nsCOMPtr uri = bindingURL->GetURI(); michael@0: nsCOMPtr principal = bindingURL->mOriginPrincipal; michael@0: michael@0: // We have a binding that must be installed. michael@0: bool dummy; michael@0: michael@0: nsXBLService* xblService = nsXBLService::GetInstance(); michael@0: if (!xblService) { michael@0: dom::Throw(aCx, NS_ERROR_NOT_AVAILABLE); michael@0: return nullptr; michael@0: } michael@0: michael@0: { michael@0: // Make a scope so that ~nsRefPtr can GC before returning obj. michael@0: nsRefPtr binding; michael@0: xblService->LoadBindings(this, uri, principal, getter_AddRefs(binding), &dummy); michael@0: michael@0: if (binding) { michael@0: if (nsContentUtils::IsSafeToRunScript()) { michael@0: binding->ExecuteAttachedHandler(); michael@0: } michael@0: else { michael@0: nsContentUtils::AddScriptRunner( michael@0: NS_NewRunnableMethod(binding, &nsXBLBinding::ExecuteAttachedHandler)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: return obj; michael@0: } michael@0: michael@0: nsDOMTokenList* michael@0: Element::GetClassList() michael@0: { michael@0: Element::nsDOMSlots *slots = DOMSlots(); michael@0: michael@0: if (!slots->mClassList) { michael@0: nsIAtom* classAttr = GetClassAttributeName(); michael@0: if (classAttr) { michael@0: slots->mClassList = new nsDOMTokenList(this, classAttr); michael@0: } michael@0: } michael@0: michael@0: return slots->mClassList; michael@0: } michael@0: michael@0: void michael@0: Element::GetClassList(nsISupports** aClassList) michael@0: { michael@0: NS_IF_ADDREF(*aClassList = GetClassList()); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetElementsByTagName(const nsAString& aLocalName) michael@0: { michael@0: return NS_GetContentList(this, kNameSpaceID_Unknown, aLocalName); michael@0: } michael@0: michael@0: void michael@0: Element::GetElementsByTagName(const nsAString& aLocalName, michael@0: nsIDOMHTMLCollection** aResult) michael@0: { michael@0: *aResult = GetElementsByTagName(aLocalName).take(); michael@0: } michael@0: michael@0: nsIFrame* michael@0: Element::GetStyledFrame() michael@0: { michael@0: nsIFrame *frame = GetPrimaryFrame(Flush_Layout); michael@0: return frame ? nsLayoutUtils::GetStyleFrame(frame) : nullptr; michael@0: } michael@0: michael@0: nsIScrollableFrame* michael@0: Element::GetScrollFrame(nsIFrame **aStyledFrame, bool aFlushLayout) michael@0: { michael@0: // it isn't clear what to return for SVG nodes, so just return nothing michael@0: if (IsSVG()) { michael@0: if (aStyledFrame) { michael@0: *aStyledFrame = nullptr; michael@0: } michael@0: return nullptr; michael@0: } michael@0: michael@0: // Inline version of GetStyledFrame to use Flush_None if needed. michael@0: nsIFrame* frame = GetPrimaryFrame(aFlushLayout ? Flush_Layout : Flush_None); michael@0: if (frame) { michael@0: frame = nsLayoutUtils::GetStyleFrame(frame); michael@0: } michael@0: michael@0: if (aStyledFrame) { michael@0: *aStyledFrame = frame; michael@0: } michael@0: if (!frame) { michael@0: return nullptr; michael@0: } michael@0: michael@0: // menu frames implement GetScrollTargetFrame but we don't want michael@0: // to use it here. Similar for comboboxes. michael@0: nsIAtom* type = frame->GetType(); michael@0: if (type != nsGkAtoms::menuFrame && type != nsGkAtoms::comboboxControlFrame) { michael@0: nsIScrollableFrame *scrollFrame = frame->GetScrollTargetFrame(); michael@0: if (scrollFrame) michael@0: return scrollFrame; michael@0: } michael@0: michael@0: nsIDocument* doc = OwnerDoc(); michael@0: bool quirksMode = doc->GetCompatibilityMode() == eCompatibility_NavQuirks; michael@0: Element* elementWithRootScrollInfo = michael@0: quirksMode ? doc->GetBodyElement() : doc->GetRootElement(); michael@0: if (this == elementWithRootScrollInfo) { michael@0: // In quirks mode, the scroll info for the body element should map to the michael@0: // root scrollable frame. michael@0: // In strict mode, the scroll info for the root element should map to the michael@0: // the root scrollable frame. michael@0: return frame->PresContext()->PresShell()->GetRootScrollFrameAsScrollable(); michael@0: } michael@0: michael@0: return nullptr; michael@0: } michael@0: michael@0: void michael@0: Element::ScrollIntoView(bool aTop) michael@0: { michael@0: nsIDocument *document = GetCurrentDoc(); michael@0: if (!document) { michael@0: return; michael@0: } michael@0: michael@0: // Get the presentation shell michael@0: nsCOMPtr presShell = document->GetShell(); michael@0: if (!presShell) { michael@0: return; michael@0: } michael@0: michael@0: int16_t vpercent = aTop ? nsIPresShell::SCROLL_TOP : michael@0: nsIPresShell::SCROLL_BOTTOM; michael@0: michael@0: presShell->ScrollContentIntoView(this, michael@0: nsIPresShell::ScrollAxis( michael@0: vpercent, michael@0: nsIPresShell::SCROLL_ALWAYS), michael@0: nsIPresShell::ScrollAxis(), michael@0: nsIPresShell::SCROLL_OVERFLOW_HIDDEN); michael@0: } michael@0: michael@0: bool michael@0: Element::ScrollByNoFlush(int32_t aDx, int32_t aDy) michael@0: { michael@0: nsIScrollableFrame* sf = GetScrollFrame(nullptr, false); michael@0: if (!sf) { michael@0: return false; michael@0: } michael@0: michael@0: nsWeakFrame weakRef(sf->GetScrolledFrame()); michael@0: michael@0: CSSIntPoint before = sf->GetScrollPositionCSSPixels(); michael@0: sf->ScrollToCSSPixelsApproximate(CSSIntPoint(before.x + aDx, before.y + aDy)); michael@0: michael@0: // The frame was destroyed, can't keep on scrolling. michael@0: if (!weakRef.IsAlive()) { michael@0: return false; michael@0: } michael@0: michael@0: CSSIntPoint after = sf->GetScrollPositionCSSPixels(); michael@0: return (before != after); michael@0: } michael@0: michael@0: static nsSize GetScrollRectSizeForOverflowVisibleFrame(nsIFrame* aFrame) michael@0: { michael@0: if (!aFrame) { michael@0: return nsSize(0,0); michael@0: } michael@0: michael@0: nsRect paddingRect = aFrame->GetPaddingRectRelativeToSelf(); michael@0: nsOverflowAreas overflowAreas(paddingRect, paddingRect); michael@0: // Add the scrollable overflow areas of children (if any) to the paddingRect. michael@0: // It's important to start with the paddingRect, otherwise if there are no michael@0: // children the overflow rect will be 0,0,0,0 which will force the point 0,0 michael@0: // to be included in the final rect. michael@0: nsLayoutUtils::UnionChildOverflow(aFrame, overflowAreas); michael@0: // Make sure that an empty padding-rect's edges are included, by adding michael@0: // the padding-rect in again with UnionEdges. michael@0: nsRect overflowRect = michael@0: overflowAreas.ScrollableOverflow().UnionEdges(paddingRect); michael@0: return nsLayoutUtils::GetScrolledRect(aFrame, michael@0: overflowRect, paddingRect.Size(), michael@0: aFrame->StyleVisibility()->mDirection).Size(); michael@0: } michael@0: michael@0: int32_t michael@0: Element::ScrollHeight() michael@0: { michael@0: if (IsSVG()) michael@0: return 0; michael@0: michael@0: nsIScrollableFrame* sf = GetScrollFrame(); michael@0: nscoord height; michael@0: if (sf) { michael@0: height = sf->GetScrollRange().height + sf->GetScrollPortRect().height; michael@0: } else { michael@0: height = GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).height; michael@0: } michael@0: michael@0: return nsPresContext::AppUnitsToIntCSSPixels(height); michael@0: } michael@0: michael@0: int32_t michael@0: Element::ScrollWidth() michael@0: { michael@0: if (IsSVG()) michael@0: return 0; michael@0: michael@0: nsIScrollableFrame* sf = GetScrollFrame(); michael@0: nscoord width; michael@0: if (sf) { michael@0: width = sf->GetScrollRange().width + sf->GetScrollPortRect().width; michael@0: } else { michael@0: width = GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).width; michael@0: } michael@0: michael@0: return nsPresContext::AppUnitsToIntCSSPixels(width); michael@0: } michael@0: michael@0: nsRect michael@0: Element::GetClientAreaRect() michael@0: { michael@0: nsIFrame* styledFrame; michael@0: nsIScrollableFrame* sf = GetScrollFrame(&styledFrame); michael@0: michael@0: if (sf) { michael@0: return sf->GetScrollPortRect(); michael@0: } michael@0: michael@0: if (styledFrame && michael@0: (styledFrame->StyleDisplay()->mDisplay != NS_STYLE_DISPLAY_INLINE || michael@0: styledFrame->IsFrameOfType(nsIFrame::eReplaced))) { michael@0: // Special case code to make client area work even when there isn't michael@0: // a scroll view, see bug 180552, bug 227567. michael@0: return styledFrame->GetPaddingRect() - styledFrame->GetPositionIgnoringScrolling(); michael@0: } michael@0: michael@0: // SVG nodes reach here and just return 0 michael@0: return nsRect(0, 0, 0, 0); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetBoundingClientRect() michael@0: { michael@0: nsRefPtr rect = new DOMRect(this); michael@0: michael@0: nsIFrame* frame = GetPrimaryFrame(Flush_Layout); michael@0: if (!frame) { michael@0: // display:none, perhaps? Return the empty rect michael@0: return rect.forget(); michael@0: } michael@0: michael@0: nsRect r = nsLayoutUtils::GetAllInFlowRectsUnion(frame, michael@0: nsLayoutUtils::GetContainingBlockForClientRect(frame), michael@0: nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS); michael@0: rect->SetLayoutRect(r); michael@0: return rect.forget(); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetClientRects() michael@0: { michael@0: nsRefPtr rectList = new DOMRectList(this); michael@0: michael@0: nsIFrame* frame = GetPrimaryFrame(Flush_Layout); michael@0: if (!frame) { michael@0: // display:none, perhaps? Return an empty list michael@0: return rectList.forget(); michael@0: } michael@0: michael@0: nsLayoutUtils::RectListBuilder builder(rectList); michael@0: nsLayoutUtils::GetAllInFlowRects(frame, michael@0: nsLayoutUtils::GetContainingBlockForClientRect(frame), &builder, michael@0: nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS); michael@0: return rectList.forget(); michael@0: } michael@0: michael@0: michael@0: //---------------------------------------------------------------------- michael@0: michael@0: void michael@0: Element::AddToIdTable(nsIAtom* aId) michael@0: { michael@0: NS_ASSERTION(HasID(), "Node doesn't have an ID?"); michael@0: if (HasFlag(NODE_IS_IN_SHADOW_TREE)) { michael@0: ShadowRoot* containingShadow = GetContainingShadow(); michael@0: containingShadow->AddToIdTable(this, aId); michael@0: } else { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc && (!IsInAnonymousSubtree() || doc->IsXUL())) { michael@0: doc->AddToIdTable(this, aId); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::RemoveFromIdTable() michael@0: { michael@0: if (HasID()) { michael@0: RemoveFromIdTable(DoGetID()); michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::RemoveFromIdTable(nsIAtom* aId) michael@0: { michael@0: NS_ASSERTION(HasID(), "Node doesn't have an ID?"); michael@0: if (HasFlag(NODE_IS_IN_SHADOW_TREE)) { michael@0: ShadowRoot* containingShadow = GetContainingShadow(); michael@0: // Check for containingShadow because it may have michael@0: // been deleted during unlinking. michael@0: if (containingShadow) { michael@0: containingShadow->RemoveFromIdTable(this, aId); michael@0: } michael@0: } else { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc && (!IsInAnonymousSubtree() || doc->IsXUL())) { michael@0: // id can be null during mutation events evilness. Also, XUL elements michael@0: // loose their proto attributes during cc-unlink, so this can happen michael@0: // during cc-unlink too. michael@0: if (aId) { michael@0: doc->RemoveFromIdTable(this, aId); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::CreateShadowRoot(ErrorResult& aError) michael@0: { michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: michael@0: nsCOMPtr nodeInfo; michael@0: nodeInfo = mNodeInfo->NodeInfoManager()->GetNodeInfo( michael@0: nsGkAtoms::documentFragmentNodeName, nullptr, kNameSpaceID_None, michael@0: nsIDOMNode::DOCUMENT_FRAGMENT_NODE); michael@0: michael@0: nsRefPtr docInfo = new nsXBLDocumentInfo(OwnerDoc()); michael@0: michael@0: nsXBLPrototypeBinding* protoBinding = new nsXBLPrototypeBinding(); michael@0: aError = protoBinding->Init(NS_LITERAL_CSTRING("shadowroot"), michael@0: docInfo, this, true); michael@0: if (aError.Failed()) { michael@0: delete protoBinding; michael@0: return nullptr; michael@0: } michael@0: michael@0: // Unlike for XBL, false is the default for inheriting style. michael@0: protoBinding->SetInheritsStyle(false); michael@0: michael@0: // Calling SetPrototypeBinding takes ownership of protoBinding. michael@0: docInfo->SetPrototypeBinding(NS_LITERAL_CSTRING("shadowroot"), protoBinding); michael@0: michael@0: nsRefPtr shadowRoot = new ShadowRoot(this, nodeInfo.forget(), michael@0: protoBinding); michael@0: michael@0: // Replace the old ShadowRoot with the new one and let the old michael@0: // ShadowRoot know about the younger ShadowRoot because the old michael@0: // ShadowRoot is projected into the younger ShadowRoot's shadow michael@0: // insertion point (if it exists). michael@0: ShadowRoot* olderShadow = GetShadowRoot(); michael@0: SetShadowRoot(shadowRoot); michael@0: if (olderShadow) { michael@0: olderShadow->SetYoungerShadow(shadowRoot); michael@0: } michael@0: michael@0: // xblBinding takes ownership of docInfo. michael@0: nsRefPtr xblBinding = new nsXBLBinding(shadowRoot, protoBinding); michael@0: shadowRoot->SetAssociatedBinding(xblBinding); michael@0: xblBinding->SetBoundElement(this); michael@0: michael@0: SetXBLBinding(xblBinding); michael@0: michael@0: // Recreate the frame for the bound content because binding a ShadowRoot michael@0: // changes how things are rendered. michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (doc) { michael@0: nsIPresShell *shell = doc->GetShell(); michael@0: if (shell) { michael@0: shell->RecreateFramesFor(this); michael@0: } michael@0: } michael@0: michael@0: return shadowRoot.forget(); michael@0: } michael@0: michael@0: void michael@0: Element::GetAttribute(const nsAString& aName, DOMString& aReturn) michael@0: { michael@0: const nsAttrValue* val = michael@0: mAttrsAndChildren.GetAttr(aName, michael@0: IsHTML() && IsInHTMLDocument() ? michael@0: eIgnoreCase : eCaseMatters); michael@0: if (val) { michael@0: val->ToString(aReturn); michael@0: } else { michael@0: if (IsXUL()) { michael@0: // XXX should be SetDOMStringToNull(aReturn); michael@0: // See bug 232598 michael@0: // aReturn is already empty michael@0: } else { michael@0: aReturn.SetNull(); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::SetAttribute(const nsAString& aName, michael@0: const nsAString& aValue, michael@0: ErrorResult& aError) michael@0: { michael@0: const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); michael@0: michael@0: if (!name) { michael@0: aError = nsContentUtils::CheckQName(aName, false); michael@0: if (aError.Failed()) { michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr nameAtom; michael@0: if (IsHTML() && IsInHTMLDocument()) { michael@0: nsAutoString lower; michael@0: nsresult rv = nsContentUtils::ASCIIToLower(aName, lower); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: nameAtom = do_GetAtom(lower); michael@0: } michael@0: } michael@0: else { michael@0: nameAtom = do_GetAtom(aName); michael@0: } michael@0: if (!nameAtom) { michael@0: aError.Throw(NS_ERROR_OUT_OF_MEMORY); michael@0: return; michael@0: } michael@0: aError = SetAttr(kNameSpaceID_None, nameAtom, aValue, true); michael@0: return; michael@0: } michael@0: michael@0: aError = SetAttr(name->NamespaceID(), name->LocalName(), name->GetPrefix(), michael@0: aValue, true); michael@0: return; michael@0: } michael@0: michael@0: void michael@0: Element::RemoveAttribute(const nsAString& aName, ErrorResult& aError) michael@0: { michael@0: const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); michael@0: michael@0: if (!name) { michael@0: // If there is no canonical nsAttrName for this attribute name, then the michael@0: // attribute does not exist and we can't get its namespace ID and michael@0: // local name below, so we return early. michael@0: return; michael@0: } michael@0: michael@0: // Hold a strong reference here so that the atom or nodeinfo doesn't go michael@0: // away during UnsetAttr. If it did UnsetAttr would be left with a michael@0: // dangling pointer as argument without knowing it. michael@0: nsAttrName tmp(*name); michael@0: michael@0: aError = UnsetAttr(name->NamespaceID(), name->LocalName(), true); michael@0: } michael@0: michael@0: Attr* michael@0: Element::GetAttributeNode(const nsAString& aName) michael@0: { michael@0: OwnerDoc()->WarnOnceAbout(nsIDocument::eGetAttributeNode); michael@0: return Attributes()->GetNamedItem(aName); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::SetAttributeNode(Attr& aNewAttr, ErrorResult& aError) michael@0: { michael@0: OwnerDoc()->WarnOnceAbout(nsIDocument::eSetAttributeNode); michael@0: michael@0: return Attributes()->SetNamedItem(aNewAttr, aError); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::RemoveAttributeNode(Attr& aAttribute, michael@0: ErrorResult& aError) michael@0: { michael@0: OwnerDoc()->WarnOnceAbout(nsIDocument::eRemoveAttributeNode); michael@0: return Attributes()->RemoveNamedItem(aAttribute.NodeName(), aError); michael@0: } michael@0: michael@0: void michael@0: Element::GetAttributeNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName, michael@0: nsAString& aReturn) michael@0: { michael@0: int32_t nsid = michael@0: nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); michael@0: michael@0: if (nsid == kNameSpaceID_Unknown) { michael@0: // Unknown namespace means no attribute. michael@0: SetDOMStringToNull(aReturn); michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr name = do_GetAtom(aLocalName); michael@0: bool hasAttr = GetAttr(nsid, name, aReturn); michael@0: if (!hasAttr) { michael@0: SetDOMStringToNull(aReturn); michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::SetAttributeNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aQualifiedName, michael@0: const nsAString& aValue, michael@0: ErrorResult& aError) michael@0: { michael@0: nsCOMPtr ni; michael@0: aError = michael@0: nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName, michael@0: mNodeInfo->NodeInfoManager(), michael@0: nsIDOMNode::ATTRIBUTE_NODE, michael@0: getter_AddRefs(ni)); michael@0: if (aError.Failed()) { michael@0: return; michael@0: } michael@0: michael@0: aError = SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(), michael@0: aValue, true); michael@0: } michael@0: michael@0: void michael@0: Element::RemoveAttributeNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName, michael@0: ErrorResult& aError) michael@0: { michael@0: nsCOMPtr name = do_GetAtom(aLocalName); michael@0: int32_t nsid = michael@0: nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); michael@0: michael@0: if (nsid == kNameSpaceID_Unknown) { michael@0: // If the namespace ID is unknown, it means there can't possibly be an michael@0: // existing attribute. We would need a known namespace ID to pass into michael@0: // UnsetAttr, so we return early if we don't have one. michael@0: return; michael@0: } michael@0: michael@0: aError = UnsetAttr(nsid, name, true); michael@0: } michael@0: michael@0: Attr* michael@0: Element::GetAttributeNodeNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName) michael@0: { michael@0: OwnerDoc()->WarnOnceAbout(nsIDocument::eGetAttributeNodeNS); michael@0: michael@0: return GetAttributeNodeNSInternal(aNamespaceURI, aLocalName); michael@0: } michael@0: michael@0: Attr* michael@0: Element::GetAttributeNodeNSInternal(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName) michael@0: { michael@0: return Attributes()->GetNamedItemNS(aNamespaceURI, aLocalName); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::SetAttributeNodeNS(Attr& aNewAttr, michael@0: ErrorResult& aError) michael@0: { michael@0: OwnerDoc()->WarnOnceAbout(nsIDocument::eSetAttributeNodeNS); michael@0: return Attributes()->SetNamedItemNS(aNewAttr, aError); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetElementsByTagNameNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName, michael@0: ErrorResult& aError) michael@0: { michael@0: int32_t nameSpaceId = kNameSpaceID_Wildcard; michael@0: michael@0: if (!aNamespaceURI.EqualsLiteral("*")) { michael@0: aError = michael@0: nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI, michael@0: nameSpaceId); michael@0: if (aError.Failed()) { michael@0: return nullptr; michael@0: } michael@0: } michael@0: michael@0: NS_ASSERTION(nameSpaceId != kNameSpaceID_Unknown, "Unexpected namespace ID!"); michael@0: michael@0: return NS_GetContentList(this, nameSpaceId, aLocalName); michael@0: } michael@0: michael@0: nsresult michael@0: Element::GetElementsByTagNameNS(const nsAString& namespaceURI, michael@0: const nsAString& localName, michael@0: nsIDOMHTMLCollection** aResult) michael@0: { michael@0: mozilla::ErrorResult rv; michael@0: nsCOMPtr list = michael@0: GetElementsByTagNameNS(namespaceURI, localName, rv); michael@0: if (rv.Failed()) { michael@0: return rv.ErrorCode(); michael@0: } michael@0: list.forget(aResult); michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: Element::HasAttributeNS(const nsAString& aNamespaceURI, michael@0: const nsAString& aLocalName) const michael@0: { michael@0: int32_t nsid = michael@0: nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); michael@0: michael@0: if (nsid == kNameSpaceID_Unknown) { michael@0: // Unknown namespace means no attr... michael@0: return false; michael@0: } michael@0: michael@0: nsCOMPtr name = do_GetAtom(aLocalName); michael@0: return HasAttr(nsid, name); michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetElementsByClassName(const nsAString& aClassNames) michael@0: { michael@0: return nsContentUtils::GetElementsByClassName(this, aClassNames); michael@0: } michael@0: michael@0: nsresult michael@0: Element::GetElementsByClassName(const nsAString& aClassNames, michael@0: nsIDOMHTMLCollection** aResult) michael@0: { michael@0: *aResult = michael@0: nsContentUtils::GetElementsByClassName(this, aClassNames).take(); michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: Element::BindToTree(nsIDocument* aDocument, nsIContent* aParent, michael@0: nsIContent* aBindingParent, michael@0: bool aCompileEventHandlers) michael@0: { michael@0: NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); michael@0: NS_PRECONDITION((NODE_FROM(aParent, aDocument)->OwnerDoc() == OwnerDoc()), michael@0: "Must have the same owner document"); michael@0: NS_PRECONDITION(!aParent || aDocument == aParent->GetCurrentDoc(), michael@0: "aDocument must be current doc of aParent"); michael@0: NS_PRECONDITION(!GetCurrentDoc(), "Already have a document. Unbind first!"); michael@0: // Note that as we recurse into the kids, they'll have a non-null parent. So michael@0: // only assert if our parent is _changing_ while we have a parent. michael@0: NS_PRECONDITION(!GetParent() || aParent == GetParent(), michael@0: "Already have a parent. Unbind first!"); michael@0: NS_PRECONDITION(!GetBindingParent() || michael@0: aBindingParent == GetBindingParent() || michael@0: (!aBindingParent && aParent && michael@0: aParent->GetBindingParent() == GetBindingParent()), michael@0: "Already have a binding parent. Unbind first!"); michael@0: NS_PRECONDITION(!aParent || !aDocument || michael@0: !aParent->HasFlag(NODE_FORCE_XBL_BINDINGS), michael@0: "Parent in document but flagged as forcing XBL"); michael@0: NS_PRECONDITION(aBindingParent != this, michael@0: "Content must not be its own binding parent"); michael@0: NS_PRECONDITION(!IsRootOfNativeAnonymousSubtree() || michael@0: aBindingParent == aParent, michael@0: "Native anonymous content must have its parent as its " michael@0: "own binding parent"); michael@0: NS_PRECONDITION(aBindingParent || !aParent || michael@0: aBindingParent == aParent->GetBindingParent(), michael@0: "We should be passed the right binding parent"); michael@0: michael@0: #ifdef MOZ_XUL michael@0: // First set the binding parent michael@0: nsXULElement* xulElem = nsXULElement::FromContent(this); michael@0: if (xulElem) { michael@0: xulElem->SetXULBindingParent(aBindingParent); michael@0: } michael@0: else michael@0: #endif michael@0: { michael@0: if (aBindingParent) { michael@0: nsDOMSlots *slots = DOMSlots(); michael@0: michael@0: slots->mBindingParent = aBindingParent; // Weak, so no addref happens. michael@0: } michael@0: } michael@0: NS_ASSERTION(!aBindingParent || IsRootOfNativeAnonymousSubtree() || michael@0: !HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE) || michael@0: (aParent && aParent->IsInNativeAnonymousSubtree()), michael@0: "Trying to re-bind content from native anonymous subtree to " michael@0: "non-native anonymous parent!"); michael@0: if (aParent) { michael@0: if (aParent->IsInNativeAnonymousSubtree()) { michael@0: SetFlags(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE); michael@0: } michael@0: if (aParent->HasFlag(NODE_CHROME_ONLY_ACCESS)) { michael@0: SetFlags(NODE_CHROME_ONLY_ACCESS); michael@0: } michael@0: if (aParent->HasFlag(NODE_IS_IN_SHADOW_TREE)) { michael@0: SetFlags(NODE_IS_IN_SHADOW_TREE); michael@0: } michael@0: ShadowRoot* parentContainingShadow = aParent->GetContainingShadow(); michael@0: if (parentContainingShadow) { michael@0: DOMSlots()->mContainingShadow = parentContainingShadow; michael@0: } michael@0: } michael@0: michael@0: bool hadForceXBL = HasFlag(NODE_FORCE_XBL_BINDINGS); michael@0: michael@0: // Now set the parent and set the "Force attach xbl" flag if needed. michael@0: if (aParent) { michael@0: if (!GetParent()) { michael@0: NS_ADDREF(aParent); michael@0: } michael@0: mParent = aParent; michael@0: michael@0: if (aParent->HasFlag(NODE_FORCE_XBL_BINDINGS)) { michael@0: SetFlags(NODE_FORCE_XBL_BINDINGS); michael@0: } michael@0: } michael@0: else { michael@0: mParent = aDocument; michael@0: } michael@0: SetParentIsContent(aParent); michael@0: michael@0: // XXXbz sXBL/XBL2 issue! michael@0: michael@0: // Finally, set the document michael@0: if (aDocument) { michael@0: // Notify XBL- & nsIAnonymousContentCreator-generated michael@0: // anonymous content that the document is changing. michael@0: // XXXbz ordering issues here? Probably not, since ChangeDocumentFor is michael@0: // just pretty broken anyway.... Need to get it working. michael@0: // XXXbz XBL doesn't handle this (asserts), and we don't really want michael@0: // to be doing this during parsing anyway... sort this out. michael@0: // aDocument->BindingManager()->ChangeDocumentFor(this, nullptr, michael@0: // aDocument); michael@0: michael@0: // We no longer need to track the subtree pointer (and in fact we'll assert michael@0: // if we do this any later). michael@0: ClearSubtreeRootPointer(); michael@0: michael@0: // Being added to a document. michael@0: SetInDocument(); michael@0: michael@0: if (GetCustomElementData()) { michael@0: // Enqueue an attached callback for the custom element. michael@0: aDocument->EnqueueLifecycleCallback(nsIDocument::eAttached, this); michael@0: } michael@0: michael@0: // Unset this flag since we now really are in a document. michael@0: UnsetFlags(NODE_FORCE_XBL_BINDINGS | michael@0: // And clear the lazy frame construction bits. michael@0: NODE_NEEDS_FRAME | NODE_DESCENDANTS_NEED_FRAMES | michael@0: // And the restyle bits michael@0: ELEMENT_ALL_RESTYLE_FLAGS); michael@0: michael@0: // Propagate scoped style sheet tracking bit. michael@0: SetIsElementInStyleScope(mParent->IsElementInStyleScope()); michael@0: } else { michael@0: // If we're not in the doc, update our subtree pointer. michael@0: SetSubtreeRootPointer(aParent->SubtreeRoot()); michael@0: } michael@0: michael@0: // This has to be here, rather than in nsGenericHTMLElement::BindToTree, michael@0: // because it has to happen after updating the parent pointer, but before michael@0: // recursively binding the kids. michael@0: if (IsHTML()) { michael@0: SetDirOnBind(this, aParent); michael@0: } michael@0: michael@0: // If NODE_FORCE_XBL_BINDINGS was set we might have anonymous children michael@0: // that also need to be told that they are moving. michael@0: nsresult rv; michael@0: if (hadForceXBL) { michael@0: nsBindingManager* bmgr = OwnerDoc()->BindingManager(); michael@0: michael@0: nsXBLBinding* contBinding = bmgr->GetBindingWithContent(this); michael@0: // First check if we have a binding... michael@0: if (contBinding) { michael@0: nsCOMPtr anonRoot = contBinding->GetAnonymousContent(); michael@0: bool allowScripts = contBinding->AllowScripts(); michael@0: for (nsCOMPtr child = anonRoot->GetFirstChild(); michael@0: child; michael@0: child = child->GetNextSibling()) { michael@0: rv = child->BindToTree(aDocument, this, this, allowScripts); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: } michael@0: } michael@0: michael@0: UpdateEditableState(false); michael@0: michael@0: // Now recurse into our kids michael@0: for (nsIContent* child = GetFirstChild(); child; michael@0: child = child->GetNextSibling()) { michael@0: rv = child->BindToTree(aDocument, this, aBindingParent, michael@0: aCompileEventHandlers); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: nsNodeUtils::ParentChainChanged(this); michael@0: michael@0: if (HasID()) { michael@0: AddToIdTable(DoGetID()); michael@0: } michael@0: michael@0: if (MayHaveStyle() && !IsXUL()) { michael@0: // XXXbz if we already have a style attr parsed, this won't do michael@0: // anything... need to fix that. michael@0: // If MayHaveStyle() is true, we must be an nsStyledElement michael@0: static_cast(this)->ReparseStyleAttribute(false); michael@0: } michael@0: michael@0: if (aDocument) { michael@0: // If we're in a document now, let our mapped attrs know what their new michael@0: // sheet is. This is safe to run for non-mapped-attribute elements too; michael@0: // it'll just do a small bit of unnecessary work. But most elements in michael@0: // practice are mapped-attribute elements. michael@0: nsHTMLStyleSheet* sheet = aDocument->GetAttributeStyleSheet(); michael@0: if (sheet) { michael@0: mAttrsAndChildren.SetMappedAttrStyleSheet(sheet); michael@0: } michael@0: } michael@0: michael@0: // XXXbz script execution during binding can trigger some of these michael@0: // postcondition asserts.... But we do want that, since things will michael@0: // generally be quite broken when that happens. michael@0: NS_POSTCONDITION(aDocument == GetCurrentDoc(), "Bound to wrong document"); michael@0: NS_POSTCONDITION(aParent == GetParent(), "Bound to wrong parent"); michael@0: NS_POSTCONDITION(aBindingParent == GetBindingParent(), michael@0: "Bound to wrong binding parent"); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: class RemoveFromBindingManagerRunnable : public nsRunnable { michael@0: public: michael@0: RemoveFromBindingManagerRunnable(nsBindingManager* aManager, michael@0: Element* aElement, michael@0: nsIDocument* aDoc): michael@0: mManager(aManager), mElement(aElement), mDoc(aDoc) michael@0: {} michael@0: michael@0: NS_IMETHOD Run() michael@0: { michael@0: // It may be the case that the element was removed from the michael@0: // DOM, causing this runnable to be created, then inserted back michael@0: // into the document before the this runnable had a chance to michael@0: // tear down the binding. Only tear down the binding if the element michael@0: // is still no longer in the DOM. nsXBLService::LoadBinding tears michael@0: // down the old binding if the element is inserted back into the michael@0: // DOM and loads a different binding. michael@0: if (!mElement->IsInDoc()) { michael@0: mManager->RemovedFromDocumentInternal(mElement, mDoc); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: private: michael@0: nsRefPtr mManager; michael@0: nsRefPtr mElement; michael@0: nsCOMPtr mDoc; michael@0: }; michael@0: michael@0: void michael@0: Element::UnbindFromTree(bool aDeep, bool aNullParent) michael@0: { michael@0: NS_PRECONDITION(aDeep || (!GetCurrentDoc() && !GetBindingParent()), michael@0: "Shallow unbind won't clear document and binding parent on " michael@0: "kids!"); michael@0: michael@0: RemoveFromIdTable(); michael@0: michael@0: // Make sure to unbind this node before doing the kids michael@0: nsIDocument *document = michael@0: HasFlag(NODE_FORCE_XBL_BINDINGS) ? OwnerDoc() : GetCurrentDoc(); michael@0: michael@0: if (aNullParent) { michael@0: if (IsFullScreenAncestor()) { michael@0: // The element being removed is an ancestor of the full-screen element, michael@0: // exit full-screen state. michael@0: nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, michael@0: NS_LITERAL_CSTRING("DOM"), OwnerDoc(), michael@0: nsContentUtils::eDOM_PROPERTIES, michael@0: "RemovedFullScreenElement"); michael@0: // Fully exit full-screen. michael@0: nsIDocument::ExitFullscreen(OwnerDoc(), /* async */ false); michael@0: } michael@0: if (HasPointerLock()) { michael@0: nsIDocument::UnlockPointer(); michael@0: } michael@0: if (GetParent()) { michael@0: nsINode* p = mParent; michael@0: mParent = nullptr; michael@0: NS_RELEASE(p); michael@0: } else { michael@0: mParent = nullptr; michael@0: } michael@0: SetParentIsContent(false); michael@0: } michael@0: ClearInDocument(); michael@0: michael@0: // Begin keeping track of our subtree root. michael@0: SetSubtreeRootPointer(aNullParent ? this : mParent->SubtreeRoot()); michael@0: michael@0: if (document) { michael@0: // Notify XBL- & nsIAnonymousContentCreator-generated michael@0: // anonymous content that the document is changing. michael@0: if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR)) { michael@0: nsContentUtils::AddScriptRunner( michael@0: new RemoveFromBindingManagerRunnable(document->BindingManager(), this, michael@0: document)); michael@0: } michael@0: michael@0: document->ClearBoxObjectFor(this); michael@0: michael@0: if (GetCustomElementData()) { michael@0: // Enqueue a detached callback for the custom element. michael@0: document->EnqueueLifecycleCallback(nsIDocument::eDetached, this); michael@0: } michael@0: } michael@0: michael@0: // Ensure that CSS transitions don't continue on an element at a michael@0: // different place in the tree (even if reinserted before next michael@0: // animation refresh). michael@0: // FIXME (Bug 522599): Need a test for this. michael@0: if (HasFlag(NODE_HAS_PROPERTIES)) { michael@0: DeleteProperty(nsGkAtoms::transitionsOfBeforeProperty); michael@0: DeleteProperty(nsGkAtoms::transitionsOfAfterProperty); michael@0: DeleteProperty(nsGkAtoms::transitionsProperty); michael@0: DeleteProperty(nsGkAtoms::animationsOfBeforeProperty); michael@0: DeleteProperty(nsGkAtoms::animationsOfAfterProperty); michael@0: DeleteProperty(nsGkAtoms::animationsProperty); michael@0: } michael@0: michael@0: // Unset this since that's what the old code effectively did. michael@0: UnsetFlags(NODE_FORCE_XBL_BINDINGS | NODE_IS_IN_SHADOW_TREE); michael@0: michael@0: #ifdef MOZ_XUL michael@0: nsXULElement* xulElem = nsXULElement::FromContent(this); michael@0: if (xulElem) { michael@0: xulElem->SetXULBindingParent(nullptr); michael@0: } michael@0: else michael@0: #endif michael@0: { michael@0: nsDOMSlots *slots = GetExistingDOMSlots(); michael@0: if (slots) { michael@0: slots->mBindingParent = nullptr; michael@0: slots->mContainingShadow = nullptr; michael@0: } michael@0: } michael@0: michael@0: // This has to be here, rather than in nsGenericHTMLElement::UnbindFromTree, michael@0: // because it has to happen after unsetting the parent pointer, but before michael@0: // recursively unbinding the kids. michael@0: if (IsHTML()) { michael@0: ResetDir(this); michael@0: } michael@0: michael@0: if (aDeep) { michael@0: // Do the kids. Don't call GetChildCount() here since that'll force michael@0: // XUL to generate template children, which there is no need for since michael@0: // all we're going to do is unbind them anyway. michael@0: uint32_t i, n = mAttrsAndChildren.ChildCount(); michael@0: michael@0: for (i = 0; i < n; ++i) { michael@0: // Note that we pass false for aNullParent here, since we don't want michael@0: // the kids to forget us. We _do_ want them to forget their binding michael@0: // parent, though, since this only walks non-anonymous kids. michael@0: mAttrsAndChildren.ChildAt(i)->UnbindFromTree(true, false); michael@0: } michael@0: } michael@0: michael@0: nsNodeUtils::ParentChainChanged(this); michael@0: } michael@0: michael@0: nsICSSDeclaration* michael@0: Element::GetSMILOverrideStyle() michael@0: { michael@0: Element::nsDOMSlots *slots = DOMSlots(); michael@0: michael@0: if (!slots->mSMILOverrideStyle) { michael@0: slots->mSMILOverrideStyle = new nsDOMCSSAttributeDeclaration(this, true); michael@0: } michael@0: michael@0: return slots->mSMILOverrideStyle; michael@0: } michael@0: michael@0: css::StyleRule* michael@0: Element::GetSMILOverrideStyleRule() michael@0: { michael@0: Element::nsDOMSlots *slots = GetExistingDOMSlots(); michael@0: return slots ? slots->mSMILOverrideStyleRule.get() : nullptr; michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetSMILOverrideStyleRule(css::StyleRule* aStyleRule, michael@0: bool aNotify) michael@0: { michael@0: Element::nsDOMSlots *slots = DOMSlots(); michael@0: michael@0: slots->mSMILOverrideStyleRule = aStyleRule; michael@0: michael@0: if (aNotify) { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: // Only need to request a restyle if we're in a document. (We might not michael@0: // be in a document, if we're clearing animation effects on a target node michael@0: // that's been detached since the previous animation sample.) michael@0: if (doc) { michael@0: nsCOMPtr shell = doc->GetShell(); michael@0: if (shell) { michael@0: shell->RestyleForAnimation(this, eRestyle_Self); michael@0: } michael@0: } michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: Element::IsLabelable() const michael@0: { michael@0: return false; michael@0: } michael@0: michael@0: css::StyleRule* michael@0: Element::GetInlineStyleRule() michael@0: { michael@0: return nullptr; michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetInlineStyleRule(css::StyleRule* aStyleRule, michael@0: const nsAString* aSerialized, michael@0: bool aNotify) michael@0: { michael@0: NS_NOTYETIMPLEMENTED("Element::SetInlineStyleRule"); michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: } michael@0: michael@0: NS_IMETHODIMP_(bool) michael@0: Element::IsAttributeMapped(const nsIAtom* aAttribute) const michael@0: { michael@0: return false; michael@0: } michael@0: michael@0: nsChangeHint michael@0: Element::GetAttributeChangeHint(const nsIAtom* aAttribute, michael@0: int32_t aModType) const michael@0: { michael@0: return nsChangeHint(0); michael@0: } michael@0: michael@0: nsIAtom * michael@0: Element::GetClassAttributeName() const michael@0: { michael@0: return nullptr; michael@0: } michael@0: michael@0: bool michael@0: Element::FindAttributeDependence(const nsIAtom* aAttribute, michael@0: const MappedAttributeEntry* const aMaps[], michael@0: uint32_t aMapCount) michael@0: { michael@0: for (uint32_t mapindex = 0; mapindex < aMapCount; ++mapindex) { michael@0: for (const MappedAttributeEntry* map = aMaps[mapindex]; michael@0: map->attribute; ++map) { michael@0: if (aAttribute == *map->attribute) { michael@0: return true; michael@0: } michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: already_AddRefed michael@0: Element::GetExistingAttrNameFromQName(const nsAString& aStr) const michael@0: { michael@0: const nsAttrName* name = InternalGetExistingAttrNameFromQName(aStr); michael@0: if (!name) { michael@0: return nullptr; michael@0: } michael@0: michael@0: nsCOMPtr nodeInfo; michael@0: if (name->IsAtom()) { michael@0: nodeInfo = mNodeInfo->NodeInfoManager()-> michael@0: GetNodeInfo(name->Atom(), nullptr, kNameSpaceID_None, michael@0: nsIDOMNode::ATTRIBUTE_NODE); michael@0: } michael@0: else { michael@0: nodeInfo = name->NodeInfo(); michael@0: } michael@0: michael@0: return nodeInfo.forget(); michael@0: } michael@0: michael@0: // static michael@0: bool michael@0: Element::ShouldBlur(nsIContent *aContent) michael@0: { michael@0: // Determine if the current element is focused, if it is not focused michael@0: // then we should not try to blur michael@0: nsIDocument *document = aContent->GetDocument(); michael@0: if (!document) michael@0: return false; michael@0: michael@0: nsCOMPtr window = do_QueryInterface(document->GetWindow()); michael@0: if (!window) michael@0: return false; michael@0: michael@0: nsCOMPtr focusedFrame; michael@0: nsIContent* contentToBlur = michael@0: nsFocusManager::GetFocusedDescendant(window, false, getter_AddRefs(focusedFrame)); michael@0: if (contentToBlur == aContent) michael@0: return true; michael@0: michael@0: // if focus on this element would get redirected, then check the redirected michael@0: // content as well when blurring. michael@0: return (contentToBlur && nsFocusManager::GetRedirectedFocus(aContent) == contentToBlur); michael@0: } michael@0: michael@0: bool michael@0: Element::IsNodeOfType(uint32_t aFlags) const michael@0: { michael@0: return !(aFlags & ~eCONTENT); michael@0: } michael@0: michael@0: /* static */ michael@0: nsresult michael@0: Element::DispatchEvent(nsPresContext* aPresContext, michael@0: WidgetEvent* aEvent, michael@0: nsIContent* aTarget, michael@0: bool aFullDispatch, michael@0: nsEventStatus* aStatus) michael@0: { michael@0: NS_PRECONDITION(aTarget, "Must have target"); michael@0: NS_PRECONDITION(aEvent, "Must have source event"); michael@0: NS_PRECONDITION(aStatus, "Null out param?"); michael@0: michael@0: if (!aPresContext) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsCOMPtr shell = aPresContext->GetPresShell(); michael@0: if (!shell) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: if (aFullDispatch) { michael@0: return shell->HandleEventWithTarget(aEvent, nullptr, aTarget, aStatus); michael@0: } michael@0: michael@0: return shell->HandleDOMEventWithTarget(aTarget, aEvent, aStatus); michael@0: } michael@0: michael@0: /* static */ michael@0: nsresult michael@0: Element::DispatchClickEvent(nsPresContext* aPresContext, michael@0: WidgetInputEvent* aSourceEvent, michael@0: nsIContent* aTarget, michael@0: bool aFullDispatch, michael@0: const EventFlags* aExtraEventFlags, michael@0: nsEventStatus* aStatus) michael@0: { michael@0: NS_PRECONDITION(aTarget, "Must have target"); michael@0: NS_PRECONDITION(aSourceEvent, "Must have source event"); michael@0: NS_PRECONDITION(aStatus, "Null out param?"); michael@0: michael@0: WidgetMouseEvent event(aSourceEvent->mFlags.mIsTrusted, NS_MOUSE_CLICK, michael@0: aSourceEvent->widget, WidgetMouseEvent::eReal); michael@0: event.refPoint = aSourceEvent->refPoint; michael@0: uint32_t clickCount = 1; michael@0: float pressure = 0; michael@0: uint16_t inputSource = 0; michael@0: WidgetMouseEvent* sourceMouseEvent = aSourceEvent->AsMouseEvent(); michael@0: if (sourceMouseEvent) { michael@0: clickCount = sourceMouseEvent->clickCount; michael@0: pressure = sourceMouseEvent->pressure; michael@0: inputSource = sourceMouseEvent->inputSource; michael@0: } else if (aSourceEvent->eventStructType == NS_KEY_EVENT) { michael@0: inputSource = nsIDOMMouseEvent::MOZ_SOURCE_KEYBOARD; michael@0: } michael@0: event.pressure = pressure; michael@0: event.clickCount = clickCount; michael@0: event.inputSource = inputSource; michael@0: event.modifiers = aSourceEvent->modifiers; michael@0: if (aExtraEventFlags) { michael@0: // Be careful not to overwrite existing flags! michael@0: event.mFlags.Union(*aExtraEventFlags); michael@0: } michael@0: michael@0: return DispatchEvent(aPresContext, &event, aTarget, aFullDispatch, aStatus); michael@0: } michael@0: michael@0: nsIFrame* michael@0: Element::GetPrimaryFrame(mozFlushType aType) michael@0: { michael@0: nsIDocument* doc = GetCurrentDoc(); michael@0: if (!doc) { michael@0: return nullptr; michael@0: } michael@0: michael@0: // Cause a flush, so we get up-to-date frame michael@0: // information michael@0: if (aType != Flush_None) { michael@0: doc->FlushPendingNotifications(aType); michael@0: } michael@0: michael@0: return GetPrimaryFrame(); michael@0: } michael@0: michael@0: //---------------------------------------------------------------------- michael@0: nsresult michael@0: Element::LeaveLink(nsPresContext* aPresContext) michael@0: { michael@0: nsILinkHandler *handler = aPresContext->GetLinkHandler(); michael@0: if (!handler) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: return handler->OnLeaveLink(); michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetEventHandler(nsIAtom* aEventName, michael@0: const nsAString& aValue, michael@0: bool aDefer) michael@0: { michael@0: nsIDocument *ownerDoc = OwnerDoc(); michael@0: if (ownerDoc->IsLoadedAsData()) { michael@0: // Make this a no-op rather than throwing an error to avoid michael@0: // the error causing problems setting the attribute. michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_PRECONDITION(aEventName, "Must have event name!"); michael@0: bool defer = true; michael@0: EventListenerManager* manager = michael@0: GetEventListenerManagerForAttr(aEventName, &defer); michael@0: if (!manager) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: defer = defer && aDefer; // only defer if everyone agrees... michael@0: manager->SetEventHandler(aEventName, aValue, michael@0: nsIProgrammingLanguage::JAVASCRIPT, michael@0: defer, !nsContentUtils::IsChromeDoc(ownerDoc), michael@0: this); michael@0: return NS_OK; michael@0: } michael@0: michael@0: michael@0: //---------------------------------------------------------------------- michael@0: michael@0: const nsAttrName* michael@0: Element::InternalGetExistingAttrNameFromQName(const nsAString& aStr) const michael@0: { michael@0: return mAttrsAndChildren.GetExistingAttrNameFromQName(aStr); michael@0: } michael@0: michael@0: bool michael@0: Element::MaybeCheckSameAttrVal(int32_t aNamespaceID, michael@0: nsIAtom* aName, michael@0: nsIAtom* aPrefix, michael@0: const nsAttrValueOrString& aValue, michael@0: bool aNotify, michael@0: nsAttrValue& aOldValue, michael@0: uint8_t* aModType, michael@0: bool* aHasListeners) michael@0: { michael@0: bool modification = false; michael@0: *aHasListeners = aNotify && michael@0: nsContentUtils::HasMutationListeners(this, michael@0: NS_EVENT_BITS_MUTATION_ATTRMODIFIED, michael@0: this); michael@0: michael@0: // If we have no listeners and aNotify is false, we are almost certainly michael@0: // coming from the content sink and will almost certainly have no previous michael@0: // value. Even if we do, setting the value is cheap when we have no michael@0: // listeners and don't plan to notify. The check for aNotify here is an michael@0: // optimization, the check for *aHasListeners is a correctness issue. michael@0: if (*aHasListeners || aNotify) { michael@0: nsAttrInfo info(GetAttrInfo(aNamespaceID, aName)); michael@0: if (info.mValue) { michael@0: // Check whether the old value is the same as the new one. Note that we michael@0: // only need to actually _get_ the old value if we have listeners or michael@0: // if the element is a custom element (because it may have an michael@0: // attribute changed callback). michael@0: if (*aHasListeners || GetCustomElementData()) { michael@0: // Need to store the old value. michael@0: // michael@0: // If the current attribute value contains a pointer to some other data michael@0: // structure that gets updated in the process of setting the attribute michael@0: // we'll no longer have the old value of the attribute. Therefore, we michael@0: // should serialize the attribute value now to keep a snapshot. michael@0: // michael@0: // We have to serialize the value anyway in order to create the michael@0: // mutation event so there's no cost in doing it now. michael@0: aOldValue.SetToSerialized(*info.mValue); michael@0: } michael@0: bool valueMatches = aValue.EqualsAsStrings(*info.mValue); michael@0: if (valueMatches && aPrefix == info.mName->GetPrefix()) { michael@0: return true; michael@0: } michael@0: modification = true; michael@0: } michael@0: } michael@0: *aModType = modification ? michael@0: static_cast(nsIDOMMutationEvent::MODIFICATION) : michael@0: static_cast(nsIDOMMutationEvent::ADDITION); michael@0: return false; michael@0: } michael@0: michael@0: bool michael@0: Element::OnlyNotifySameValueSet(int32_t aNamespaceID, nsIAtom* aName, michael@0: nsIAtom* aPrefix, michael@0: const nsAttrValueOrString& aValue, michael@0: bool aNotify, nsAttrValue& aOldValue, michael@0: uint8_t* aModType, bool* aHasListeners) michael@0: { michael@0: if (!MaybeCheckSameAttrVal(aNamespaceID, aName, aPrefix, aValue, aNotify, michael@0: aOldValue, aModType, aHasListeners)) { michael@0: return false; michael@0: } michael@0: michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: nsNodeUtils::AttributeSetToCurrentValue(this, aNamespaceID, aName); michael@0: return true; michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetAttr(int32_t aNamespaceID, nsIAtom* aName, michael@0: nsIAtom* aPrefix, const nsAString& aValue, michael@0: bool aNotify) michael@0: { michael@0: // Keep this in sync with SetParsedAttr below michael@0: michael@0: NS_ENSURE_ARG_POINTER(aName); michael@0: NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown, michael@0: "Don't call SetAttr with unknown namespace"); michael@0: michael@0: if (!mAttrsAndChildren.CanFitMoreAttrs()) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: uint8_t modType; michael@0: bool hasListeners; michael@0: nsAttrValueOrString value(aValue); michael@0: nsAttrValue oldValue; michael@0: michael@0: if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify, michael@0: oldValue, &modType, &hasListeners)) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (aNotify) { michael@0: nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType); michael@0: } michael@0: michael@0: // Hold a script blocker while calling ParseAttribute since that can call michael@0: // out to id-observers michael@0: nsAutoScriptBlocker scriptBlocker; michael@0: michael@0: nsAttrValue attrValue; michael@0: if (!ParseAttribute(aNamespaceID, aName, aValue, attrValue)) { michael@0: attrValue.SetTo(aValue); michael@0: } michael@0: michael@0: return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue, michael@0: attrValue, modType, hasListeners, aNotify, michael@0: kCallAfterSetAttr); michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetParsedAttr(int32_t aNamespaceID, nsIAtom* aName, michael@0: nsIAtom* aPrefix, nsAttrValue& aParsedValue, michael@0: bool aNotify) michael@0: { michael@0: // Keep this in sync with SetAttr above michael@0: michael@0: NS_ENSURE_ARG_POINTER(aName); michael@0: NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown, michael@0: "Don't call SetAttr with unknown namespace"); michael@0: michael@0: if (!mAttrsAndChildren.CanFitMoreAttrs()) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: michael@0: uint8_t modType; michael@0: bool hasListeners; michael@0: nsAttrValueOrString value(aParsedValue); michael@0: nsAttrValue oldValue; michael@0: michael@0: if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify, michael@0: oldValue, &modType, &hasListeners)) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (aNotify) { michael@0: nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType); michael@0: } michael@0: michael@0: return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue, michael@0: aParsedValue, modType, hasListeners, aNotify, michael@0: kCallAfterSetAttr); michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetAttrAndNotify(int32_t aNamespaceID, michael@0: nsIAtom* aName, michael@0: nsIAtom* aPrefix, michael@0: const nsAttrValue& aOldValue, michael@0: nsAttrValue& aParsedValue, michael@0: uint8_t aModType, michael@0: bool aFireMutation, michael@0: bool aNotify, michael@0: bool aCallAfterSetAttr) michael@0: { michael@0: nsresult rv; michael@0: michael@0: nsIDocument* document = GetCurrentDoc(); michael@0: mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify); michael@0: michael@0: nsMutationGuard::DidMutate(); michael@0: michael@0: // Copy aParsedValue for later use since it will be lost when we call michael@0: // SetAndTakeMappedAttr below michael@0: nsAttrValue aValueForAfterSetAttr; michael@0: if (aCallAfterSetAttr) { michael@0: aValueForAfterSetAttr.SetTo(aParsedValue); michael@0: } michael@0: michael@0: bool hadValidDir = false; michael@0: bool hadDirAuto = false; michael@0: michael@0: if (aNamespaceID == kNameSpaceID_None) { michael@0: if (aName == nsGkAtoms::dir) { michael@0: hadValidDir = HasValidDir() || IsHTML(nsGkAtoms::bdi); michael@0: hadDirAuto = HasDirAuto(); // already takes bdi into account michael@0: } michael@0: michael@0: // XXXbz Perhaps we should push up the attribute mapping function michael@0: // stuff to Element? michael@0: if (!IsAttributeMapped(aName) || michael@0: !SetMappedAttribute(document, aName, aParsedValue, &rv)) { michael@0: rv = mAttrsAndChildren.SetAndTakeAttr(aName, aParsedValue); michael@0: } michael@0: } michael@0: else { michael@0: nsCOMPtr ni; michael@0: ni = mNodeInfo->NodeInfoManager()->GetNodeInfo(aName, aPrefix, michael@0: aNamespaceID, michael@0: nsIDOMNode::ATTRIBUTE_NODE); michael@0: michael@0: rv = mAttrsAndChildren.SetAndTakeAttr(ni, aParsedValue); michael@0: } michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) { michael@0: nsRefPtr binding = GetXBLBinding(); michael@0: if (binding) { michael@0: binding->AttributeChanged(aName, aNamespaceID, false, aNotify); michael@0: } michael@0: } michael@0: michael@0: UpdateState(aNotify); michael@0: michael@0: nsIDocument* ownerDoc = OwnerDoc(); michael@0: if (ownerDoc && GetCustomElementData()) { michael@0: nsCOMPtr oldValueAtom = aOldValue.GetAsAtom(); michael@0: nsCOMPtr newValueAtom = aValueForAfterSetAttr.GetAsAtom(); michael@0: LifecycleCallbackArgs args = { michael@0: nsDependentAtomString(aName), michael@0: aModType == nsIDOMMutationEvent::ADDITION ? michael@0: NullString() : nsDependentAtomString(oldValueAtom), michael@0: nsDependentAtomString(newValueAtom) michael@0: }; michael@0: michael@0: ownerDoc->EnqueueLifecycleCallback(nsIDocument::eAttributeChanged, this, &args); michael@0: } michael@0: michael@0: if (aCallAfterSetAttr) { michael@0: rv = AfterSetAttr(aNamespaceID, aName, &aValueForAfterSetAttr, aNotify); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (aNamespaceID == kNameSpaceID_None && aName == nsGkAtoms::dir) { michael@0: OnSetDirAttr(this, &aValueForAfterSetAttr, michael@0: hadValidDir, hadDirAuto, aNotify); michael@0: } michael@0: } michael@0: michael@0: if (aNotify) { michael@0: nsNodeUtils::AttributeChanged(this, aNamespaceID, aName, aModType); michael@0: } michael@0: michael@0: if (aFireMutation) { michael@0: InternalMutationEvent mutation(true, NS_MUTATION_ATTRMODIFIED); michael@0: michael@0: nsAutoString ns; michael@0: nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID, ns); michael@0: Attr* attrNode = michael@0: GetAttributeNodeNSInternal(ns, nsDependentAtomString(aName)); michael@0: mutation.mRelatedNode = attrNode; michael@0: michael@0: mutation.mAttrName = aName; michael@0: nsAutoString newValue; michael@0: GetAttr(aNamespaceID, aName, newValue); michael@0: if (!newValue.IsEmpty()) { michael@0: mutation.mNewAttrValue = do_GetAtom(newValue); michael@0: } michael@0: if (!aOldValue.IsEmptyString()) { michael@0: mutation.mPrevAttrValue = aOldValue.GetAsAtom(); michael@0: } michael@0: mutation.mAttrChange = aModType; michael@0: michael@0: mozAutoSubtreeModified subtree(OwnerDoc(), this); michael@0: (new AsyncEventDispatcher(this, mutation))->RunDOMEventWhenSafe(); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: Element::ParseAttribute(int32_t aNamespaceID, michael@0: nsIAtom* aAttribute, michael@0: const nsAString& aValue, michael@0: nsAttrValue& aResult) michael@0: { michael@0: return false; michael@0: } michael@0: michael@0: bool michael@0: Element::SetMappedAttribute(nsIDocument* aDocument, michael@0: nsIAtom* aName, michael@0: nsAttrValue& aValue, michael@0: nsresult* aRetval) michael@0: { michael@0: *aRetval = NS_OK; michael@0: return false; michael@0: } michael@0: michael@0: EventListenerManager* michael@0: Element::GetEventListenerManagerForAttr(nsIAtom* aAttrName, michael@0: bool* aDefer) michael@0: { michael@0: *aDefer = true; michael@0: return GetOrCreateListenerManager(); michael@0: } michael@0: michael@0: Element::nsAttrInfo michael@0: Element::GetAttrInfo(int32_t aNamespaceID, nsIAtom* aName) const michael@0: { michael@0: NS_ASSERTION(nullptr != aName, "must have attribute name"); michael@0: NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown, michael@0: "must have a real namespace ID!"); michael@0: michael@0: int32_t index = mAttrsAndChildren.IndexOfAttr(aName, aNamespaceID); michael@0: if (index >= 0) { michael@0: return nsAttrInfo(mAttrsAndChildren.AttrNameAt(index), michael@0: mAttrsAndChildren.AttrAt(index)); michael@0: } michael@0: michael@0: return nsAttrInfo(nullptr, nullptr); michael@0: } michael@0: michael@0: michael@0: bool michael@0: Element::GetAttr(int32_t aNameSpaceID, nsIAtom* aName, michael@0: nsAString& aResult) const michael@0: { michael@0: DOMString str; michael@0: bool haveAttr = GetAttr(aNameSpaceID, aName, str); michael@0: str.ToString(aResult); michael@0: return haveAttr; michael@0: } michael@0: michael@0: int32_t michael@0: Element::FindAttrValueIn(int32_t aNameSpaceID, michael@0: nsIAtom* aName, michael@0: AttrValuesArray* aValues, michael@0: nsCaseTreatment aCaseSensitive) const michael@0: { michael@0: NS_ASSERTION(aName, "Must have attr name"); michael@0: NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace"); michael@0: NS_ASSERTION(aValues, "Null value array"); michael@0: michael@0: const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID); michael@0: if (val) { michael@0: for (int32_t i = 0; aValues[i]; ++i) { michael@0: if (val->Equals(*aValues[i], aCaseSensitive)) { michael@0: return i; michael@0: } michael@0: } michael@0: return ATTR_VALUE_NO_MATCH; michael@0: } michael@0: return ATTR_MISSING; michael@0: } michael@0: michael@0: nsresult michael@0: Element::UnsetAttr(int32_t aNameSpaceID, nsIAtom* aName, michael@0: bool aNotify) michael@0: { michael@0: NS_ASSERTION(nullptr != aName, "must have attribute name"); michael@0: michael@0: int32_t index = mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID); michael@0: if (index < 0) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = BeforeSetAttr(aNameSpaceID, aName, nullptr, aNotify); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: nsIDocument *document = GetCurrentDoc(); michael@0: mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify); michael@0: michael@0: if (aNotify) { michael@0: nsNodeUtils::AttributeWillChange(this, aNameSpaceID, aName, michael@0: nsIDOMMutationEvent::REMOVAL); michael@0: } michael@0: michael@0: bool hasMutationListeners = aNotify && michael@0: nsContentUtils::HasMutationListeners(this, michael@0: NS_EVENT_BITS_MUTATION_ATTRMODIFIED, michael@0: this); michael@0: michael@0: // Grab the attr node if needed before we remove it from the attr map michael@0: nsRefPtr attrNode; michael@0: if (hasMutationListeners) { michael@0: nsAutoString ns; michael@0: nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNameSpaceID, ns); michael@0: attrNode = GetAttributeNodeNSInternal(ns, nsDependentAtomString(aName)); michael@0: } michael@0: michael@0: // Clear binding to nsIDOMMozNamedAttrMap michael@0: nsDOMSlots *slots = GetExistingDOMSlots(); michael@0: if (slots && slots->mAttributeMap) { michael@0: slots->mAttributeMap->DropAttribute(aNameSpaceID, aName); michael@0: } michael@0: michael@0: // The id-handling code, and in the future possibly other code, need to michael@0: // react to unexpected attribute changes. michael@0: nsMutationGuard::DidMutate(); michael@0: michael@0: bool hadValidDir = false; michael@0: bool hadDirAuto = false; michael@0: michael@0: if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::dir) { michael@0: hadValidDir = HasValidDir() || IsHTML(nsGkAtoms::bdi); michael@0: hadDirAuto = HasDirAuto(); // already takes bdi into account michael@0: } michael@0: michael@0: nsAttrValue oldValue; michael@0: rv = mAttrsAndChildren.RemoveAttrAt(index, oldValue); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) { michael@0: nsRefPtr binding = GetXBLBinding(); michael@0: if (binding) { michael@0: binding->AttributeChanged(aName, aNameSpaceID, true, aNotify); michael@0: } michael@0: } michael@0: michael@0: UpdateState(aNotify); michael@0: michael@0: nsIDocument* ownerDoc = OwnerDoc(); michael@0: if (ownerDoc && GetCustomElementData()) { michael@0: nsCOMPtr oldValueAtom = oldValue.GetAsAtom(); michael@0: LifecycleCallbackArgs args = { michael@0: nsDependentAtomString(aName), michael@0: nsDependentAtomString(oldValueAtom), michael@0: NullString() michael@0: }; michael@0: michael@0: ownerDoc->EnqueueLifecycleCallback(nsIDocument::eAttributeChanged, this, &args); michael@0: } michael@0: michael@0: if (aNotify) { michael@0: nsNodeUtils::AttributeChanged(this, aNameSpaceID, aName, michael@0: nsIDOMMutationEvent::REMOVAL); michael@0: } michael@0: michael@0: rv = AfterSetAttr(aNameSpaceID, aName, nullptr, aNotify); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::dir) { michael@0: OnSetDirAttr(this, nullptr, hadValidDir, hadDirAuto, aNotify); michael@0: } michael@0: michael@0: if (hasMutationListeners) { michael@0: InternalMutationEvent mutation(true, NS_MUTATION_ATTRMODIFIED); michael@0: michael@0: mutation.mRelatedNode = attrNode; michael@0: mutation.mAttrName = aName; michael@0: michael@0: nsAutoString value; michael@0: oldValue.ToString(value); michael@0: if (!value.IsEmpty()) michael@0: mutation.mPrevAttrValue = do_GetAtom(value); michael@0: mutation.mAttrChange = nsIDOMMutationEvent::REMOVAL; michael@0: michael@0: mozAutoSubtreeModified subtree(OwnerDoc(), this); michael@0: (new AsyncEventDispatcher(this, mutation))->RunDOMEventWhenSafe(); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: const nsAttrName* michael@0: Element::GetAttrNameAt(uint32_t aIndex) const michael@0: { michael@0: return mAttrsAndChildren.GetSafeAttrNameAt(aIndex); michael@0: } michael@0: michael@0: uint32_t michael@0: Element::GetAttrCount() const michael@0: { michael@0: return mAttrsAndChildren.AttrCount(); michael@0: } michael@0: michael@0: void michael@0: Element::DescribeAttribute(uint32_t index, nsAString& aOutDescription) const michael@0: { michael@0: // name michael@0: mAttrsAndChildren.AttrNameAt(index)->GetQualifiedName(aOutDescription); michael@0: michael@0: // value michael@0: aOutDescription.AppendLiteral("=\""); michael@0: nsAutoString value; michael@0: mAttrsAndChildren.AttrAt(index)->ToString(value); michael@0: for (int i = value.Length(); i >= 0; --i) { michael@0: if (value[i] == char16_t('"')) michael@0: value.Insert(char16_t('\\'), uint32_t(i)); michael@0: } michael@0: aOutDescription.Append(value); michael@0: aOutDescription.AppendLiteral("\""); michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: void michael@0: Element::ListAttributes(FILE* out) const michael@0: { michael@0: uint32_t index, count = mAttrsAndChildren.AttrCount(); michael@0: for (index = 0; index < count; index++) { michael@0: nsAutoString attributeDescription; michael@0: DescribeAttribute(index, attributeDescription); michael@0: michael@0: fputs(" ", out); michael@0: fputs(NS_LossyConvertUTF16toASCII(attributeDescription).get(), out); michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::List(FILE* out, int32_t aIndent, michael@0: const nsCString& aPrefix) const michael@0: { michael@0: int32_t indent; michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: michael@0: fputs(aPrefix.get(), out); michael@0: michael@0: fputs(NS_LossyConvertUTF16toASCII(mNodeInfo->QualifiedName()).get(), out); michael@0: michael@0: fprintf(out, "@%p", (void *)this); michael@0: michael@0: ListAttributes(out); michael@0: michael@0: fprintf(out, " state=[%llx]", michael@0: static_cast(State().GetInternalValue())); michael@0: fprintf(out, " flags=[%08x]", static_cast(GetFlags())); michael@0: if (IsCommonAncestorForRangeInSelection()) { michael@0: nsRange::RangeHashTable* ranges = michael@0: static_cast(GetProperty(nsGkAtoms::range)); michael@0: fprintf(out, " ranges:%d", ranges ? ranges->Count() : 0); michael@0: } michael@0: fprintf(out, " primaryframe=%p", static_cast(GetPrimaryFrame())); michael@0: fprintf(out, " refcount=%" PRIuPTR "<", mRefCnt.get()); michael@0: michael@0: nsIContent* child = GetFirstChild(); michael@0: if (child) { michael@0: fputs("\n", out); michael@0: michael@0: for (; child; child = child->GetNextSibling()) { michael@0: child->List(out, aIndent + 1); michael@0: } michael@0: michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: } michael@0: michael@0: fputs(">\n", out); michael@0: michael@0: Element* nonConstThis = const_cast(this); michael@0: michael@0: // XXX sXBL/XBL2 issue! Owner or current document? michael@0: nsIDocument *document = OwnerDoc(); michael@0: michael@0: // Note: not listing nsIAnonymousContentCreator-created content... michael@0: michael@0: nsBindingManager* bindingManager = document->BindingManager(); michael@0: nsCOMPtr anonymousChildren; michael@0: bindingManager->GetAnonymousNodesFor(nonConstThis, michael@0: getter_AddRefs(anonymousChildren)); michael@0: michael@0: if (anonymousChildren) { michael@0: uint32_t length = 0; michael@0: anonymousChildren->GetLength(&length); michael@0: michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: fputs("anonymous-children<\n", out); michael@0: michael@0: for (uint32_t i = 0; i < length; ++i) { michael@0: nsCOMPtr node; michael@0: anonymousChildren->Item(i, getter_AddRefs(node)); michael@0: nsCOMPtr child = do_QueryInterface(node); michael@0: child->List(out, aIndent + 1); michael@0: } michael@0: michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: fputs(">\n", out); michael@0: michael@0: bool outHeader = false; michael@0: ExplicitChildIterator iter(nonConstThis); michael@0: for (nsIContent* child = iter.GetNextChild(); child; child = iter.GetNextChild()) { michael@0: if (!outHeader) { michael@0: outHeader = true; michael@0: michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: fputs("content-list<\n", out); michael@0: } michael@0: michael@0: child->List(out, aIndent + 1); michael@0: } michael@0: michael@0: if (outHeader) { michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: fputs(">\n", out); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: Element::DumpContent(FILE* out, int32_t aIndent, michael@0: bool aDumpAll) const michael@0: { michael@0: int32_t indent; michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: michael@0: const nsString& buf = mNodeInfo->QualifiedName(); michael@0: fputs("<", out); michael@0: fputs(NS_LossyConvertUTF16toASCII(buf).get(), out); michael@0: michael@0: if(aDumpAll) ListAttributes(out); michael@0: michael@0: fputs(">", out); michael@0: michael@0: if(aIndent) fputs("\n", out); michael@0: michael@0: for (nsIContent* child = GetFirstChild(); michael@0: child; michael@0: child = child->GetNextSibling()) { michael@0: int32_t indent = aIndent ? aIndent + 1 : 0; michael@0: child->DumpContent(out, indent, aDumpAll); michael@0: } michael@0: for (indent = aIndent; --indent >= 0; ) fputs(" ", out); michael@0: fputs("", out); michael@0: michael@0: if(aIndent) fputs("\n", out); michael@0: } michael@0: #endif michael@0: michael@0: void michael@0: Element::Describe(nsAString& aOutDescription) const michael@0: { michael@0: aOutDescription.Append(mNodeInfo->QualifiedName()); michael@0: aOutDescription.AppendPrintf("@%p", (void *)this); michael@0: michael@0: uint32_t index, count = mAttrsAndChildren.AttrCount(); michael@0: for (index = 0; index < count; index++) { michael@0: aOutDescription.Append(' '); michael@0: nsAutoString attributeDescription; michael@0: DescribeAttribute(index, attributeDescription); michael@0: aOutDescription.Append(attributeDescription); michael@0: } michael@0: } michael@0: michael@0: bool michael@0: Element::CheckHandleEventForLinksPrecondition(EventChainVisitor& aVisitor, michael@0: nsIURI** aURI) const michael@0: { michael@0: if (aVisitor.mEventStatus == nsEventStatus_eConsumeNoDefault || michael@0: (!aVisitor.mEvent->mFlags.mIsTrusted && michael@0: (aVisitor.mEvent->message != NS_MOUSE_CLICK) && michael@0: (aVisitor.mEvent->message != NS_KEY_PRESS) && michael@0: (aVisitor.mEvent->message != NS_UI_ACTIVATE)) || michael@0: !aVisitor.mPresContext || michael@0: aVisitor.mEvent->mFlags.mMultipleActionsPrevented) { michael@0: return false; michael@0: } michael@0: michael@0: // Make sure we actually are a link michael@0: return IsLink(aURI); michael@0: } michael@0: michael@0: nsresult michael@0: Element::PreHandleEventForLinks(EventChainPreVisitor& aVisitor) michael@0: { michael@0: // Optimisation: return early if this event doesn't interest us. michael@0: // IMPORTANT: this switch and the switch below it must be kept in sync! michael@0: switch (aVisitor.mEvent->message) { michael@0: case NS_MOUSE_ENTER_SYNTH: michael@0: case NS_FOCUS_CONTENT: michael@0: case NS_MOUSE_EXIT_SYNTH: michael@0: case NS_BLUR_CONTENT: michael@0: break; michael@0: default: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Make sure we meet the preconditions before continuing michael@0: nsCOMPtr absURI; michael@0: if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = NS_OK; michael@0: michael@0: // We do the status bar updates in PreHandleEvent so that the status bar gets michael@0: // updated even if the event is consumed before we have a chance to set it. michael@0: switch (aVisitor.mEvent->message) { michael@0: // Set the status bar similarly for mouseover and focus michael@0: case NS_MOUSE_ENTER_SYNTH: michael@0: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; michael@0: // FALL THROUGH michael@0: case NS_FOCUS_CONTENT: { michael@0: InternalFocusEvent* focusEvent = aVisitor.mEvent->AsFocusEvent(); michael@0: if (!focusEvent || !focusEvent->isRefocus) { michael@0: nsAutoString target; michael@0: GetLinkTarget(target); michael@0: nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target, michael@0: false, true, true); michael@0: // Make sure any ancestor links don't also TriggerLink michael@0: aVisitor.mEvent->mFlags.mMultipleActionsPrevented = true; michael@0: } michael@0: break; michael@0: } michael@0: case NS_MOUSE_EXIT_SYNTH: michael@0: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; michael@0: // FALL THROUGH michael@0: case NS_BLUR_CONTENT: michael@0: rv = LeaveLink(aVisitor.mPresContext); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: aVisitor.mEvent->mFlags.mMultipleActionsPrevented = true; michael@0: } michael@0: break; michael@0: michael@0: default: michael@0: // switch not in sync with the optimization switch earlier in this function michael@0: NS_NOTREACHED("switch statements not in sync"); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: nsresult michael@0: Element::PostHandleEventForLinks(EventChainPostVisitor& aVisitor) michael@0: { michael@0: // Optimisation: return early if this event doesn't interest us. michael@0: // IMPORTANT: this switch and the switch below it must be kept in sync! michael@0: switch (aVisitor.mEvent->message) { michael@0: case NS_MOUSE_BUTTON_DOWN: michael@0: case NS_MOUSE_CLICK: michael@0: case NS_UI_ACTIVATE: michael@0: case NS_KEY_PRESS: michael@0: break; michael@0: default: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Make sure we meet the preconditions before continuing michael@0: nsCOMPtr absURI; michael@0: if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = NS_OK; michael@0: michael@0: switch (aVisitor.mEvent->message) { michael@0: case NS_MOUSE_BUTTON_DOWN: michael@0: { michael@0: if (aVisitor.mEvent->AsMouseEvent()->button == michael@0: WidgetMouseEvent::eLeftButton) { michael@0: // don't make the link grab the focus if there is no link handler michael@0: nsILinkHandler *handler = aVisitor.mPresContext->GetLinkHandler(); michael@0: nsIDocument *document = GetCurrentDoc(); michael@0: if (handler && document) { michael@0: nsIFocusManager* fm = nsFocusManager::GetFocusManager(); michael@0: if (fm) { michael@0: aVisitor.mEvent->mFlags.mMultipleActionsPrevented = true; michael@0: nsCOMPtr elem = do_QueryInterface(this); michael@0: fm->SetFocus(elem, nsIFocusManager::FLAG_BYMOUSE | michael@0: nsIFocusManager::FLAG_NOSCROLL); michael@0: } michael@0: michael@0: EventStateManager::SetActiveManager( michael@0: aVisitor.mPresContext->EventStateManager(), this); michael@0: } michael@0: } michael@0: } michael@0: break; michael@0: michael@0: case NS_MOUSE_CLICK: { michael@0: WidgetMouseEvent* mouseEvent = aVisitor.mEvent->AsMouseEvent(); michael@0: if (mouseEvent->IsLeftClickEvent()) { michael@0: if (mouseEvent->IsControl() || mouseEvent->IsMeta() || michael@0: mouseEvent->IsAlt() ||mouseEvent->IsShift()) { michael@0: break; michael@0: } michael@0: michael@0: // The default action is simply to dispatch DOMActivate michael@0: nsCOMPtr shell = aVisitor.mPresContext->GetPresShell(); michael@0: if (shell) { michael@0: // single-click michael@0: nsEventStatus status = nsEventStatus_eIgnore; michael@0: InternalUIEvent actEvent(mouseEvent->mFlags.mIsTrusted, NS_UI_ACTIVATE); michael@0: actEvent.detail = 1; michael@0: michael@0: rv = shell->HandleDOMEventWithTarget(this, &actEvent, &status); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; michael@0: } michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: case NS_UI_ACTIVATE: michael@0: { michael@0: if (aVisitor.mEvent->originalTarget == this) { michael@0: nsAutoString target; michael@0: GetLinkTarget(target); michael@0: nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target, michael@0: true, true, michael@0: aVisitor.mEvent->mFlags.mIsTrusted); michael@0: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; michael@0: } michael@0: } michael@0: break; michael@0: michael@0: case NS_KEY_PRESS: michael@0: { michael@0: WidgetKeyboardEvent* keyEvent = aVisitor.mEvent->AsKeyboardEvent(); michael@0: if (keyEvent && keyEvent->keyCode == NS_VK_RETURN) { michael@0: nsEventStatus status = nsEventStatus_eIgnore; michael@0: rv = DispatchClickEvent(aVisitor.mPresContext, keyEvent, this, michael@0: false, nullptr, &status); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; michael@0: } michael@0: } michael@0: } michael@0: break; michael@0: michael@0: default: michael@0: // switch not in sync with the optimization switch earlier in this function michael@0: NS_NOTREACHED("switch statements not in sync"); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: void michael@0: Element::GetLinkTarget(nsAString& aTarget) michael@0: { michael@0: aTarget.Truncate(); michael@0: } michael@0: michael@0: bool michael@0: Element::MozMatchesSelector(const nsAString& aSelector, michael@0: ErrorResult& aError) michael@0: { michael@0: nsCSSSelectorList* selectorList = ParseSelectorList(aSelector, aError); michael@0: if (!selectorList) { michael@0: // Either we failed (and aError already has the exception), or this michael@0: // is a pseudo-element-only selector that matches nothing. michael@0: return false; michael@0: } michael@0: michael@0: OwnerDoc()->FlushPendingLinkUpdates(); michael@0: TreeMatchContext matchingContext(false, michael@0: nsRuleWalker::eRelevantLinkUnvisited, michael@0: OwnerDoc(), michael@0: TreeMatchContext::eNeverMatchVisited); michael@0: matchingContext.SetHasSpecifiedScope(); michael@0: matchingContext.AddScopeElement(this); michael@0: return nsCSSRuleProcessor::SelectorListMatches(this, matchingContext, michael@0: selectorList); michael@0: } michael@0: michael@0: static const nsAttrValue::EnumTable kCORSAttributeTable[] = { michael@0: // Order matters here michael@0: // See ParseCORSValue michael@0: { "anonymous", CORS_ANONYMOUS }, michael@0: { "use-credentials", CORS_USE_CREDENTIALS }, michael@0: { 0 } michael@0: }; michael@0: michael@0: /* static */ void michael@0: Element::ParseCORSValue(const nsAString& aValue, michael@0: nsAttrValue& aResult) michael@0: { michael@0: DebugOnly success = michael@0: aResult.ParseEnumValue(aValue, kCORSAttributeTable, false, michael@0: // default value is anonymous if aValue is michael@0: // not a value we understand michael@0: &kCORSAttributeTable[0]); michael@0: MOZ_ASSERT(success); michael@0: } michael@0: michael@0: /* static */ CORSMode michael@0: Element::StringToCORSMode(const nsAString& aValue) michael@0: { michael@0: if (aValue.IsVoid()) { michael@0: return CORS_NONE; michael@0: } michael@0: michael@0: nsAttrValue val; michael@0: Element::ParseCORSValue(aValue, val); michael@0: return CORSMode(val.GetEnumValue()); michael@0: } michael@0: michael@0: /* static */ CORSMode michael@0: Element::AttrValueToCORSMode(const nsAttrValue* aValue) michael@0: { michael@0: if (!aValue) { michael@0: return CORS_NONE; michael@0: } michael@0: michael@0: return CORSMode(aValue->GetEnumValue()); michael@0: } michael@0: michael@0: static const char* michael@0: GetFullScreenError(nsIDocument* aDoc) michael@0: { michael@0: // Block fullscreen requests in the chrome document when the fullscreen API michael@0: // is configured for content only. michael@0: if (nsContentUtils::IsFullscreenApiContentOnly() && michael@0: nsContentUtils::IsChromeDoc(aDoc)) { michael@0: return "FullScreenDeniedContentOnly"; michael@0: } michael@0: michael@0: nsCOMPtr win = aDoc->GetWindow(); michael@0: if (aDoc->NodePrincipal()->GetAppStatus() >= nsIPrincipal::APP_STATUS_INSTALLED) { michael@0: // Request is in a web app and in the same origin as the web app. michael@0: // Don't enforce as strict security checks for web apps, the user michael@0: // is supposed to have trust in them. However documents cross-origin michael@0: // to the web app must still confirm to the normal security checks. michael@0: return nullptr; michael@0: } michael@0: michael@0: if (!nsContentUtils::IsRequestFullScreenAllowed()) { michael@0: return "FullScreenDeniedNotInputDriven"; michael@0: } michael@0: michael@0: if (nsContentUtils::IsSitePermDeny(aDoc->NodePrincipal(), "fullscreen")) { michael@0: return "FullScreenDeniedBlocked"; michael@0: } michael@0: michael@0: return nullptr; michael@0: } michael@0: michael@0: void michael@0: Element::MozRequestFullScreen() michael@0: { michael@0: // Only grant full-screen requests if this is called from inside a trusted michael@0: // event handler (i.e. inside an event handler for a user initiated event). michael@0: // This stops the full-screen from being abused similar to the popups of old, michael@0: // and it also makes it harder for bad guys' script to go full-screen and michael@0: // spoof the browser chrome/window and phish logins etc. michael@0: // Note that requests for fullscreen inside a web app's origin are exempt michael@0: // from this restriction. michael@0: const char* error = GetFullScreenError(OwnerDoc()); michael@0: if (error) { michael@0: nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, michael@0: NS_LITERAL_CSTRING("DOM"), OwnerDoc(), michael@0: nsContentUtils::eDOM_PROPERTIES, michael@0: error); michael@0: nsRefPtr asyncDispatcher = michael@0: new AsyncEventDispatcher(OwnerDoc(), michael@0: NS_LITERAL_STRING("mozfullscreenerror"), michael@0: true, michael@0: false); michael@0: asyncDispatcher->PostDOMEvent(); michael@0: return; michael@0: } michael@0: michael@0: OwnerDoc()->AsyncRequestFullScreen(this); michael@0: michael@0: return; michael@0: } michael@0: michael@0: void michael@0: Element::MozRequestPointerLock() michael@0: { michael@0: OwnerDoc()->RequestPointerLock(this); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: Element::GetInnerHTML(nsAString& aInnerHTML) michael@0: { michael@0: GetMarkup(false, aInnerHTML); michael@0: return NS_OK; michael@0: } michael@0: michael@0: void michael@0: Element::SetInnerHTML(const nsAString& aInnerHTML, ErrorResult& aError) michael@0: { michael@0: SetInnerHTMLInternal(aInnerHTML, aError); michael@0: } michael@0: michael@0: void michael@0: Element::GetOuterHTML(nsAString& aOuterHTML) michael@0: { michael@0: GetMarkup(true, aOuterHTML); michael@0: } michael@0: michael@0: void michael@0: Element::SetOuterHTML(const nsAString& aOuterHTML, ErrorResult& aError) michael@0: { michael@0: nsCOMPtr parent = GetParentNode(); michael@0: if (!parent) { michael@0: return; michael@0: } michael@0: michael@0: if (parent->NodeType() == nsIDOMNode::DOCUMENT_NODE) { michael@0: aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR); michael@0: return; michael@0: } michael@0: michael@0: if (OwnerDoc()->IsHTML()) { michael@0: nsIAtom* localName; michael@0: int32_t namespaceID; michael@0: if (parent->IsElement()) { michael@0: localName = static_cast(parent.get())->Tag(); michael@0: namespaceID = static_cast(parent.get())->GetNameSpaceID(); michael@0: } else { michael@0: NS_ASSERTION(parent->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE, michael@0: "How come the parent isn't a document, a fragment or an element?"); michael@0: localName = nsGkAtoms::body; michael@0: namespaceID = kNameSpaceID_XHTML; michael@0: } michael@0: nsRefPtr fragment = michael@0: new DocumentFragment(OwnerDoc()->NodeInfoManager()); michael@0: nsContentUtils::ParseFragmentHTML(aOuterHTML, michael@0: fragment, michael@0: localName, michael@0: namespaceID, michael@0: OwnerDoc()->GetCompatibilityMode() == michael@0: eCompatibility_NavQuirks, michael@0: true); michael@0: parent->ReplaceChild(*fragment, *this, aError); michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr context; michael@0: if (parent->IsElement()) { michael@0: context = parent; michael@0: } else { michael@0: NS_ASSERTION(parent->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE, michael@0: "How come the parent isn't a document, a fragment or an element?"); michael@0: nsCOMPtr info = michael@0: OwnerDoc()->NodeInfoManager()->GetNodeInfo(nsGkAtoms::body, michael@0: nullptr, michael@0: kNameSpaceID_XHTML, michael@0: nsIDOMNode::ELEMENT_NODE); michael@0: context = NS_NewHTMLBodyElement(info.forget(), FROM_PARSER_FRAGMENT); michael@0: } michael@0: michael@0: nsCOMPtr df; michael@0: aError = nsContentUtils::CreateContextualFragment(context, michael@0: aOuterHTML, michael@0: true, michael@0: getter_AddRefs(df)); michael@0: if (aError.Failed()) { michael@0: return; michael@0: } michael@0: nsCOMPtr fragment = do_QueryInterface(df); michael@0: parent->ReplaceChild(*fragment, *this, aError); michael@0: } michael@0: michael@0: enum nsAdjacentPosition { michael@0: eBeforeBegin, michael@0: eAfterBegin, michael@0: eBeforeEnd, michael@0: eAfterEnd michael@0: }; michael@0: michael@0: void michael@0: Element::InsertAdjacentHTML(const nsAString& aPosition, const nsAString& aText, michael@0: ErrorResult& aError) michael@0: { michael@0: nsAdjacentPosition position; michael@0: if (aPosition.LowerCaseEqualsLiteral("beforebegin")) { michael@0: position = eBeforeBegin; michael@0: } else if (aPosition.LowerCaseEqualsLiteral("afterbegin")) { michael@0: position = eAfterBegin; michael@0: } else if (aPosition.LowerCaseEqualsLiteral("beforeend")) { michael@0: position = eBeforeEnd; michael@0: } else if (aPosition.LowerCaseEqualsLiteral("afterend")) { michael@0: position = eAfterEnd; michael@0: } else { michael@0: aError.Throw(NS_ERROR_DOM_SYNTAX_ERR); michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr destination; michael@0: if (position == eBeforeBegin || position == eAfterEnd) { michael@0: destination = GetParent(); michael@0: if (!destination) { michael@0: aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR); michael@0: return; michael@0: } michael@0: } else { michael@0: destination = this; michael@0: } michael@0: michael@0: nsIDocument* doc = OwnerDoc(); michael@0: michael@0: // Needed when insertAdjacentHTML is used in combination with contenteditable michael@0: mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, true); michael@0: nsAutoScriptLoaderDisabler sld(doc); michael@0: michael@0: // Batch possible DOMSubtreeModified events. michael@0: mozAutoSubtreeModified subtree(doc, nullptr); michael@0: michael@0: // Parse directly into destination if possible michael@0: if (doc->IsHTML() && !OwnerDoc()->MayHaveDOMMutationObservers() && michael@0: (position == eBeforeEnd || michael@0: (position == eAfterEnd && !GetNextSibling()) || michael@0: (position == eAfterBegin && !GetFirstChild()))) { michael@0: int32_t oldChildCount = destination->GetChildCount(); michael@0: int32_t contextNs = destination->GetNameSpaceID(); michael@0: nsIAtom* contextLocal = destination->Tag(); michael@0: if (contextLocal == nsGkAtoms::html && contextNs == kNameSpaceID_XHTML) { michael@0: // For compat with IE6 through IE9. Willful violation of HTML5 as of michael@0: // 2011-04-06. CreateContextualFragment does the same already. michael@0: // Spec bug: http://www.w3.org/Bugs/Public/show_bug.cgi?id=12434 michael@0: contextLocal = nsGkAtoms::body; michael@0: } michael@0: aError = nsContentUtils::ParseFragmentHTML(aText, michael@0: destination, michael@0: contextLocal, michael@0: contextNs, michael@0: doc->GetCompatibilityMode() == michael@0: eCompatibility_NavQuirks, michael@0: true); michael@0: // HTML5 parser has notified, but not fired mutation events. michael@0: nsContentUtils::FireMutationEventsForDirectParsing(doc, destination, michael@0: oldChildCount); michael@0: return; michael@0: } michael@0: michael@0: // couldn't parse directly michael@0: nsCOMPtr df; michael@0: aError = nsContentUtils::CreateContextualFragment(destination, michael@0: aText, michael@0: true, michael@0: getter_AddRefs(df)); michael@0: if (aError.Failed()) { michael@0: return; michael@0: } michael@0: michael@0: nsCOMPtr fragment = do_QueryInterface(df); michael@0: michael@0: // Suppress assertion about node removal mutation events that can't have michael@0: // listeners anyway, because no one has had the chance to register mutation michael@0: // listeners on the fragment that comes from the parser. michael@0: nsAutoScriptBlockerSuppressNodeRemoved scriptBlocker; michael@0: michael@0: nsAutoMutationBatch mb(destination, true, false); michael@0: switch (position) { michael@0: case eBeforeBegin: michael@0: destination->InsertBefore(*fragment, this, aError); michael@0: break; michael@0: case eAfterBegin: michael@0: static_cast(this)->InsertBefore(*fragment, GetFirstChild(), michael@0: aError); michael@0: break; michael@0: case eBeforeEnd: michael@0: static_cast(this)->AppendChild(*fragment, aError); michael@0: break; michael@0: case eAfterEnd: michael@0: destination->InsertBefore(*fragment, GetNextSibling(), aError); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: nsIEditor* michael@0: Element::GetEditorInternal() michael@0: { michael@0: nsCOMPtr textCtrl = do_QueryInterface(this); michael@0: return textCtrl ? textCtrl->GetTextEditor() : nullptr; michael@0: } michael@0: michael@0: nsresult michael@0: Element::SetBoolAttr(nsIAtom* aAttr, bool aValue) michael@0: { michael@0: if (aValue) { michael@0: return SetAttr(kNameSpaceID_None, aAttr, EmptyString(), true); michael@0: } michael@0: michael@0: return UnsetAttr(kNameSpaceID_None, aAttr, true); michael@0: } michael@0: michael@0: Directionality michael@0: Element::GetComputedDirectionality() const michael@0: { michael@0: nsIFrame* frame = GetPrimaryFrame(); michael@0: if (frame) { michael@0: return frame->StyleVisibility()->mDirection == NS_STYLE_DIRECTION_LTR michael@0: ? eDir_LTR : eDir_RTL; michael@0: } michael@0: michael@0: return GetDirectionality(); michael@0: } michael@0: michael@0: float michael@0: Element::FontSizeInflation() michael@0: { michael@0: nsIFrame* frame = GetPrimaryFrame(); michael@0: if (!frame) { michael@0: return -1.0; michael@0: } michael@0: michael@0: if (nsLayoutUtils::FontSizeInflationEnabled(frame->PresContext())) { michael@0: return nsLayoutUtils::FontSizeInflationFor(frame); michael@0: } michael@0: michael@0: return 1.0; michael@0: }