1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=79: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * Base class for all element classes; this provides an implementation
9 * of DOM Core's nsIDOMElement, implements nsIContent, provides
10 * utility methods for subclasses, and so forth.
13 #include "mozilla/dom/ElementInlines.h"
15 #include "AnimationCommon.h"
16 #include "mozilla/DebugOnly.h"
17 #include "mozilla/dom/AnimationPlayer.h"
18 #include "mozilla/dom/Attr.h"
19 #include "nsDOMAttributeMap.h"
21 #include "nsIContentInlines.h"
22 #include "mozilla/dom/NodeInfo.h"
23 #include "nsIDocumentInlines.h"
24 #include "nsIDOMNodeList.h"
25 #include "nsIDOMDocument.h"
26 #include "nsIContentIterator.h"
27 #include "nsFocusManager.h"
28 #include "nsFrameManager.h"
29 #include "nsILinkHandler.h"
30 #include "nsIScriptGlobalObject.h"
32 #include "nsNetUtil.h"
33 #include "nsContainerFrame.h"
34 #include "nsIAnonymousContentCreator.h"
35 #include "nsIPresShell.h"
36 #include "nsPresContext.h"
37 #include "nsStyleConsts.h"
39 #include "nsUnicharUtils.h"
40 #include "nsIDOMEvent.h"
42 #include "nsIServiceManager.h"
43 #include "nsIDOMCSSStyleDeclaration.h"
44 #include "nsDOMCSSAttrDeclaration.h"
45 #include "nsNameSpaceManager.h"
46 #include "nsContentList.h"
47 #include "nsVariant.h"
48 #include "nsDOMSettableTokenList.h"
49 #include "nsDOMTokenList.h"
50 #include "nsXBLPrototypeBinding.h"
52 #include "nsDOMString.h"
53 #include "nsIScriptSecurityManager.h"
54 #include "nsIDOMMutationEvent.h"
55 #include "mozilla/AsyncEventDispatcher.h"
56 #include "mozilla/ContentEvents.h"
57 #include "mozilla/EventDispatcher.h"
58 #include "mozilla/EventListenerManager.h"
59 #include "mozilla/EventStateManager.h"
60 #include "mozilla/EventStates.h"
61 #include "mozilla/InternalMutationEvent.h"
62 #include "mozilla/MouseEvents.h"
63 #include "mozilla/TextEvents.h"
64 #include "nsNodeUtils.h"
65 #include "mozilla/dom/DirectionalityUtils.h"
66 #include "nsDocument.h"
67 #include "nsAttrValueOrString.h"
68 #include "nsAttrValueInlines.h"
70 #include "nsXULElement.h"
72 #include "nsSVGElement.h"
73 #include "nsFrameSelection.h"
78 #include "nsBindingManager.h"
79 #include "nsXBLBinding.h"
80 #include "nsPIDOMWindow.h"
81 #include "nsPIBoxObject.h"
82 #include "mozilla/dom/DOMRect.h"
83 #include "nsSVGUtils.h"
84 #include "nsLayoutUtils.h"
85 #include "nsGkAtoms.h"
86 #include "nsContentUtils.h"
87 #include "ChildIterator.h"
89 #include "nsIDOMEventListener.h"
90 #include "nsIWebNavigation.h"
91 #include "nsIBaseWindow.h"
92 #include "nsIWidget.h"
94 #include "nsNodeInfoManager.h"
95 #include "nsICategoryManager.h"
96 #include "nsIDOMDocumentType.h"
97 #include "nsGenericHTMLElement.h"
98 #include "nsIEditor.h"
99 #include "nsIEditorIMESupport.h"
100 #include "nsContentCreatorFunctions.h"
101 #include "nsIControllers.h"
103 #include "nsViewManager.h"
104 #include "nsIScrollableFrame.h"
105 #include "mozilla/css/StyleRule.h" /* For nsCSSSelectorList */
106 #include "nsCSSRuleProcessor.h"
107 #include "nsRuleProcessorData.h"
108 #include "nsTextNode.h"
111 #include "nsIXULDocument.h"
114 #include "nsCycleCollectionParticipant.h"
115 #include "nsCCUncollectableMarker.h"
117 #include "mozAutoDocUpdate.h"
119 #include "nsCSSParser.h"
121 #include "nsDOMMutationObserver.h"
122 #include "nsSVGFeatures.h"
123 #include "nsWrapperCacheInlines.h"
124 #include "xpcpublic.h"
125 #include "nsIScriptError.h"
126 #include "mozilla/Telemetry.h"
128 #include "mozilla/CORSMode.h"
129 #include "mozilla/dom/ShadowRoot.h"
130 #include "mozilla/dom/NodeListBinding.h"
132 #include "nsStyledElement.h"
133 #include "nsXBLService.h"
134 #include "nsITextControlElement.h"
135 #include "nsITextControlFrame.h"
136 #include "nsISupportsImpl.h"
137 #include "mozilla/dom/DocumentFragment.h"
138 #include "mozilla/IntegerPrintfMacros.h"
139 #include "mozilla/dom/WindowBinding.h"
140 #include "mozilla/dom/ElementBinding.h"
141 #include "mozilla/dom/VRDevice.h"
143 using namespace mozilla
;
144 using namespace mozilla::dom
;
147 nsIContent::DoGetID() const
149 MOZ_ASSERT(HasID(), "Unexpected call");
150 MOZ_ASSERT(IsElement(), "Only elements can have IDs");
152 return AsElement()->GetParsedAttr(nsGkAtoms::id
)->GetAtomValue();
156 nsIContent::DoGetClasses() const
158 MOZ_ASSERT(HasFlag(NODE_MAY_HAVE_CLASS
), "Unexpected call");
159 MOZ_ASSERT(IsElement(), "Only elements can have classes");
162 const nsAttrValue
* animClass
=
163 static_cast<const nsSVGElement
*>(this)->GetAnimatedClassName();
169 return AsElement()->GetParsedAttr(nsGkAtoms::_class
);
173 Element::QueryInterface(REFNSIID aIID
, void** aInstancePtr
)
175 NS_ASSERTION(aInstancePtr
,
176 "QueryInterface requires a non-NULL destination!");
177 nsresult rv
= FragmentOrElement::QueryInterface(aIID
, aInstancePtr
);
178 if (NS_SUCCEEDED(rv
)) {
182 // Give the binding manager a chance to get an interface for this element.
183 return OwnerDoc()->BindingManager()->GetBindingImplementation(this, aIID
,
188 Element::IntrinsicState() const
190 return IsEditable() ? NS_EVENT_STATE_MOZ_READWRITE
:
191 NS_EVENT_STATE_MOZ_READONLY
;
195 Element::NotifyStateChange(EventStates aStates
)
197 nsIDocument
* doc
= GetCrossShadowCurrentDoc();
199 nsAutoScriptBlocker scriptBlocker
;
200 doc
->ContentStateChanged(this, aStates
);
205 Element::UpdateLinkState(EventStates aState
)
207 NS_ABORT_IF_FALSE(!aState
.HasAtLeastOneOfStates(~(NS_EVENT_STATE_VISITED
|
208 NS_EVENT_STATE_UNVISITED
)),
209 "Unexpected link state bits");
211 (mState
& ~(NS_EVENT_STATE_VISITED
| NS_EVENT_STATE_UNVISITED
)) |
216 Element::UpdateState(bool aNotify
)
218 EventStates oldState
= mState
;
219 mState
= IntrinsicState() | (oldState
& ESM_MANAGED_STATES
);
221 EventStates changedStates
= oldState
^ mState
;
222 if (!changedStates
.IsEmpty()) {
223 nsIDocument
* doc
= GetCrossShadowCurrentDoc();
225 nsAutoScriptBlocker scriptBlocker
;
226 doc
->ContentStateChanged(this, changedStates
);
233 nsIContent::UpdateEditableState(bool aNotify
)
235 // Guaranteed to be non-element content
236 NS_ASSERTION(!IsElement(), "What happened here?");
237 nsIContent
*parent
= GetParent();
239 // Skip over unknown native anonymous content to avoid setting a flag we
241 bool isUnknownNativeAnon
= false;
242 if (IsInNativeAnonymousSubtree()) {
243 isUnknownNativeAnon
= true;
244 nsCOMPtr
<nsIContent
> root
= this;
245 while (root
&& !root
->IsRootOfNativeAnonymousSubtree()) {
246 root
= root
->GetParent();
248 // root should always be true here, but isn't -- bug 999416
250 nsIFrame
* rootFrame
= root
->GetPrimaryFrame();
252 nsContainerFrame
* parentFrame
= rootFrame
->GetParent();
253 nsITextControlFrame
* textCtrl
= do_QueryFrame(parentFrame
);
254 isUnknownNativeAnon
= !textCtrl
;
259 SetEditableFlag(parent
&& parent
->HasFlag(NODE_IS_EDITABLE
) &&
260 !isUnknownNativeAnon
);
264 Element::UpdateEditableState(bool aNotify
)
266 nsIContent
*parent
= GetParent();
268 SetEditableFlag(parent
&& parent
->HasFlag(NODE_IS_EDITABLE
));
270 UpdateState(aNotify
);
272 // Avoid calling UpdateState in this very common case, because
273 // this gets called for pretty much every single element on
274 // insertion into the document and UpdateState can be slow for
275 // some kinds of elements even when not notifying.
277 RemoveStatesSilently(NS_EVENT_STATE_MOZ_READONLY
);
278 AddStatesSilently(NS_EVENT_STATE_MOZ_READWRITE
);
280 RemoveStatesSilently(NS_EVENT_STATE_MOZ_READWRITE
);
281 AddStatesSilently(NS_EVENT_STATE_MOZ_READONLY
);
287 Element::StyleStateFromLocks() const
289 EventStates locks
= LockedStyleStates();
290 EventStates state
= mState
| locks
;
292 if (locks
.HasState(NS_EVENT_STATE_VISITED
)) {
293 return state
& ~NS_EVENT_STATE_UNVISITED
;
295 if (locks
.HasState(NS_EVENT_STATE_UNVISITED
)) {
296 return state
& ~NS_EVENT_STATE_VISITED
;
302 Element::LockedStyleStates() const
305 static_cast<EventStates
*>(GetProperty(nsGkAtoms::lockedStyleStates
));
309 return EventStates();
313 Element::NotifyStyleStateChange(EventStates aStates
)
315 nsIDocument
* doc
= GetComposedDoc();
317 nsIPresShell
*presShell
= doc
->GetShell();
319 nsAutoScriptBlocker scriptBlocker
;
320 presShell
->ContentStateChanged(doc
, this, aStates
);
326 Element::LockStyleStates(EventStates aStates
)
328 EventStates
* locks
= new EventStates(LockedStyleStates());
332 if (aStates
.HasState(NS_EVENT_STATE_VISITED
)) {
333 *locks
&= ~NS_EVENT_STATE_UNVISITED
;
335 if (aStates
.HasState(NS_EVENT_STATE_UNVISITED
)) {
336 *locks
&= ~NS_EVENT_STATE_VISITED
;
339 SetProperty(nsGkAtoms::lockedStyleStates
, locks
,
340 nsINode::DeleteProperty
<EventStates
>);
341 SetHasLockedStyleStates();
343 NotifyStyleStateChange(aStates
);
347 Element::UnlockStyleStates(EventStates aStates
)
349 EventStates
* locks
= new EventStates(LockedStyleStates());
353 if (locks
->IsEmpty()) {
354 DeleteProperty(nsGkAtoms::lockedStyleStates
);
355 ClearHasLockedStyleStates();
359 SetProperty(nsGkAtoms::lockedStyleStates
, locks
,
360 nsINode::DeleteProperty
<EventStates
>);
363 NotifyStyleStateChange(aStates
);
367 Element::ClearStyleStateLocks()
369 EventStates locks
= LockedStyleStates();
371 DeleteProperty(nsGkAtoms::lockedStyleStates
);
372 ClearHasLockedStyleStates();
374 NotifyStyleStateChange(locks
);
378 Element::GetBindingURL(nsIDocument
*aDocument
, css::URLValue
**aResult
)
380 // If we have a frame the frame has already loaded the binding. And
381 // otherwise, don't do anything else here unless we're dealing with
382 // XUL or an HTML element that may have a plugin-related overlay
383 // (i.e. object, embed, or applet).
384 bool isXULorPluginElement
= (IsXUL() ||
385 IsHTML(nsGkAtoms::object
) ||
386 IsHTML(nsGkAtoms::embed
) ||
387 IsHTML(nsGkAtoms::applet
));
388 nsIPresShell
*shell
= aDocument
->GetShell();
389 if (!shell
|| GetPrimaryFrame() || !isXULorPluginElement
) {
395 // Get the computed -moz-binding directly from the style context
396 nsPresContext
*pctx
= shell
->GetPresContext();
397 NS_ENSURE_TRUE(pctx
, false);
399 nsRefPtr
<nsStyleContext
> sc
= pctx
->StyleSet()->ResolveStyleFor(this,
401 NS_ENSURE_TRUE(sc
, false);
403 *aResult
= sc
->StyleDisplay()->mBinding
;
409 Element::WrapObject(JSContext
*aCx
)
411 JS::Rooted
<JSObject
*> obj(aCx
, nsINode::WrapObject(aCx
));
416 // Custom element prototype swizzling.
417 CustomElementData
* data
= GetCustomElementData();
419 // If this is a registered custom element then fix the prototype.
420 JSAutoCompartment
ac(aCx
, obj
);
421 nsDocument
* document
= static_cast<nsDocument
*>(OwnerDoc());
422 JS::Rooted
<JSObject
*> prototype(aCx
);
423 document
->GetCustomPrototype(NodeInfo()->NamespaceID(), data
->mType
, &prototype
);
425 if (!JS_WrapObject(aCx
, &prototype
) || !JS_SetPrototype(aCx
, obj
, prototype
)) {
426 dom::Throw(aCx
, NS_ERROR_FAILURE
);
433 if (HasFlag(NODE_FORCE_XBL_BINDINGS
)) {
437 doc
= GetComposedDoc();
441 // There's no baseclass that cares about this call so we just
446 // We must ensure that the XBL Binding is installed before we hand
449 if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR
) && GetXBLBinding()) {
450 // There's already a binding for this element so nothing left to
453 // In theory we could call ExecuteAttachedHandler here when it's safe to
454 // run script if we also removed the binding from the PAQ queue, but that
455 // seems like a scary change that would mosly just add more
460 // Make sure the style context goes away _before_ we load the binding
461 // since that can destroy the relevant presshell.
462 mozilla::css::URLValue
*bindingURL
;
463 bool ok
= GetBindingURL(doc
, &bindingURL
);
465 dom::Throw(aCx
, NS_ERROR_FAILURE
);
470 // No binding, nothing left to do here.
474 nsCOMPtr
<nsIURI
> uri
= bindingURL
->GetURI();
475 nsCOMPtr
<nsIPrincipal
> principal
= bindingURL
->mOriginPrincipal
;
477 // We have a binding that must be installed.
480 nsXBLService
* xblService
= nsXBLService::GetInstance();
482 dom::Throw(aCx
, NS_ERROR_NOT_AVAILABLE
);
487 // Make a scope so that ~nsRefPtr can GC before returning obj.
488 nsRefPtr
<nsXBLBinding
> binding
;
489 xblService
->LoadBindings(this, uri
, principal
, getter_AddRefs(binding
), &dummy
);
492 if (nsContentUtils::IsSafeToRunScript()) {
493 binding
->ExecuteAttachedHandler();
496 nsContentUtils::AddScriptRunner(
497 NS_NewRunnableMethod(binding
, &nsXBLBinding::ExecuteAttachedHandler
));
507 Element::GetScopeChainParent() const
515 Element::nsDOMSlots
* slots
= DOMSlots();
517 if (!slots
->mClassList
) {
518 slots
->mClassList
= new nsDOMTokenList(this, nsGkAtoms::_class
);
521 return slots
->mClassList
;
525 Element::GetClassList(nsISupports
** aClassList
)
527 NS_ADDREF(*aClassList
= ClassList());
530 already_AddRefed
<nsIHTMLCollection
>
531 Element::GetElementsByTagName(const nsAString
& aLocalName
)
533 return NS_GetContentList(this, kNameSpaceID_Unknown
, aLocalName
);
537 Element::GetElementsByTagName(const nsAString
& aLocalName
,
538 nsIDOMHTMLCollection
** aResult
)
540 *aResult
= GetElementsByTagName(aLocalName
).take();
544 Element::GetStyledFrame()
546 nsIFrame
*frame
= GetPrimaryFrame(Flush_Layout
);
547 return frame
? nsLayoutUtils::GetStyleFrame(frame
) : nullptr;
551 Element::GetScrollFrame(nsIFrame
**aStyledFrame
, bool aFlushLayout
)
553 // it isn't clear what to return for SVG nodes, so just return nothing
556 *aStyledFrame
= nullptr;
561 // Inline version of GetStyledFrame to use Flush_None if needed.
562 nsIFrame
* frame
= GetPrimaryFrame(aFlushLayout
? Flush_Layout
: Flush_None
);
564 frame
= nsLayoutUtils::GetStyleFrame(frame
);
568 *aStyledFrame
= frame
;
574 // menu frames implement GetScrollTargetFrame but we don't want
575 // to use it here. Similar for comboboxes.
576 nsIAtom
* type
= frame
->GetType();
577 if (type
!= nsGkAtoms::menuFrame
&& type
!= nsGkAtoms::comboboxControlFrame
) {
578 nsIScrollableFrame
*scrollFrame
= frame
->GetScrollTargetFrame();
583 nsIDocument
* doc
= OwnerDoc();
584 bool quirksMode
= doc
->GetCompatibilityMode() == eCompatibility_NavQuirks
;
585 Element
* elementWithRootScrollInfo
=
586 quirksMode
? doc
->GetBodyElement() : doc
->GetRootElement();
587 if (this == elementWithRootScrollInfo
) {
588 // In quirks mode, the scroll info for the body element should map to the
589 // root scrollable frame.
590 // In strict mode, the scroll info for the root element should map to the
591 // the root scrollable frame.
592 return frame
->PresContext()->PresShell()->GetRootScrollFrameAsScrollable();
599 Element::ScrollIntoView()
601 ScrollIntoView(ScrollIntoViewOptions());
605 Element::ScrollIntoView(bool aTop
)
607 ScrollIntoViewOptions options
;
609 options
.mBlock
= ScrollLogicalPosition::End
;
611 ScrollIntoView(options
);
615 Element::ScrollIntoView(const ScrollIntoViewOptions
&aOptions
)
617 nsIDocument
*document
= GetComposedDoc();
622 // Get the presentation shell
623 nsCOMPtr
<nsIPresShell
> presShell
= document
->GetShell();
628 int16_t vpercent
= (aOptions
.mBlock
== ScrollLogicalPosition::Start
)
629 ? nsIPresShell::SCROLL_TOP
630 : nsIPresShell::SCROLL_BOTTOM
;
632 uint32_t flags
= nsIPresShell::SCROLL_OVERFLOW_HIDDEN
;
633 if (aOptions
.mBehavior
== ScrollBehavior::Smooth
) {
634 flags
|= nsIPresShell::SCROLL_SMOOTH
;
635 } else if (aOptions
.mBehavior
== ScrollBehavior::Auto
) {
636 flags
|= nsIPresShell::SCROLL_SMOOTH_AUTO
;
639 presShell
->ScrollContentIntoView(this,
640 nsIPresShell::ScrollAxis(
642 nsIPresShell::SCROLL_ALWAYS
),
643 nsIPresShell::ScrollAxis(),
648 Element::Scroll(const CSSIntPoint
& aScroll
, const ScrollOptions
& aOptions
)
650 nsIScrollableFrame
* sf
= GetScrollFrame();
652 nsIScrollableFrame::ScrollMode scrollMode
= nsIScrollableFrame::INSTANT
;
653 if (aOptions
.mBehavior
== ScrollBehavior::Smooth
) {
654 scrollMode
= nsIScrollableFrame::SMOOTH_MSD
;
655 } else if (aOptions
.mBehavior
== ScrollBehavior::Auto
) {
656 ScrollbarStyles styles
= sf
->GetScrollbarStyles();
657 if (styles
.mScrollBehavior
== NS_STYLE_SCROLL_BEHAVIOR_SMOOTH
) {
658 scrollMode
= nsIScrollableFrame::SMOOTH_MSD
;
662 sf
->ScrollToCSSPixels(aScroll
, scrollMode
);
667 Element::Scroll(double aXScroll
, double aYScroll
)
669 // Convert -Inf, Inf, and NaN to 0; otherwise, convert by C-style cast.
670 CSSIntPoint
scrollPos(mozilla::ToZeroIfNonfinite(aXScroll
),
671 mozilla::ToZeroIfNonfinite(aYScroll
));
673 Scroll(scrollPos
, ScrollOptions());
677 Element::Scroll(const ScrollToOptions
& aOptions
)
679 nsIScrollableFrame
*sf
= GetScrollFrame();
681 CSSIntPoint scrollPos
= sf
->GetScrollPositionCSSPixels();
682 if (aOptions
.mLeft
.WasPassed()) {
683 scrollPos
.x
= mozilla::ToZeroIfNonfinite(aOptions
.mLeft
.Value());
685 if (aOptions
.mTop
.WasPassed()) {
686 scrollPos
.y
= mozilla::ToZeroIfNonfinite(aOptions
.mTop
.Value());
688 Scroll(scrollPos
, aOptions
);
693 Element::ScrollTo(double aXScroll
, double aYScroll
)
695 Scroll(aXScroll
, aYScroll
);
699 Element::ScrollTo(const ScrollToOptions
& aOptions
)
705 Element::ScrollBy(double aXScrollDif
, double aYScrollDif
)
707 nsIScrollableFrame
*sf
= GetScrollFrame();
709 CSSIntPoint scrollPos
= sf
->GetScrollPositionCSSPixels();
710 scrollPos
+= CSSIntPoint(mozilla::ToZeroIfNonfinite(aXScrollDif
),
711 mozilla::ToZeroIfNonfinite(aYScrollDif
));
712 Scroll(scrollPos
, ScrollOptions());
717 Element::ScrollBy(const ScrollToOptions
& aOptions
)
719 nsIScrollableFrame
*sf
= GetScrollFrame();
721 CSSIntPoint scrollPos
= sf
->GetScrollPositionCSSPixels();
722 if (aOptions
.mLeft
.WasPassed()) {
723 scrollPos
.x
+= mozilla::ToZeroIfNonfinite(aOptions
.mLeft
.Value());
725 if (aOptions
.mTop
.WasPassed()) {
726 scrollPos
.y
+= mozilla::ToZeroIfNonfinite(aOptions
.mTop
.Value());
728 Scroll(scrollPos
, aOptions
);
735 nsIScrollableFrame
* sf
= GetScrollFrame();
736 return sf
? sf
->GetScrollPositionCSSPixels().y
: 0;
740 Element::SetScrollTop(int32_t aScrollTop
)
742 nsIScrollableFrame
* sf
= GetScrollFrame();
744 nsIScrollableFrame::ScrollMode scrollMode
= nsIScrollableFrame::INSTANT
;
745 if (sf
->GetScrollbarStyles().mScrollBehavior
== NS_STYLE_SCROLL_BEHAVIOR_SMOOTH
) {
746 scrollMode
= nsIScrollableFrame::SMOOTH_MSD
;
748 sf
->ScrollToCSSPixels(CSSIntPoint(sf
->GetScrollPositionCSSPixels().x
,
755 Element::ScrollLeft()
757 nsIScrollableFrame
* sf
= GetScrollFrame();
758 return sf
? sf
->GetScrollPositionCSSPixels().x
: 0;
762 Element::SetScrollLeft(int32_t aScrollLeft
)
764 nsIScrollableFrame
* sf
= GetScrollFrame();
766 nsIScrollableFrame::ScrollMode scrollMode
= nsIScrollableFrame::INSTANT
;
767 if (sf
->GetScrollbarStyles().mScrollBehavior
== NS_STYLE_SCROLL_BEHAVIOR_SMOOTH
) {
768 scrollMode
= nsIScrollableFrame::SMOOTH_MSD
;
771 sf
->ScrollToCSSPixels(CSSIntPoint(aScrollLeft
,
772 sf
->GetScrollPositionCSSPixels().y
),
779 Element::ScrollByNoFlush(int32_t aDx
, int32_t aDy
)
781 nsIScrollableFrame
* sf
= GetScrollFrame(nullptr, false);
786 nsWeakFrame
weakRef(sf
->GetScrolledFrame());
788 CSSIntPoint before
= sf
->GetScrollPositionCSSPixels();
789 sf
->ScrollToCSSPixelsApproximate(CSSIntPoint(before
.x
+ aDx
, before
.y
+ aDy
));
791 // The frame was destroyed, can't keep on scrolling.
792 if (!weakRef
.IsAlive()) {
796 CSSIntPoint after
= sf
->GetScrollPositionCSSPixels();
797 return (before
!= after
);
800 static nsSize
GetScrollRectSizeForOverflowVisibleFrame(nsIFrame
* aFrame
)
806 nsRect paddingRect
= aFrame
->GetPaddingRectRelativeToSelf();
807 nsOverflowAreas
overflowAreas(paddingRect
, paddingRect
);
808 // Add the scrollable overflow areas of children (if any) to the paddingRect.
809 // It's important to start with the paddingRect, otherwise if there are no
810 // children the overflow rect will be 0,0,0,0 which will force the point 0,0
811 // to be included in the final rect.
812 nsLayoutUtils::UnionChildOverflow(aFrame
, overflowAreas
);
813 // Make sure that an empty padding-rect's edges are included, by adding
814 // the padding-rect in again with UnionEdges.
815 nsRect overflowRect
=
816 overflowAreas
.ScrollableOverflow().UnionEdges(paddingRect
);
817 return nsLayoutUtils::GetScrolledRect(aFrame
,
818 overflowRect
, paddingRect
.Size(),
819 aFrame
->StyleVisibility()->mDirection
).Size();
823 Element::ScrollHeight()
828 nsIScrollableFrame
* sf
= GetScrollFrame();
831 height
= sf
->GetScrollRange().height
+ sf
->GetScrollPortRect().height
;
833 height
= GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).height
;
836 return nsPresContext::AppUnitsToIntCSSPixels(height
);
840 Element::ScrollWidth()
845 nsIScrollableFrame
* sf
= GetScrollFrame();
848 width
= sf
->GetScrollRange().width
+ sf
->GetScrollPortRect().width
;
850 width
= GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).width
;
853 return nsPresContext::AppUnitsToIntCSSPixels(width
);
857 Element::GetClientAreaRect()
859 nsIFrame
* styledFrame
;
860 nsIScrollableFrame
* sf
= GetScrollFrame(&styledFrame
);
863 return sf
->GetScrollPortRect();
867 (styledFrame
->StyleDisplay()->mDisplay
!= NS_STYLE_DISPLAY_INLINE
||
868 styledFrame
->IsFrameOfType(nsIFrame::eReplaced
))) {
869 // Special case code to make client area work even when there isn't
870 // a scroll view, see bug 180552, bug 227567.
871 return styledFrame
->GetPaddingRect() - styledFrame
->GetPositionIgnoringScrolling();
874 // SVG nodes reach here and just return 0
875 return nsRect(0, 0, 0, 0);
878 already_AddRefed
<DOMRect
>
879 Element::GetBoundingClientRect()
881 nsRefPtr
<DOMRect
> rect
= new DOMRect(this);
883 nsIFrame
* frame
= GetPrimaryFrame(Flush_Layout
);
885 // display:none, perhaps? Return the empty rect
886 return rect
.forget();
889 nsRect r
= nsLayoutUtils::GetAllInFlowRectsUnion(frame
,
890 nsLayoutUtils::GetContainingBlockForClientRect(frame
),
891 nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS
);
892 rect
->SetLayoutRect(r
);
893 return rect
.forget();
896 already_AddRefed
<DOMRectList
>
897 Element::GetClientRects()
899 nsRefPtr
<DOMRectList
> rectList
= new DOMRectList(this);
901 nsIFrame
* frame
= GetPrimaryFrame(Flush_Layout
);
903 // display:none, perhaps? Return an empty list
904 return rectList
.forget();
907 nsLayoutUtils::RectListBuilder
builder(rectList
);
908 nsLayoutUtils::GetAllInFlowRects(frame
,
909 nsLayoutUtils::GetContainingBlockForClientRect(frame
), &builder
,
910 nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS
);
911 return rectList
.forget();
915 //----------------------------------------------------------------------
918 Element::AddToIdTable(nsIAtom
* aId
)
920 NS_ASSERTION(HasID(), "Node doesn't have an ID?");
921 if (IsInShadowTree()) {
922 ShadowRoot
* containingShadow
= GetContainingShadow();
923 containingShadow
->AddToIdTable(this, aId
);
925 nsIDocument
* doc
= GetUncomposedDoc();
926 if (doc
&& (!IsInAnonymousSubtree() || doc
->IsXUL())) {
927 doc
->AddToIdTable(this, aId
);
933 Element::RemoveFromIdTable()
939 nsIAtom
* id
= DoGetID();
940 if (IsInShadowTree()) {
941 ShadowRoot
* containingShadow
= GetContainingShadow();
942 // Check for containingShadow because it may have
943 // been deleted during unlinking.
944 if (containingShadow
) {
945 containingShadow
->RemoveFromIdTable(this, id
);
948 nsIDocument
* doc
= GetUncomposedDoc();
949 if (doc
&& (!IsInAnonymousSubtree() || doc
->IsXUL())) {
950 doc
->RemoveFromIdTable(this, id
);
955 already_AddRefed
<ShadowRoot
>
956 Element::CreateShadowRoot(ErrorResult
& aError
)
958 nsAutoScriptBlocker scriptBlocker
;
960 nsRefPtr
<mozilla::dom::NodeInfo
> nodeInfo
;
961 nodeInfo
= mNodeInfo
->NodeInfoManager()->GetNodeInfo(
962 nsGkAtoms::documentFragmentNodeName
, nullptr, kNameSpaceID_None
,
963 nsIDOMNode::DOCUMENT_FRAGMENT_NODE
);
965 nsRefPtr
<nsXBLDocumentInfo
> docInfo
= new nsXBLDocumentInfo(OwnerDoc());
967 nsXBLPrototypeBinding
* protoBinding
= new nsXBLPrototypeBinding();
968 aError
= protoBinding
->Init(NS_LITERAL_CSTRING("shadowroot"),
969 docInfo
, nullptr, true);
970 if (aError
.Failed()) {
975 nsIDocument
* doc
= GetCrossShadowCurrentDoc();
976 nsIContent
* destroyedFramesFor
= nullptr;
978 nsIPresShell
* shell
= doc
->GetShell();
980 shell
->DestroyFramesFor(this, &destroyedFramesFor
);
981 MOZ_ASSERT(!shell
->FrameManager()->GetDisplayContentsStyleFor(this));
984 MOZ_ASSERT(!GetPrimaryFrame());
986 // Unlike for XBL, false is the default for inheriting style.
987 protoBinding
->SetInheritsStyle(false);
989 // Calling SetPrototypeBinding takes ownership of protoBinding.
990 docInfo
->SetPrototypeBinding(NS_LITERAL_CSTRING("shadowroot"), protoBinding
);
992 nsRefPtr
<ShadowRoot
> shadowRoot
= new ShadowRoot(this, nodeInfo
.forget(),
995 // Replace the old ShadowRoot with the new one and let the old
996 // ShadowRoot know about the younger ShadowRoot because the old
997 // ShadowRoot is projected into the younger ShadowRoot's shadow
998 // insertion point (if it exists).
999 ShadowRoot
* olderShadow
= GetShadowRoot();
1000 SetShadowRoot(shadowRoot
);
1002 olderShadow
->SetYoungerShadow(shadowRoot
);
1004 // Unbind children of older shadow root because they
1005 // are no longer in the composed tree.
1006 for (nsIContent
* child
= olderShadow
->GetFirstChild(); child
;
1007 child
= child
->GetNextSibling()) {
1008 child
->UnbindFromTree(true, false);
1012 // xblBinding takes ownership of docInfo.
1013 nsRefPtr
<nsXBLBinding
> xblBinding
= new nsXBLBinding(shadowRoot
, protoBinding
);
1014 shadowRoot
->SetAssociatedBinding(xblBinding
);
1015 xblBinding
->SetBoundElement(this);
1017 SetXBLBinding(xblBinding
);
1019 // Recreate the frame for the bound content because binding a ShadowRoot
1020 // changes how things are rendered.
1022 MOZ_ASSERT(doc
== GetCrossShadowCurrentDoc());
1023 nsIPresShell
* shell
= doc
->GetShell();
1025 shell
->CreateFramesFor(destroyedFramesFor
);
1029 return shadowRoot
.forget();
1032 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(DestinationInsertionPointList
, mParent
,
1035 NS_INTERFACE_TABLE_HEAD(DestinationInsertionPointList
)
1036 NS_WRAPPERCACHE_INTERFACE_TABLE_ENTRY
1037 NS_INTERFACE_TABLE(DestinationInsertionPointList
, nsINodeList
, nsIDOMNodeList
)
1038 NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(DestinationInsertionPointList
)
1039 NS_INTERFACE_MAP_END
1041 NS_IMPL_CYCLE_COLLECTING_ADDREF(DestinationInsertionPointList
)
1042 NS_IMPL_CYCLE_COLLECTING_RELEASE(DestinationInsertionPointList
)
1044 DestinationInsertionPointList::DestinationInsertionPointList(Element
* aElement
)
1047 nsTArray
<nsIContent
*>* destPoints
= aElement
->GetExistingDestInsertionPoints();
1049 for (uint32_t i
= 0; i
< destPoints
->Length(); i
++) {
1050 mDestinationPoints
.AppendElement(destPoints
->ElementAt(i
));
1055 DestinationInsertionPointList::~DestinationInsertionPointList()
1060 DestinationInsertionPointList::Item(uint32_t aIndex
)
1062 return mDestinationPoints
.SafeElementAt(aIndex
);
1066 DestinationInsertionPointList::Item(uint32_t aIndex
, nsIDOMNode
** aReturn
)
1068 nsIContent
* item
= Item(aIndex
);
1070 return NS_ERROR_FAILURE
;
1073 return CallQueryInterface(item
, aReturn
);
1077 DestinationInsertionPointList::Length() const
1079 return mDestinationPoints
.Length();
1083 DestinationInsertionPointList::GetLength(uint32_t* aLength
)
1085 *aLength
= Length();
1090 DestinationInsertionPointList::IndexOf(nsIContent
* aContent
)
1092 return mDestinationPoints
.IndexOf(aContent
);
1096 DestinationInsertionPointList::WrapObject(JSContext
* aCx
)
1098 return NodeListBinding::Wrap(aCx
, this);
1101 already_AddRefed
<DestinationInsertionPointList
>
1102 Element::GetDestinationInsertionPoints()
1104 nsRefPtr
<DestinationInsertionPointList
> list
=
1105 new DestinationInsertionPointList(this);
1106 return list
.forget();
1110 Element::GetAttribute(const nsAString
& aName
, DOMString
& aReturn
)
1112 const nsAttrValue
* val
=
1113 mAttrsAndChildren
.GetAttr(aName
,
1114 IsHTML() && IsInHTMLDocument() ?
1115 eIgnoreCase
: eCaseMatters
);
1117 val
->ToString(aReturn
);
1120 // XXX should be SetDOMStringToNull(aReturn);
1122 // aReturn is already empty
1130 Element::SetAttribute(const nsAString
& aName
,
1131 const nsAString
& aValue
,
1132 ErrorResult
& aError
)
1134 const nsAttrName
* name
= InternalGetExistingAttrNameFromQName(aName
);
1137 aError
= nsContentUtils::CheckQName(aName
, false);
1138 if (aError
.Failed()) {
1142 nsCOMPtr
<nsIAtom
> nameAtom
;
1143 if (IsHTML() && IsInHTMLDocument()) {
1145 nsContentUtils::ASCIIToLower(aName
, lower
);
1146 nameAtom
= do_GetAtom(lower
);
1149 nameAtom
= do_GetAtom(aName
);
1152 aError
.Throw(NS_ERROR_OUT_OF_MEMORY
);
1155 aError
= SetAttr(kNameSpaceID_None
, nameAtom
, aValue
, true);
1159 aError
= SetAttr(name
->NamespaceID(), name
->LocalName(), name
->GetPrefix(),
1165 Element::RemoveAttribute(const nsAString
& aName
, ErrorResult
& aError
)
1167 const nsAttrName
* name
= InternalGetExistingAttrNameFromQName(aName
);
1170 // If there is no canonical nsAttrName for this attribute name, then the
1171 // attribute does not exist and we can't get its namespace ID and
1172 // local name below, so we return early.
1176 // Hold a strong reference here so that the atom or nodeinfo doesn't go
1177 // away during UnsetAttr. If it did UnsetAttr would be left with a
1178 // dangling pointer as argument without knowing it.
1179 nsAttrName
tmp(*name
);
1181 aError
= UnsetAttr(name
->NamespaceID(), name
->LocalName(), true);
1185 Element::GetAttributeNode(const nsAString
& aName
)
1187 OwnerDoc()->WarnOnceAbout(nsIDocument::eGetAttributeNode
);
1188 return Attributes()->GetNamedItem(aName
);
1191 already_AddRefed
<Attr
>
1192 Element::SetAttributeNode(Attr
& aNewAttr
, ErrorResult
& aError
)
1194 OwnerDoc()->WarnOnceAbout(nsIDocument::eSetAttributeNode
);
1196 return Attributes()->SetNamedItem(aNewAttr
, aError
);
1199 already_AddRefed
<Attr
>
1200 Element::RemoveAttributeNode(Attr
& aAttribute
,
1201 ErrorResult
& aError
)
1203 OwnerDoc()->WarnOnceAbout(nsIDocument::eRemoveAttributeNode
);
1204 return Attributes()->RemoveNamedItem(aAttribute
.NodeName(), aError
);
1208 Element::GetAttributeNS(const nsAString
& aNamespaceURI
,
1209 const nsAString
& aLocalName
,
1213 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI
);
1215 if (nsid
== kNameSpaceID_Unknown
) {
1216 // Unknown namespace means no attribute.
1217 SetDOMStringToNull(aReturn
);
1221 nsCOMPtr
<nsIAtom
> name
= do_GetAtom(aLocalName
);
1222 bool hasAttr
= GetAttr(nsid
, name
, aReturn
);
1224 SetDOMStringToNull(aReturn
);
1229 Element::SetAttributeNS(const nsAString
& aNamespaceURI
,
1230 const nsAString
& aQualifiedName
,
1231 const nsAString
& aValue
,
1232 ErrorResult
& aError
)
1234 nsRefPtr
<mozilla::dom::NodeInfo
> ni
;
1236 nsContentUtils::GetNodeInfoFromQName(aNamespaceURI
, aQualifiedName
,
1237 mNodeInfo
->NodeInfoManager(),
1238 nsIDOMNode::ATTRIBUTE_NODE
,
1239 getter_AddRefs(ni
));
1240 if (aError
.Failed()) {
1244 aError
= SetAttr(ni
->NamespaceID(), ni
->NameAtom(), ni
->GetPrefixAtom(),
1249 Element::RemoveAttributeNS(const nsAString
& aNamespaceURI
,
1250 const nsAString
& aLocalName
,
1251 ErrorResult
& aError
)
1253 nsCOMPtr
<nsIAtom
> name
= do_GetAtom(aLocalName
);
1255 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI
);
1257 if (nsid
== kNameSpaceID_Unknown
) {
1258 // If the namespace ID is unknown, it means there can't possibly be an
1259 // existing attribute. We would need a known namespace ID to pass into
1260 // UnsetAttr, so we return early if we don't have one.
1264 aError
= UnsetAttr(nsid
, name
, true);
1268 Element::GetAttributeNodeNS(const nsAString
& aNamespaceURI
,
1269 const nsAString
& aLocalName
)
1271 OwnerDoc()->WarnOnceAbout(nsIDocument::eGetAttributeNodeNS
);
1273 return GetAttributeNodeNSInternal(aNamespaceURI
, aLocalName
);
1277 Element::GetAttributeNodeNSInternal(const nsAString
& aNamespaceURI
,
1278 const nsAString
& aLocalName
)
1280 return Attributes()->GetNamedItemNS(aNamespaceURI
, aLocalName
);
1283 already_AddRefed
<Attr
>
1284 Element::SetAttributeNodeNS(Attr
& aNewAttr
,
1285 ErrorResult
& aError
)
1287 OwnerDoc()->WarnOnceAbout(nsIDocument::eSetAttributeNodeNS
);
1288 return Attributes()->SetNamedItemNS(aNewAttr
, aError
);
1291 already_AddRefed
<nsIHTMLCollection
>
1292 Element::GetElementsByTagNameNS(const nsAString
& aNamespaceURI
,
1293 const nsAString
& aLocalName
,
1294 ErrorResult
& aError
)
1296 int32_t nameSpaceId
= kNameSpaceID_Wildcard
;
1298 if (!aNamespaceURI
.EqualsLiteral("*")) {
1300 nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI
,
1302 if (aError
.Failed()) {
1307 NS_ASSERTION(nameSpaceId
!= kNameSpaceID_Unknown
, "Unexpected namespace ID!");
1309 return NS_GetContentList(this, nameSpaceId
, aLocalName
);
1313 Element::GetElementsByTagNameNS(const nsAString
& namespaceURI
,
1314 const nsAString
& localName
,
1315 nsIDOMHTMLCollection
** aResult
)
1317 mozilla::ErrorResult rv
;
1318 nsCOMPtr
<nsIHTMLCollection
> list
=
1319 GetElementsByTagNameNS(namespaceURI
, localName
, rv
);
1321 return rv
.ErrorCode();
1323 list
.forget(aResult
);
1328 Element::HasAttributeNS(const nsAString
& aNamespaceURI
,
1329 const nsAString
& aLocalName
) const
1332 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI
);
1334 if (nsid
== kNameSpaceID_Unknown
) {
1335 // Unknown namespace means no attr...
1339 nsCOMPtr
<nsIAtom
> name
= do_GetAtom(aLocalName
);
1340 return HasAttr(nsid
, name
);
1343 already_AddRefed
<nsIHTMLCollection
>
1344 Element::GetElementsByClassName(const nsAString
& aClassNames
)
1346 return nsContentUtils::GetElementsByClassName(this, aClassNames
);
1350 Element::GetElementsByClassName(const nsAString
& aClassNames
,
1351 nsIDOMHTMLCollection
** aResult
)
1354 nsContentUtils::GetElementsByClassName(this, aClassNames
).take();
1359 Element::BindToTree(nsIDocument
* aDocument
, nsIContent
* aParent
,
1360 nsIContent
* aBindingParent
,
1361 bool aCompileEventHandlers
)
1363 NS_PRECONDITION(aParent
|| aDocument
, "Must have document if no parent!");
1364 NS_PRECONDITION((NODE_FROM(aParent
, aDocument
)->OwnerDoc() == OwnerDoc()),
1365 "Must have the same owner document");
1366 NS_PRECONDITION(!aParent
|| aDocument
== aParent
->GetUncomposedDoc(),
1367 "aDocument must be current doc of aParent");
1368 NS_PRECONDITION(!GetUncomposedDoc(), "Already have a document. Unbind first!");
1369 // Note that as we recurse into the kids, they'll have a non-null parent. So
1370 // only assert if our parent is _changing_ while we have a parent.
1371 NS_PRECONDITION(!GetParent() || aParent
== GetParent(),
1372 "Already have a parent. Unbind first!");
1373 NS_PRECONDITION(!GetBindingParent() ||
1374 aBindingParent
== GetBindingParent() ||
1375 (!aBindingParent
&& aParent
&&
1376 aParent
->GetBindingParent() == GetBindingParent()),
1377 "Already have a binding parent. Unbind first!");
1378 NS_PRECONDITION(!aParent
|| !aDocument
||
1379 !aParent
->HasFlag(NODE_FORCE_XBL_BINDINGS
),
1380 "Parent in document but flagged as forcing XBL");
1381 NS_PRECONDITION(aBindingParent
!= this,
1382 "Content must not be its own binding parent");
1383 NS_PRECONDITION(!IsRootOfNativeAnonymousSubtree() ||
1384 aBindingParent
== aParent
,
1385 "Native anonymous content must have its parent as its "
1386 "own binding parent");
1387 NS_PRECONDITION(aBindingParent
|| !aParent
||
1388 aBindingParent
== aParent
->GetBindingParent(),
1389 "We should be passed the right binding parent");
1392 // First set the binding parent
1393 nsXULElement
* xulElem
= nsXULElement::FromContent(this);
1395 xulElem
->SetXULBindingParent(aBindingParent
);
1400 if (aBindingParent
) {
1401 nsDOMSlots
*slots
= DOMSlots();
1403 slots
->mBindingParent
= aBindingParent
; // Weak, so no addref happens.
1406 NS_ASSERTION(!aBindingParent
|| IsRootOfNativeAnonymousSubtree() ||
1407 !HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE
) ||
1408 (aParent
&& aParent
->IsInNativeAnonymousSubtree()),
1409 "Trying to re-bind content from native anonymous subtree to "
1410 "non-native anonymous parent!");
1412 if (aParent
->IsInNativeAnonymousSubtree()) {
1413 SetFlags(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE
);
1415 if (aParent
->HasFlag(NODE_CHROME_ONLY_ACCESS
)) {
1416 SetFlags(NODE_CHROME_ONLY_ACCESS
);
1418 if (aParent
->IsInShadowTree()) {
1419 ClearSubtreeRootPointer();
1420 SetFlags(NODE_IS_IN_SHADOW_TREE
);
1422 ShadowRoot
* parentContainingShadow
= aParent
->GetContainingShadow();
1423 if (parentContainingShadow
) {
1424 DOMSlots()->mContainingShadow
= parentContainingShadow
;
1428 bool hadForceXBL
= HasFlag(NODE_FORCE_XBL_BINDINGS
);
1430 // Now set the parent and set the "Force attach xbl" flag if needed.
1437 if (aParent
->HasFlag(NODE_FORCE_XBL_BINDINGS
)) {
1438 SetFlags(NODE_FORCE_XBL_BINDINGS
);
1442 mParent
= aDocument
;
1444 SetParentIsContent(aParent
);
1446 // XXXbz sXBL/XBL2 issue!
1448 // Finally, set the document
1450 // Notify XBL- & nsIAnonymousContentCreator-generated
1451 // anonymous content that the document is changing.
1452 // XXXbz ordering issues here? Probably not, since ChangeDocumentFor is
1453 // just pretty broken anyway.... Need to get it working.
1454 // XXXbz XBL doesn't handle this (asserts), and we don't really want
1455 // to be doing this during parsing anyway... sort this out.
1456 // aDocument->BindingManager()->ChangeDocumentFor(this, nullptr,
1459 // We no longer need to track the subtree pointer (and in fact we'll assert
1460 // if we do this any later).
1461 ClearSubtreeRootPointer();
1463 // Being added to a document.
1466 // Attached callback must be enqueued whenever custom element is inserted into a
1467 // document and this document has a browsing context.
1468 if (GetCustomElementData() && aDocument
->GetDocShell()) {
1469 // Enqueue an attached callback for the custom element.
1470 aDocument
->EnqueueLifecycleCallback(nsIDocument::eAttached
, this);
1473 // Unset this flag since we now really are in a document.
1474 UnsetFlags(NODE_FORCE_XBL_BINDINGS
|
1475 // And clear the lazy frame construction bits.
1476 NODE_NEEDS_FRAME
| NODE_DESCENDANTS_NEED_FRAMES
|
1477 // And the restyle bits
1478 ELEMENT_ALL_RESTYLE_FLAGS
);
1479 } else if (IsInShadowTree()) {
1480 // We're not in a document, but we did get inserted into a shadow tree.
1481 // Since we won't have any restyle data in the document's restyle trackers,
1482 // don't let us get inserted with restyle bits set incorrectly.
1484 // Also clear all the other flags that are cleared above when we do get
1485 // inserted into a document.
1486 UnsetFlags(NODE_FORCE_XBL_BINDINGS
|
1487 NODE_NEEDS_FRAME
| NODE_DESCENDANTS_NEED_FRAMES
|
1488 ELEMENT_ALL_RESTYLE_FLAGS
);
1490 // If we're not in the doc and not in a shadow tree,
1491 // update our subtree pointer.
1492 SetSubtreeRootPointer(aParent
->SubtreeRoot());
1495 // Propagate scoped style sheet tracking bit.
1496 if (mParent
->IsContent()) {
1498 ShadowRoot
* shadowRootParent
= ShadowRoot::FromNode(mParent
);
1499 if (shadowRootParent
) {
1500 parent
= shadowRootParent
->GetHost();
1502 parent
= mParent
->AsContent();
1505 bool inStyleScope
= parent
->IsElementInStyleScope();
1507 SetIsElementInStyleScope(inStyleScope
);
1508 SetIsElementInStyleScopeFlagOnShadowTree(inStyleScope
);
1511 // This has to be here, rather than in nsGenericHTMLElement::BindToTree,
1512 // because it has to happen after updating the parent pointer, but before
1513 // recursively binding the kids.
1515 SetDirOnBind(this, aParent
);
1518 // If NODE_FORCE_XBL_BINDINGS was set we might have anonymous children
1519 // that also need to be told that they are moving.
1522 nsBindingManager
* bmgr
= OwnerDoc()->BindingManager();
1524 nsXBLBinding
* contBinding
= bmgr
->GetBindingWithContent(this);
1525 // First check if we have a binding...
1527 nsCOMPtr
<nsIContent
> anonRoot
= contBinding
->GetAnonymousContent();
1528 bool allowScripts
= contBinding
->AllowScripts();
1529 for (nsCOMPtr
<nsIContent
> child
= anonRoot
->GetFirstChild();
1531 child
= child
->GetNextSibling()) {
1532 rv
= child
->BindToTree(aDocument
, this, this, allowScripts
);
1533 NS_ENSURE_SUCCESS(rv
, rv
);
1538 UpdateEditableState(false);
1540 // Now recurse into our kids
1541 for (nsIContent
* child
= GetFirstChild(); child
;
1542 child
= child
->GetNextSibling()) {
1543 rv
= child
->BindToTree(aDocument
, this, aBindingParent
,
1544 aCompileEventHandlers
);
1545 NS_ENSURE_SUCCESS(rv
, rv
);
1548 nsNodeUtils::ParentChainChanged(this);
1551 AddToIdTable(DoGetID());
1554 if (MayHaveStyle() && !IsXUL()) {
1555 // XXXbz if we already have a style attr parsed, this won't do
1556 // anything... need to fix that.
1557 // If MayHaveStyle() is true, we must be an nsStyledElement
1558 static_cast<nsStyledElement
*>(this)->ReparseStyleAttribute(false);
1562 // If we're in a document now, let our mapped attrs know what their new
1563 // sheet is. This is safe to run for non-mapped-attribute elements too;
1564 // it'll just do a small bit of unnecessary work. But most elements in
1565 // practice are mapped-attribute elements.
1566 nsHTMLStyleSheet
* sheet
= aDocument
->GetAttributeStyleSheet();
1568 mAttrsAndChildren
.SetMappedAttrStyleSheet(sheet
);
1572 // Call BindToTree on shadow root children.
1573 ShadowRoot
* shadowRoot
= GetShadowRoot();
1575 for (nsIContent
* child
= shadowRoot
->GetFirstChild(); child
;
1576 child
= child
->GetNextSibling()) {
1577 rv
= child
->BindToTree(nullptr, shadowRoot
,
1578 shadowRoot
->GetBindingParent(),
1579 aCompileEventHandlers
);
1580 NS_ENSURE_SUCCESS(rv
, rv
);
1584 // XXXbz script execution during binding can trigger some of these
1585 // postcondition asserts.... But we do want that, since things will
1586 // generally be quite broken when that happens.
1587 NS_POSTCONDITION(aDocument
== GetUncomposedDoc(), "Bound to wrong document");
1588 NS_POSTCONDITION(aParent
== GetParent(), "Bound to wrong parent");
1589 NS_POSTCONDITION(aBindingParent
== GetBindingParent(),
1590 "Bound to wrong binding parent");
1595 RemoveFromBindingManagerRunnable::RemoveFromBindingManagerRunnable(nsBindingManager
* aManager
,
1596 nsIContent
* aContent
,
1598 mManager(aManager
), mContent(aContent
), mDoc(aDoc
)
1601 RemoveFromBindingManagerRunnable::~RemoveFromBindingManagerRunnable() {}
1604 RemoveFromBindingManagerRunnable::Run()
1606 // It may be the case that the element was removed from the
1607 // DOM, causing this runnable to be created, then inserted back
1608 // into the document before the this runnable had a chance to
1609 // tear down the binding. Only tear down the binding if the element
1610 // is still no longer in the DOM. nsXBLService::LoadBinding tears
1611 // down the old binding if the element is inserted back into the
1612 // DOM and loads a different binding.
1613 if (!mContent
->IsInComposedDoc()) {
1614 mManager
->RemovedFromDocumentInternal(mContent
, mDoc
);
1622 Element::UnbindFromTree(bool aDeep
, bool aNullParent
)
1624 NS_PRECONDITION(aDeep
|| (!GetUncomposedDoc() && !GetBindingParent()),
1625 "Shallow unbind won't clear document and binding parent on "
1628 RemoveFromIdTable();
1630 // Make sure to unbind this node before doing the kids
1631 nsIDocument
* document
=
1632 HasFlag(NODE_FORCE_XBL_BINDINGS
) || IsInShadowTree() ?
1633 OwnerDoc() : GetUncomposedDoc();
1636 if (IsFullScreenAncestor()) {
1637 // The element being removed is an ancestor of the full-screen element,
1638 // exit full-screen state.
1639 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag
,
1640 NS_LITERAL_CSTRING("DOM"), OwnerDoc(),
1641 nsContentUtils::eDOM_PROPERTIES
,
1642 "RemovedFullScreenElement");
1643 // Fully exit full-screen.
1644 nsIDocument::ExitFullscreen(OwnerDoc(), /* async */ false);
1646 if (HasPointerLock()) {
1647 nsIDocument::UnlockPointer();
1650 nsINode
* p
= mParent
;
1656 SetParentIsContent(false);
1660 if (aNullParent
|| !mParent
->IsInShadowTree()) {
1661 UnsetFlags(NODE_IS_IN_SHADOW_TREE
);
1663 // Begin keeping track of our subtree root.
1664 SetSubtreeRootPointer(aNullParent
? this : mParent
->SubtreeRoot());
1668 // Notify XBL- & nsIAnonymousContentCreator-generated
1669 // anonymous content that the document is changing.
1670 // Unlike XBL, bindings for web components shadow DOM
1671 // do not get uninstalled.
1672 if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR
) && !GetShadowRoot()) {
1673 nsContentUtils::AddScriptRunner(
1674 new RemoveFromBindingManagerRunnable(document
->BindingManager(), this,
1678 document
->ClearBoxObjectFor(this);
1680 // Detached must be enqueued whenever custom element is removed from
1681 // the document and this document has a browsing context.
1682 if (GetCustomElementData() && document
->GetDocShell()) {
1683 // Enqueue a detached callback for the custom element.
1684 document
->EnqueueLifecycleCallback(nsIDocument::eDetached
, this);
1688 // Ensure that CSS transitions don't continue on an element at a
1689 // different place in the tree (even if reinserted before next
1690 // animation refresh).
1691 // FIXME (Bug 522599): Need a test for this.
1692 if (HasFlag(NODE_HAS_PROPERTIES
)) {
1693 DeleteProperty(nsGkAtoms::transitionsOfBeforeProperty
);
1694 DeleteProperty(nsGkAtoms::transitionsOfAfterProperty
);
1695 DeleteProperty(nsGkAtoms::transitionsProperty
);
1696 DeleteProperty(nsGkAtoms::animationsOfBeforeProperty
);
1697 DeleteProperty(nsGkAtoms::animationsOfAfterProperty
);
1698 DeleteProperty(nsGkAtoms::animationsProperty
);
1701 // Unset this since that's what the old code effectively did.
1702 UnsetFlags(NODE_FORCE_XBL_BINDINGS
);
1703 bool clearBindingParent
= true;
1706 nsXULElement
* xulElem
= nsXULElement::FromContent(this);
1708 xulElem
->SetXULBindingParent(nullptr);
1709 clearBindingParent
= false;
1713 nsDOMSlots
* slots
= GetExistingDOMSlots();
1715 if (clearBindingParent
) {
1716 slots
->mBindingParent
= nullptr;
1718 if (aNullParent
|| !mParent
->IsInShadowTree()) {
1719 slots
->mContainingShadow
= nullptr;
1723 // This has to be here, rather than in nsGenericHTMLElement::UnbindFromTree,
1724 // because it has to happen after unsetting the parent pointer, but before
1725 // recursively unbinding the kids.
1731 // Do the kids. Don't call GetChildCount() here since that'll force
1732 // XUL to generate template children, which there is no need for since
1733 // all we're going to do is unbind them anyway.
1734 uint32_t i
, n
= mAttrsAndChildren
.ChildCount();
1736 for (i
= 0; i
< n
; ++i
) {
1737 // Note that we pass false for aNullParent here, since we don't want
1738 // the kids to forget us. We _do_ want them to forget their binding
1739 // parent, though, since this only walks non-anonymous kids.
1740 mAttrsAndChildren
.ChildAt(i
)->UnbindFromTree(true, false);
1744 nsNodeUtils::ParentChainChanged(this);
1746 // Unbind children of shadow root.
1747 ShadowRoot
* shadowRoot
= GetShadowRoot();
1749 for (nsIContent
* child
= shadowRoot
->GetFirstChild(); child
;
1750 child
= child
->GetNextSibling()) {
1751 child
->UnbindFromTree(true, false);
1757 Element::GetSMILOverrideStyle()
1759 Element::nsDOMSlots
*slots
= DOMSlots();
1761 if (!slots
->mSMILOverrideStyle
) {
1762 slots
->mSMILOverrideStyle
= new nsDOMCSSAttributeDeclaration(this, true);
1765 return slots
->mSMILOverrideStyle
;
1769 Element::GetSMILOverrideStyleRule()
1771 Element::nsDOMSlots
*slots
= GetExistingDOMSlots();
1772 return slots
? slots
->mSMILOverrideStyleRule
.get() : nullptr;
1776 Element::SetSMILOverrideStyleRule(css::StyleRule
* aStyleRule
,
1779 Element::nsDOMSlots
*slots
= DOMSlots();
1781 slots
->mSMILOverrideStyleRule
= aStyleRule
;
1784 nsIDocument
* doc
= GetComposedDoc();
1785 // Only need to request a restyle if we're in a document. (We might not
1786 // be in a document, if we're clearing animation effects on a target node
1787 // that's been detached since the previous animation sample.)
1789 nsCOMPtr
<nsIPresShell
> shell
= doc
->GetShell();
1791 shell
->RestyleForAnimation(this,
1792 eRestyle_StyleAttribute
| eRestyle_ChangeAnimationPhase
);
1801 Element::IsLabelable() const
1807 Element::GetInlineStyleRule()
1813 Element::SetInlineStyleRule(css::StyleRule
* aStyleRule
,
1814 const nsAString
* aSerialized
,
1817 NS_NOTYETIMPLEMENTED("Element::SetInlineStyleRule");
1818 return NS_ERROR_NOT_IMPLEMENTED
;
1821 NS_IMETHODIMP_(bool)
1822 Element::IsAttributeMapped(const nsIAtom
* aAttribute
) const
1828 Element::GetAttributeChangeHint(const nsIAtom
* aAttribute
,
1829 int32_t aModType
) const
1831 return nsChangeHint(0);
1835 Element::FindAttributeDependence(const nsIAtom
* aAttribute
,
1836 const MappedAttributeEntry
* const aMaps
[],
1839 for (uint32_t mapindex
= 0; mapindex
< aMapCount
; ++mapindex
) {
1840 for (const MappedAttributeEntry
* map
= aMaps
[mapindex
];
1841 map
->attribute
; ++map
) {
1842 if (aAttribute
== *map
->attribute
) {
1851 already_AddRefed
<mozilla::dom::NodeInfo
>
1852 Element::GetExistingAttrNameFromQName(const nsAString
& aStr
) const
1854 const nsAttrName
* name
= InternalGetExistingAttrNameFromQName(aStr
);
1859 nsRefPtr
<mozilla::dom::NodeInfo
> nodeInfo
;
1860 if (name
->IsAtom()) {
1861 nodeInfo
= mNodeInfo
->NodeInfoManager()->
1862 GetNodeInfo(name
->Atom(), nullptr, kNameSpaceID_None
,
1863 nsIDOMNode::ATTRIBUTE_NODE
);
1866 nodeInfo
= name
->NodeInfo();
1869 return nodeInfo
.forget();
1874 Element::ShouldBlur(nsIContent
*aContent
)
1876 // Determine if the current element is focused, if it is not focused
1877 // then we should not try to blur
1878 nsIDocument
* document
= aContent
->GetComposedDoc();
1882 nsCOMPtr
<nsPIDOMWindow
> window
= do_QueryInterface(document
->GetWindow());
1886 nsCOMPtr
<nsPIDOMWindow
> focusedFrame
;
1887 nsIContent
* contentToBlur
=
1888 nsFocusManager::GetFocusedDescendant(window
, false, getter_AddRefs(focusedFrame
));
1889 if (contentToBlur
== aContent
)
1892 // if focus on this element would get redirected, then check the redirected
1893 // content as well when blurring.
1894 return (contentToBlur
&& nsFocusManager::GetRedirectedFocus(aContent
) == contentToBlur
);
1898 Element::IsNodeOfType(uint32_t aFlags
) const
1900 return !(aFlags
& ~eCONTENT
);
1905 Element::DispatchEvent(nsPresContext
* aPresContext
,
1906 WidgetEvent
* aEvent
,
1907 nsIContent
* aTarget
,
1909 nsEventStatus
* aStatus
)
1911 NS_PRECONDITION(aTarget
, "Must have target");
1912 NS_PRECONDITION(aEvent
, "Must have source event");
1913 NS_PRECONDITION(aStatus
, "Null out param?");
1915 if (!aPresContext
) {
1919 nsCOMPtr
<nsIPresShell
> shell
= aPresContext
->GetPresShell();
1924 if (aFullDispatch
) {
1925 return shell
->HandleEventWithTarget(aEvent
, nullptr, aTarget
, aStatus
);
1928 return shell
->HandleDOMEventWithTarget(aTarget
, aEvent
, aStatus
);
1933 Element::DispatchClickEvent(nsPresContext
* aPresContext
,
1934 WidgetInputEvent
* aSourceEvent
,
1935 nsIContent
* aTarget
,
1937 const EventFlags
* aExtraEventFlags
,
1938 nsEventStatus
* aStatus
)
1940 NS_PRECONDITION(aTarget
, "Must have target");
1941 NS_PRECONDITION(aSourceEvent
, "Must have source event");
1942 NS_PRECONDITION(aStatus
, "Null out param?");
1944 WidgetMouseEvent
event(aSourceEvent
->mFlags
.mIsTrusted
, NS_MOUSE_CLICK
,
1945 aSourceEvent
->widget
, WidgetMouseEvent::eReal
);
1946 event
.refPoint
= aSourceEvent
->refPoint
;
1947 uint32_t clickCount
= 1;
1949 uint16_t inputSource
= 0;
1950 WidgetMouseEvent
* sourceMouseEvent
= aSourceEvent
->AsMouseEvent();
1951 if (sourceMouseEvent
) {
1952 clickCount
= sourceMouseEvent
->clickCount
;
1953 pressure
= sourceMouseEvent
->pressure
;
1954 inputSource
= sourceMouseEvent
->inputSource
;
1955 } else if (aSourceEvent
->mClass
== eKeyboardEventClass
) {
1956 inputSource
= nsIDOMMouseEvent::MOZ_SOURCE_KEYBOARD
;
1958 event
.pressure
= pressure
;
1959 event
.clickCount
= clickCount
;
1960 event
.inputSource
= inputSource
;
1961 event
.modifiers
= aSourceEvent
->modifiers
;
1962 if (aExtraEventFlags
) {
1963 // Be careful not to overwrite existing flags!
1964 event
.mFlags
.Union(*aExtraEventFlags
);
1967 return DispatchEvent(aPresContext
, &event
, aTarget
, aFullDispatch
, aStatus
);
1971 Element::GetPrimaryFrame(mozFlushType aType
)
1973 nsIDocument
* doc
= GetComposedDoc();
1978 // Cause a flush, so we get up-to-date frame
1980 if (aType
!= Flush_None
) {
1981 doc
->FlushPendingNotifications(aType
);
1984 return GetPrimaryFrame();
1987 //----------------------------------------------------------------------
1989 Element::LeaveLink(nsPresContext
* aPresContext
)
1991 nsILinkHandler
*handler
= aPresContext
->GetLinkHandler();
1996 return handler
->OnLeaveLink();
2000 Element::SetEventHandler(nsIAtom
* aEventName
,
2001 const nsAString
& aValue
,
2004 nsIDocument
*ownerDoc
= OwnerDoc();
2005 if (ownerDoc
->IsLoadedAsData()) {
2006 // Make this a no-op rather than throwing an error to avoid
2007 // the error causing problems setting the attribute.
2011 NS_PRECONDITION(aEventName
, "Must have event name!");
2013 EventListenerManager
* manager
=
2014 GetEventListenerManagerForAttr(aEventName
, &defer
);
2019 defer
= defer
&& aDefer
; // only defer if everyone agrees...
2020 manager
->SetEventHandler(aEventName
, aValue
,
2021 defer
, !nsContentUtils::IsChromeDoc(ownerDoc
),
2027 //----------------------------------------------------------------------
2030 Element::InternalGetExistingAttrNameFromQName(const nsAString
& aStr
) const
2032 return mAttrsAndChildren
.GetExistingAttrNameFromQName(aStr
);
2036 Element::MaybeCheckSameAttrVal(int32_t aNamespaceID
,
2039 const nsAttrValueOrString
& aValue
,
2041 nsAttrValue
& aOldValue
,
2043 bool* aHasListeners
)
2045 bool modification
= false;
2046 *aHasListeners
= aNotify
&&
2047 nsContentUtils::HasMutationListeners(this,
2048 NS_EVENT_BITS_MUTATION_ATTRMODIFIED
,
2051 // If we have no listeners and aNotify is false, we are almost certainly
2052 // coming from the content sink and will almost certainly have no previous
2053 // value. Even if we do, setting the value is cheap when we have no
2054 // listeners and don't plan to notify. The check for aNotify here is an
2055 // optimization, the check for *aHasListeners is a correctness issue.
2056 if (*aHasListeners
|| aNotify
) {
2057 nsAttrInfo
info(GetAttrInfo(aNamespaceID
, aName
));
2059 // Check whether the old value is the same as the new one. Note that we
2060 // only need to actually _get_ the old value if we have listeners or
2061 // if the element is a custom element (because it may have an
2062 // attribute changed callback).
2063 if (*aHasListeners
|| GetCustomElementData()) {
2064 // Need to store the old value.
2066 // If the current attribute value contains a pointer to some other data
2067 // structure that gets updated in the process of setting the attribute
2068 // we'll no longer have the old value of the attribute. Therefore, we
2069 // should serialize the attribute value now to keep a snapshot.
2071 // We have to serialize the value anyway in order to create the
2072 // mutation event so there's no cost in doing it now.
2073 aOldValue
.SetToSerialized(*info
.mValue
);
2075 bool valueMatches
= aValue
.EqualsAsStrings(*info
.mValue
);
2076 if (valueMatches
&& aPrefix
== info
.mName
->GetPrefix()) {
2079 modification
= true;
2082 *aModType
= modification
?
2083 static_cast<uint8_t>(nsIDOMMutationEvent::MODIFICATION
) :
2084 static_cast<uint8_t>(nsIDOMMutationEvent::ADDITION
);
2089 Element::OnlyNotifySameValueSet(int32_t aNamespaceID
, nsIAtom
* aName
,
2091 const nsAttrValueOrString
& aValue
,
2092 bool aNotify
, nsAttrValue
& aOldValue
,
2093 uint8_t* aModType
, bool* aHasListeners
)
2095 if (!MaybeCheckSameAttrVal(aNamespaceID
, aName
, aPrefix
, aValue
, aNotify
,
2096 aOldValue
, aModType
, aHasListeners
)) {
2100 nsAutoScriptBlocker scriptBlocker
;
2101 nsNodeUtils::AttributeSetToCurrentValue(this, aNamespaceID
, aName
);
2106 Element::SetAttr(int32_t aNamespaceID
, nsIAtom
* aName
,
2107 nsIAtom
* aPrefix
, const nsAString
& aValue
,
2110 // Keep this in sync with SetParsedAttr below
2112 NS_ENSURE_ARG_POINTER(aName
);
2113 NS_ASSERTION(aNamespaceID
!= kNameSpaceID_Unknown
,
2114 "Don't call SetAttr with unknown namespace");
2116 if (!mAttrsAndChildren
.CanFitMoreAttrs()) {
2117 return NS_ERROR_FAILURE
;
2122 nsAttrValueOrString
value(aValue
);
2123 nsAttrValue oldValue
;
2125 if (OnlyNotifySameValueSet(aNamespaceID
, aName
, aPrefix
, value
, aNotify
,
2126 oldValue
, &modType
, &hasListeners
)) {
2130 nsresult rv
= BeforeSetAttr(aNamespaceID
, aName
, &value
, aNotify
);
2131 NS_ENSURE_SUCCESS(rv
, rv
);
2134 nsNodeUtils::AttributeWillChange(this, aNamespaceID
, aName
, modType
);
2137 // Hold a script blocker while calling ParseAttribute since that can call
2138 // out to id-observers
2139 nsAutoScriptBlocker scriptBlocker
;
2141 nsAttrValue attrValue
;
2142 if (!ParseAttribute(aNamespaceID
, aName
, aValue
, attrValue
)) {
2143 attrValue
.SetTo(aValue
);
2146 return SetAttrAndNotify(aNamespaceID
, aName
, aPrefix
, oldValue
,
2147 attrValue
, modType
, hasListeners
, aNotify
,
2152 Element::SetParsedAttr(int32_t aNamespaceID
, nsIAtom
* aName
,
2153 nsIAtom
* aPrefix
, nsAttrValue
& aParsedValue
,
2156 // Keep this in sync with SetAttr above
2158 NS_ENSURE_ARG_POINTER(aName
);
2159 NS_ASSERTION(aNamespaceID
!= kNameSpaceID_Unknown
,
2160 "Don't call SetAttr with unknown namespace");
2162 if (!mAttrsAndChildren
.CanFitMoreAttrs()) {
2163 return NS_ERROR_FAILURE
;
2169 nsAttrValueOrString
value(aParsedValue
);
2170 nsAttrValue oldValue
;
2172 if (OnlyNotifySameValueSet(aNamespaceID
, aName
, aPrefix
, value
, aNotify
,
2173 oldValue
, &modType
, &hasListeners
)) {
2177 nsresult rv
= BeforeSetAttr(aNamespaceID
, aName
, &value
, aNotify
);
2178 NS_ENSURE_SUCCESS(rv
, rv
);
2181 nsNodeUtils::AttributeWillChange(this, aNamespaceID
, aName
, modType
);
2184 return SetAttrAndNotify(aNamespaceID
, aName
, aPrefix
, oldValue
,
2185 aParsedValue
, modType
, hasListeners
, aNotify
,
2190 Element::SetAttrAndNotify(int32_t aNamespaceID
,
2193 const nsAttrValue
& aOldValue
,
2194 nsAttrValue
& aParsedValue
,
2198 bool aCallAfterSetAttr
)
2202 nsIDocument
* document
= GetComposedDoc();
2203 mozAutoDocUpdate
updateBatch(document
, UPDATE_CONTENT_MODEL
, aNotify
);
2205 nsMutationGuard::DidMutate();
2207 // Copy aParsedValue for later use since it will be lost when we call
2208 // SetAndTakeMappedAttr below
2209 nsAttrValue aValueForAfterSetAttr
;
2210 if (aCallAfterSetAttr
) {
2211 aValueForAfterSetAttr
.SetTo(aParsedValue
);
2214 bool hadValidDir
= false;
2215 bool hadDirAuto
= false;
2217 if (aNamespaceID
== kNameSpaceID_None
) {
2218 if (aName
== nsGkAtoms::dir
) {
2219 hadValidDir
= HasValidDir() || IsHTML(nsGkAtoms::bdi
);
2220 hadDirAuto
= HasDirAuto(); // already takes bdi into account
2223 // XXXbz Perhaps we should push up the attribute mapping function
2224 // stuff to Element?
2225 if (!IsAttributeMapped(aName
) ||
2226 !SetMappedAttribute(document
, aName
, aParsedValue
, &rv
)) {
2227 rv
= mAttrsAndChildren
.SetAndTakeAttr(aName
, aParsedValue
);
2231 nsRefPtr
<mozilla::dom::NodeInfo
> ni
;
2232 ni
= mNodeInfo
->NodeInfoManager()->GetNodeInfo(aName
, aPrefix
,
2234 nsIDOMNode::ATTRIBUTE_NODE
);
2236 rv
= mAttrsAndChildren
.SetAndTakeAttr(ni
, aParsedValue
);
2238 NS_ENSURE_SUCCESS(rv
, rv
);
2240 if (document
|| HasFlag(NODE_FORCE_XBL_BINDINGS
)) {
2241 nsRefPtr
<nsXBLBinding
> binding
= GetXBLBinding();
2243 binding
->AttributeChanged(aName
, aNamespaceID
, false, aNotify
);
2247 UpdateState(aNotify
);
2249 nsIDocument
* ownerDoc
= OwnerDoc();
2250 if (ownerDoc
&& GetCustomElementData()) {
2251 nsCOMPtr
<nsIAtom
> oldValueAtom
= aOldValue
.GetAsAtom();
2252 nsCOMPtr
<nsIAtom
> newValueAtom
= aValueForAfterSetAttr
.GetAsAtom();
2253 LifecycleCallbackArgs args
= {
2254 nsDependentAtomString(aName
),
2255 aModType
== nsIDOMMutationEvent::ADDITION
?
2256 NullString() : nsDependentAtomString(oldValueAtom
),
2257 nsDependentAtomString(newValueAtom
)
2260 ownerDoc
->EnqueueLifecycleCallback(nsIDocument::eAttributeChanged
, this, &args
);
2263 if (aCallAfterSetAttr
) {
2264 rv
= AfterSetAttr(aNamespaceID
, aName
, &aValueForAfterSetAttr
, aNotify
);
2265 NS_ENSURE_SUCCESS(rv
, rv
);
2267 if (aNamespaceID
== kNameSpaceID_None
&& aName
== nsGkAtoms::dir
) {
2268 OnSetDirAttr(this, &aValueForAfterSetAttr
,
2269 hadValidDir
, hadDirAuto
, aNotify
);
2274 nsNodeUtils::AttributeChanged(this, aNamespaceID
, aName
, aModType
);
2277 if (aFireMutation
) {
2278 InternalMutationEvent
mutation(true, NS_MUTATION_ATTRMODIFIED
);
2281 nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID
, ns
);
2283 GetAttributeNodeNSInternal(ns
, nsDependentAtomString(aName
));
2284 mutation
.mRelatedNode
= attrNode
;
2286 mutation
.mAttrName
= aName
;
2287 nsAutoString newValue
;
2288 GetAttr(aNamespaceID
, aName
, newValue
);
2289 if (!newValue
.IsEmpty()) {
2290 mutation
.mNewAttrValue
= do_GetAtom(newValue
);
2292 if (!aOldValue
.IsEmptyString()) {
2293 mutation
.mPrevAttrValue
= aOldValue
.GetAsAtom();
2295 mutation
.mAttrChange
= aModType
;
2297 mozAutoSubtreeModified
subtree(OwnerDoc(), this);
2298 (new AsyncEventDispatcher(this, mutation
))->RunDOMEventWhenSafe();
2305 Element::ParseAttribute(int32_t aNamespaceID
,
2306 nsIAtom
* aAttribute
,
2307 const nsAString
& aValue
,
2308 nsAttrValue
& aResult
)
2310 if (aNamespaceID
== kNameSpaceID_None
) {
2311 if (aAttribute
== nsGkAtoms::_class
) {
2312 SetFlags(NODE_MAY_HAVE_CLASS
);
2313 aResult
.ParseAtomArray(aValue
);
2316 if (aAttribute
== nsGkAtoms::id
) {
2317 // Store id as an atom. id="" means that the element has no id,
2318 // not that it has an emptystring as the id.
2319 RemoveFromIdTable();
2320 if (aValue
.IsEmpty()) {
2324 aResult
.ParseAtom(aValue
);
2326 AddToIdTable(aResult
.GetAtomValue());
2335 Element::SetMappedAttribute(nsIDocument
* aDocument
,
2337 nsAttrValue
& aValue
,
2344 EventListenerManager
*
2345 Element::GetEventListenerManagerForAttr(nsIAtom
* aAttrName
,
2349 return GetOrCreateListenerManager();
2353 Element::GetAttrInfo(int32_t aNamespaceID
, nsIAtom
* aName
) const
2355 NS_ASSERTION(nullptr != aName
, "must have attribute name");
2356 NS_ASSERTION(aNamespaceID
!= kNameSpaceID_Unknown
,
2357 "must have a real namespace ID!");
2359 int32_t index
= mAttrsAndChildren
.IndexOfAttr(aName
, aNamespaceID
);
2361 return nsAttrInfo(mAttrsAndChildren
.AttrNameAt(index
),
2362 mAttrsAndChildren
.AttrAt(index
));
2365 return nsAttrInfo(nullptr, nullptr);
2370 Element::GetAttr(int32_t aNameSpaceID
, nsIAtom
* aName
,
2371 nsAString
& aResult
) const
2374 bool haveAttr
= GetAttr(aNameSpaceID
, aName
, str
);
2375 str
.ToString(aResult
);
2380 Element::FindAttrValueIn(int32_t aNameSpaceID
,
2382 AttrValuesArray
* aValues
,
2383 nsCaseTreatment aCaseSensitive
) const
2385 NS_ASSERTION(aName
, "Must have attr name");
2386 NS_ASSERTION(aNameSpaceID
!= kNameSpaceID_Unknown
, "Must have namespace");
2387 NS_ASSERTION(aValues
, "Null value array");
2389 const nsAttrValue
* val
= mAttrsAndChildren
.GetAttr(aName
, aNameSpaceID
);
2391 for (int32_t i
= 0; aValues
[i
]; ++i
) {
2392 if (val
->Equals(*aValues
[i
], aCaseSensitive
)) {
2396 return ATTR_VALUE_NO_MATCH
;
2398 return ATTR_MISSING
;
2402 Element::UnsetAttr(int32_t aNameSpaceID
, nsIAtom
* aName
,
2405 NS_ASSERTION(nullptr != aName
, "must have attribute name");
2407 int32_t index
= mAttrsAndChildren
.IndexOfAttr(aName
, aNameSpaceID
);
2412 nsresult rv
= BeforeSetAttr(aNameSpaceID
, aName
, nullptr, aNotify
);
2413 NS_ENSURE_SUCCESS(rv
, rv
);
2415 nsIDocument
*document
= GetComposedDoc();
2416 mozAutoDocUpdate
updateBatch(document
, UPDATE_CONTENT_MODEL
, aNotify
);
2419 nsNodeUtils::AttributeWillChange(this, aNameSpaceID
, aName
,
2420 nsIDOMMutationEvent::REMOVAL
);
2423 bool hasMutationListeners
= aNotify
&&
2424 nsContentUtils::HasMutationListeners(this,
2425 NS_EVENT_BITS_MUTATION_ATTRMODIFIED
,
2428 // Grab the attr node if needed before we remove it from the attr map
2429 nsRefPtr
<Attr
> attrNode
;
2430 if (hasMutationListeners
) {
2432 nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNameSpaceID
, ns
);
2433 attrNode
= GetAttributeNodeNSInternal(ns
, nsDependentAtomString(aName
));
2436 // Clear binding to nsIDOMMozNamedAttrMap
2437 nsDOMSlots
*slots
= GetExistingDOMSlots();
2438 if (slots
&& slots
->mAttributeMap
) {
2439 slots
->mAttributeMap
->DropAttribute(aNameSpaceID
, aName
);
2442 // The id-handling code, and in the future possibly other code, need to
2443 // react to unexpected attribute changes.
2444 nsMutationGuard::DidMutate();
2446 if (aName
== nsGkAtoms::id
&& aNameSpaceID
== kNameSpaceID_None
) {
2447 // Have to do this before clearing flag. See RemoveFromIdTable
2448 RemoveFromIdTable();
2452 bool hadValidDir
= false;
2453 bool hadDirAuto
= false;
2455 if (aNameSpaceID
== kNameSpaceID_None
&& aName
== nsGkAtoms::dir
) {
2456 hadValidDir
= HasValidDir() || IsHTML(nsGkAtoms::bdi
);
2457 hadDirAuto
= HasDirAuto(); // already takes bdi into account
2460 nsAttrValue oldValue
;
2461 rv
= mAttrsAndChildren
.RemoveAttrAt(index
, oldValue
);
2462 NS_ENSURE_SUCCESS(rv
, rv
);
2464 if (document
|| HasFlag(NODE_FORCE_XBL_BINDINGS
)) {
2465 nsRefPtr
<nsXBLBinding
> binding
= GetXBLBinding();
2467 binding
->AttributeChanged(aName
, aNameSpaceID
, true, aNotify
);
2471 UpdateState(aNotify
);
2473 nsIDocument
* ownerDoc
= OwnerDoc();
2474 if (ownerDoc
&& GetCustomElementData()) {
2475 nsCOMPtr
<nsIAtom
> oldValueAtom
= oldValue
.GetAsAtom();
2476 LifecycleCallbackArgs args
= {
2477 nsDependentAtomString(aName
),
2478 nsDependentAtomString(oldValueAtom
),
2482 ownerDoc
->EnqueueLifecycleCallback(nsIDocument::eAttributeChanged
, this, &args
);
2486 nsNodeUtils::AttributeChanged(this, aNameSpaceID
, aName
,
2487 nsIDOMMutationEvent::REMOVAL
);
2490 rv
= AfterSetAttr(aNameSpaceID
, aName
, nullptr, aNotify
);
2491 NS_ENSURE_SUCCESS(rv
, rv
);
2493 if (aNameSpaceID
== kNameSpaceID_None
&& aName
== nsGkAtoms::dir
) {
2494 OnSetDirAttr(this, nullptr, hadValidDir
, hadDirAuto
, aNotify
);
2497 if (hasMutationListeners
) {
2498 InternalMutationEvent
mutation(true, NS_MUTATION_ATTRMODIFIED
);
2500 mutation
.mRelatedNode
= attrNode
;
2501 mutation
.mAttrName
= aName
;
2504 oldValue
.ToString(value
);
2505 if (!value
.IsEmpty())
2506 mutation
.mPrevAttrValue
= do_GetAtom(value
);
2507 mutation
.mAttrChange
= nsIDOMMutationEvent::REMOVAL
;
2509 mozAutoSubtreeModified
subtree(OwnerDoc(), this);
2510 (new AsyncEventDispatcher(this, mutation
))->RunDOMEventWhenSafe();
2517 Element::GetAttrNameAt(uint32_t aIndex
) const
2519 return mAttrsAndChildren
.GetSafeAttrNameAt(aIndex
);
2523 Element::GetAttrCount() const
2525 return mAttrsAndChildren
.AttrCount();
2529 Element::DescribeAttribute(uint32_t index
, nsAString
& aOutDescription
) const
2532 mAttrsAndChildren
.AttrNameAt(index
)->GetQualifiedName(aOutDescription
);
2535 aOutDescription
.AppendLiteral("=\"");
2537 mAttrsAndChildren
.AttrAt(index
)->ToString(value
);
2538 for (int i
= value
.Length(); i
>= 0; --i
) {
2539 if (value
[i
] == char16_t('"'))
2540 value
.Insert(char16_t('\\'), uint32_t(i
));
2542 aOutDescription
.Append(value
);
2543 aOutDescription
.Append('"');
2548 Element::ListAttributes(FILE* out
) const
2550 uint32_t index
, count
= mAttrsAndChildren
.AttrCount();
2551 for (index
= 0; index
< count
; index
++) {
2552 nsAutoString attributeDescription
;
2553 DescribeAttribute(index
, attributeDescription
);
2556 fputs(NS_LossyConvertUTF16toASCII(attributeDescription
).get(), out
);
2561 Element::List(FILE* out
, int32_t aIndent
,
2562 const nsCString
& aPrefix
) const
2565 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2567 fputs(aPrefix
.get(), out
);
2569 fputs(NS_LossyConvertUTF16toASCII(mNodeInfo
->QualifiedName()).get(), out
);
2571 fprintf(out
, "@%p", (void *)this);
2573 ListAttributes(out
);
2575 fprintf(out
, " state=[%llx]",
2576 static_cast<unsigned long long>(State().GetInternalValue()));
2577 fprintf(out
, " flags=[%08x]", static_cast<unsigned int>(GetFlags()));
2578 if (IsCommonAncestorForRangeInSelection()) {
2579 nsRange::RangeHashTable
* ranges
=
2580 static_cast<nsRange::RangeHashTable
*>(GetProperty(nsGkAtoms::range
));
2581 fprintf(out
, " ranges:%d", ranges
? ranges
->Count() : 0);
2583 fprintf(out
, " primaryframe=%p", static_cast<void*>(GetPrimaryFrame()));
2584 fprintf(out
, " refcount=%" PRIuPTR
"<", mRefCnt
.get());
2586 nsIContent
* child
= GetFirstChild();
2590 for (; child
; child
= child
->GetNextSibling()) {
2591 child
->List(out
, aIndent
+ 1);
2594 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2599 Element
* nonConstThis
= const_cast<Element
*>(this);
2601 // XXX sXBL/XBL2 issue! Owner or current document?
2602 nsIDocument
*document
= OwnerDoc();
2604 // Note: not listing nsIAnonymousContentCreator-created content...
2606 nsBindingManager
* bindingManager
= document
->BindingManager();
2607 nsCOMPtr
<nsIDOMNodeList
> anonymousChildren
;
2608 bindingManager
->GetAnonymousNodesFor(nonConstThis
,
2609 getter_AddRefs(anonymousChildren
));
2611 if (anonymousChildren
) {
2612 uint32_t length
= 0;
2613 anonymousChildren
->GetLength(&length
);
2615 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2616 fputs("anonymous-children<\n", out
);
2618 for (uint32_t i
= 0; i
< length
; ++i
) {
2619 nsCOMPtr
<nsIDOMNode
> node
;
2620 anonymousChildren
->Item(i
, getter_AddRefs(node
));
2621 nsCOMPtr
<nsIContent
> child
= do_QueryInterface(node
);
2622 child
->List(out
, aIndent
+ 1);
2625 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2628 bool outHeader
= false;
2629 ExplicitChildIterator
iter(nonConstThis
);
2630 for (nsIContent
* child
= iter
.GetNextChild(); child
; child
= iter
.GetNextChild()) {
2634 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2635 fputs("content-list<\n", out
);
2638 child
->List(out
, aIndent
+ 1);
2642 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2649 Element::DumpContent(FILE* out
, int32_t aIndent
,
2650 bool aDumpAll
) const
2653 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2655 const nsString
& buf
= mNodeInfo
->QualifiedName();
2657 fputs(NS_LossyConvertUTF16toASCII(buf
).get(), out
);
2659 if(aDumpAll
) ListAttributes(out
);
2663 if(aIndent
) fputs("\n", out
);
2665 for (nsIContent
* child
= GetFirstChild();
2667 child
= child
->GetNextSibling()) {
2668 int32_t indent
= aIndent
? aIndent
+ 1 : 0;
2669 child
->DumpContent(out
, indent
, aDumpAll
);
2671 for (indent
= aIndent
; --indent
>= 0; ) fputs(" ", out
);
2673 fputs(NS_LossyConvertUTF16toASCII(buf
).get(), out
);
2676 if(aIndent
) fputs("\n", out
);
2681 Element::Describe(nsAString
& aOutDescription
) const
2683 aOutDescription
.Append(mNodeInfo
->QualifiedName());
2684 aOutDescription
.AppendPrintf("@%p", (void *)this);
2686 uint32_t index
, count
= mAttrsAndChildren
.AttrCount();
2687 for (index
= 0; index
< count
; index
++) {
2688 aOutDescription
.Append(' ');
2689 nsAutoString attributeDescription
;
2690 DescribeAttribute(index
, attributeDescription
);
2691 aOutDescription
.Append(attributeDescription
);
2696 Element::CheckHandleEventForLinksPrecondition(EventChainVisitor
& aVisitor
,
2697 nsIURI
** aURI
) const
2699 if (aVisitor
.mEventStatus
== nsEventStatus_eConsumeNoDefault
||
2700 (!aVisitor
.mEvent
->mFlags
.mIsTrusted
&&
2701 (aVisitor
.mEvent
->message
!= NS_MOUSE_CLICK
) &&
2702 (aVisitor
.mEvent
->message
!= NS_KEY_PRESS
) &&
2703 (aVisitor
.mEvent
->message
!= NS_UI_ACTIVATE
)) ||
2704 !aVisitor
.mPresContext
||
2705 aVisitor
.mEvent
->mFlags
.mMultipleActionsPrevented
) {
2709 // Make sure we actually are a link
2710 return IsLink(aURI
);
2714 Element::PreHandleEventForLinks(EventChainPreVisitor
& aVisitor
)
2716 // Optimisation: return early if this event doesn't interest us.
2717 // IMPORTANT: this switch and the switch below it must be kept in sync!
2718 switch (aVisitor
.mEvent
->message
) {
2719 case NS_MOUSE_ENTER_SYNTH
:
2720 case NS_FOCUS_CONTENT
:
2721 case NS_MOUSE_EXIT_SYNTH
:
2722 case NS_BLUR_CONTENT
:
2728 // Make sure we meet the preconditions before continuing
2729 nsCOMPtr
<nsIURI
> absURI
;
2730 if (!CheckHandleEventForLinksPrecondition(aVisitor
, getter_AddRefs(absURI
))) {
2734 nsresult rv
= NS_OK
;
2736 // We do the status bar updates in PreHandleEvent so that the status bar gets
2737 // updated even if the event is consumed before we have a chance to set it.
2738 switch (aVisitor
.mEvent
->message
) {
2739 // Set the status bar similarly for mouseover and focus
2740 case NS_MOUSE_ENTER_SYNTH
:
2741 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
2743 case NS_FOCUS_CONTENT
: {
2744 InternalFocusEvent
* focusEvent
= aVisitor
.mEvent
->AsFocusEvent();
2745 if (!focusEvent
|| !focusEvent
->isRefocus
) {
2746 nsAutoString target
;
2747 GetLinkTarget(target
);
2748 nsContentUtils::TriggerLink(this, aVisitor
.mPresContext
, absURI
, target
,
2750 // Make sure any ancestor links don't also TriggerLink
2751 aVisitor
.mEvent
->mFlags
.mMultipleActionsPrevented
= true;
2755 case NS_MOUSE_EXIT_SYNTH
:
2756 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
2758 case NS_BLUR_CONTENT
:
2759 rv
= LeaveLink(aVisitor
.mPresContext
);
2760 if (NS_SUCCEEDED(rv
)) {
2761 aVisitor
.mEvent
->mFlags
.mMultipleActionsPrevented
= true;
2766 // switch not in sync with the optimization switch earlier in this function
2767 NS_NOTREACHED("switch statements not in sync");
2768 return NS_ERROR_UNEXPECTED
;
2775 Element::PostHandleEventForLinks(EventChainPostVisitor
& aVisitor
)
2777 // Optimisation: return early if this event doesn't interest us.
2778 // IMPORTANT: this switch and the switch below it must be kept in sync!
2779 switch (aVisitor
.mEvent
->message
) {
2780 case NS_MOUSE_BUTTON_DOWN
:
2781 case NS_MOUSE_CLICK
:
2782 case NS_UI_ACTIVATE
:
2789 // Make sure we meet the preconditions before continuing
2790 nsCOMPtr
<nsIURI
> absURI
;
2791 if (!CheckHandleEventForLinksPrecondition(aVisitor
, getter_AddRefs(absURI
))) {
2795 nsresult rv
= NS_OK
;
2797 switch (aVisitor
.mEvent
->message
) {
2798 case NS_MOUSE_BUTTON_DOWN
:
2800 if (aVisitor
.mEvent
->AsMouseEvent()->button
==
2801 WidgetMouseEvent::eLeftButton
) {
2802 // don't make the link grab the focus if there is no link handler
2803 nsILinkHandler
*handler
= aVisitor
.mPresContext
->GetLinkHandler();
2804 nsIDocument
*document
= GetComposedDoc();
2805 if (handler
&& document
) {
2806 nsIFocusManager
* fm
= nsFocusManager::GetFocusManager();
2808 aVisitor
.mEvent
->mFlags
.mMultipleActionsPrevented
= true;
2809 nsCOMPtr
<nsIDOMElement
> elem
= do_QueryInterface(this);
2810 fm
->SetFocus(elem
, nsIFocusManager::FLAG_BYMOUSE
|
2811 nsIFocusManager::FLAG_NOSCROLL
);
2814 EventStateManager::SetActiveManager(
2815 aVisitor
.mPresContext
->EventStateManager(), this);
2821 case NS_MOUSE_CLICK
: {
2822 WidgetMouseEvent
* mouseEvent
= aVisitor
.mEvent
->AsMouseEvent();
2823 if (mouseEvent
->IsLeftClickEvent()) {
2824 if (mouseEvent
->IsControl() || mouseEvent
->IsMeta() ||
2825 mouseEvent
->IsAlt() ||mouseEvent
->IsShift()) {
2829 // The default action is simply to dispatch DOMActivate
2830 nsCOMPtr
<nsIPresShell
> shell
= aVisitor
.mPresContext
->GetPresShell();
2833 nsEventStatus status
= nsEventStatus_eIgnore
;
2834 InternalUIEvent
actEvent(mouseEvent
->mFlags
.mIsTrusted
, NS_UI_ACTIVATE
);
2835 actEvent
.detail
= 1;
2837 rv
= shell
->HandleDOMEventWithTarget(this, &actEvent
, &status
);
2838 if (NS_SUCCEEDED(rv
)) {
2839 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
2845 case NS_UI_ACTIVATE
:
2847 if (aVisitor
.mEvent
->originalTarget
== this) {
2848 nsAutoString target
;
2849 GetLinkTarget(target
);
2850 nsContentUtils::TriggerLink(this, aVisitor
.mPresContext
, absURI
, target
,
2852 aVisitor
.mEvent
->mFlags
.mIsTrusted
);
2853 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
2860 WidgetKeyboardEvent
* keyEvent
= aVisitor
.mEvent
->AsKeyboardEvent();
2861 if (keyEvent
&& keyEvent
->keyCode
== NS_VK_RETURN
) {
2862 nsEventStatus status
= nsEventStatus_eIgnore
;
2863 rv
= DispatchClickEvent(aVisitor
.mPresContext
, keyEvent
, this,
2864 false, nullptr, &status
);
2865 if (NS_SUCCEEDED(rv
)) {
2866 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
2873 // switch not in sync with the optimization switch earlier in this function
2874 NS_NOTREACHED("switch statements not in sync");
2875 return NS_ERROR_UNEXPECTED
;
2882 Element::GetLinkTarget(nsAString
& aTarget
)
2888 nsDOMSettableTokenListPropertyDestructor(void *aObject
, nsIAtom
*aProperty
,
2889 void *aPropertyValue
, void *aData
)
2891 nsDOMSettableTokenList
* list
=
2892 static_cast<nsDOMSettableTokenList
*>(aPropertyValue
);
2896 static nsIAtom
** sPropertiesToTraverseAndUnlink
[] =
2898 &nsGkAtoms::microdataProperties
,
2899 &nsGkAtoms::itemtype
,
2900 &nsGkAtoms::itemref
,
2901 &nsGkAtoms::itemprop
,
2902 &nsGkAtoms::sandbox
,
2909 Element::HTMLSVGPropertiesToTraverseAndUnlink()
2911 return sPropertiesToTraverseAndUnlink
;
2914 nsDOMSettableTokenList
*
2915 Element::GetTokenList(nsIAtom
* aAtom
)
2919 HTMLSVGPropertiesToTraverseAndUnlink();
2921 for (uint32_t i
= 0; props
[i
]; ++i
) {
2922 if (*props
[i
] == aAtom
) {
2927 MOZ_ASSERT(found
, "Trying to use an unknown tokenlist!");
2930 nsDOMSettableTokenList
* list
= nullptr;
2931 if (HasProperties()) {
2932 list
= static_cast<nsDOMSettableTokenList
*>(GetProperty(aAtom
));
2935 list
= new nsDOMSettableTokenList(this, aAtom
);
2937 SetProperty(aAtom
, list
, nsDOMSettableTokenListPropertyDestructor
);
2943 Element::GetTokenList(nsIAtom
* aAtom
, nsIVariant
** aResult
)
2945 nsISupports
* itemType
= GetTokenList(aAtom
);
2946 nsCOMPtr
<nsIWritableVariant
> out
= new nsVariant();
2947 out
->SetAsInterface(NS_GET_IID(nsISupports
), itemType
);
2948 out
.forget(aResult
);
2952 Element::SetTokenList(nsIAtom
* aAtom
, nsIVariant
* aValue
)
2954 nsDOMSettableTokenList
* itemType
= GetTokenList(aAtom
);
2955 nsAutoString string
;
2956 aValue
->GetAsAString(string
);
2958 itemType
->SetValue(string
, rv
);
2959 return rv
.ErrorCode();
2963 Element::Closest(const nsAString
& aSelector
, ErrorResult
& aResult
)
2965 nsCSSSelectorList
* selectorList
= ParseSelectorList(aSelector
, aResult
);
2966 if (!selectorList
) {
2967 // Either we failed (and aResult already has the exception), or this
2968 // is a pseudo-element-only selector that matches nothing.
2971 OwnerDoc()->FlushPendingLinkUpdates();
2972 TreeMatchContext
matchingContext(false,
2973 nsRuleWalker::eRelevantLinkUnvisited
,
2975 TreeMatchContext::eNeverMatchVisited
);
2976 matchingContext
.SetHasSpecifiedScope();
2977 matchingContext
.AddScopeElement(this);
2978 for (nsINode
* node
= this; node
; node
= node
->GetParentNode()) {
2979 if (node
->IsElement() &&
2980 nsCSSRuleProcessor::SelectorListMatches(node
->AsElement(),
2983 return node
->AsElement();
2990 Element::Matches(const nsAString
& aSelector
, ErrorResult
& aError
)
2992 nsCSSSelectorList
* selectorList
= ParseSelectorList(aSelector
, aError
);
2993 if (!selectorList
) {
2994 // Either we failed (and aError already has the exception), or this
2995 // is a pseudo-element-only selector that matches nothing.
2999 OwnerDoc()->FlushPendingLinkUpdates();
3000 TreeMatchContext
matchingContext(false,
3001 nsRuleWalker::eRelevantLinkUnvisited
,
3003 TreeMatchContext::eNeverMatchVisited
);
3004 matchingContext
.SetHasSpecifiedScope();
3005 matchingContext
.AddScopeElement(this);
3006 return nsCSSRuleProcessor::SelectorListMatches(this, matchingContext
,
3010 static const nsAttrValue::EnumTable kCORSAttributeTable
[] = {
3011 // Order matters here
3012 // See ParseCORSValue
3013 { "anonymous", CORS_ANONYMOUS
},
3014 { "use-credentials", CORS_USE_CREDENTIALS
},
3019 Element::ParseCORSValue(const nsAString
& aValue
,
3020 nsAttrValue
& aResult
)
3022 DebugOnly
<bool> success
=
3023 aResult
.ParseEnumValue(aValue
, kCORSAttributeTable
, false,
3024 // default value is anonymous if aValue is
3025 // not a value we understand
3026 &kCORSAttributeTable
[0]);
3027 MOZ_ASSERT(success
);
3030 /* static */ CORSMode
3031 Element::StringToCORSMode(const nsAString
& aValue
)
3033 if (aValue
.IsVoid()) {
3038 Element::ParseCORSValue(aValue
, val
);
3039 return CORSMode(val
.GetEnumValue());
3042 /* static */ CORSMode
3043 Element::AttrValueToCORSMode(const nsAttrValue
* aValue
)
3049 return CORSMode(aValue
->GetEnumValue());
3053 GetFullScreenError(nsIDocument
* aDoc
)
3055 // Block fullscreen requests in the chrome document when the fullscreen API
3056 // is configured for content only.
3057 if (nsContentUtils::IsFullscreenApiContentOnly() &&
3058 nsContentUtils::IsChromeDoc(aDoc
)) {
3059 return "FullScreenDeniedContentOnly";
3062 nsCOMPtr
<nsPIDOMWindow
> win
= aDoc
->GetWindow();
3063 if (aDoc
->NodePrincipal()->GetAppStatus() >= nsIPrincipal::APP_STATUS_INSTALLED
) {
3064 // Request is in a web app and in the same origin as the web app.
3065 // Don't enforce as strict security checks for web apps, the user
3066 // is supposed to have trust in them. However documents cross-origin
3067 // to the web app must still confirm to the normal security checks.
3071 if (!nsContentUtils::IsRequestFullScreenAllowed()) {
3072 return "FullScreenDeniedNotInputDriven";
3075 if (nsContentUtils::IsSitePermDeny(aDoc
->NodePrincipal(), "fullscreen")) {
3076 return "FullScreenDeniedBlocked";
3083 Element::MozRequestFullScreen(JSContext
* aCx
, JS::Handle
<JS::Value
> aOptions
,
3084 ErrorResult
& aError
)
3086 MOZ_ASSERT_IF(!aCx
, aOptions
.isNullOrUndefined());
3087 // Only grant full-screen requests if this is called from inside a trusted
3088 // event handler (i.e. inside an event handler for a user initiated event).
3089 // This stops the full-screen from being abused similar to the popups of old,
3090 // and it also makes it harder for bad guys' script to go full-screen and
3091 // spoof the browser chrome/window and phish logins etc.
3092 // Note that requests for fullscreen inside a web app's origin are exempt
3093 // from this restriction.
3094 const char* error
= GetFullScreenError(OwnerDoc());
3096 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag
,
3097 NS_LITERAL_CSTRING("DOM"), OwnerDoc(),
3098 nsContentUtils::eDOM_PROPERTIES
,
3100 nsRefPtr
<AsyncEventDispatcher
> asyncDispatcher
=
3101 new AsyncEventDispatcher(OwnerDoc(),
3102 NS_LITERAL_STRING("mozfullscreenerror"),
3105 asyncDispatcher
->PostDOMEvent();
3109 FullScreenOptions opts
;
3110 RequestFullscreenOptions fsOptions
;
3112 // We need to check if options is convertible to a dict first before
3113 // trying to init fsOptions; otherwise Init() would throw, and we want to
3114 // silently ignore non-dictionary values
3115 if (aCx
&& IsConvertibleToDictionary(aCx
, aOptions
)) {
3116 if (!fsOptions
.Init(aCx
, aOptions
)) {
3117 aError
.Throw(NS_ERROR_FAILURE
);
3121 if (fsOptions
.mVrDisplay
) {
3122 opts
.mVRHMDDevice
= fsOptions
.mVrDisplay
->GetHMD();
3126 OwnerDoc()->AsyncRequestFullScreen(this, opts
);
3130 Element::MozRequestPointerLock()
3132 OwnerDoc()->RequestPointerLock(this);
3136 Element::GetAnimationPlayers(nsTArray
<nsRefPtr
<AnimationPlayer
> >& aPlayers
)
3138 nsIDocument
* doc
= GetComposedDoc();
3140 doc
->FlushPendingNotifications(Flush_Style
);
3143 nsIAtom
* properties
[] = { nsGkAtoms::transitionsProperty
,
3144 nsGkAtoms::animationsProperty
};
3145 for (size_t propIdx
= 0; propIdx
< MOZ_ARRAY_LENGTH(properties
);
3147 AnimationPlayerCollection
* collection
=
3148 static_cast<AnimationPlayerCollection
*>(
3149 GetProperty(properties
[propIdx
]));
3153 for (size_t playerIdx
= 0;
3154 playerIdx
< collection
->mPlayers
.Length();
3156 AnimationPlayer
* player
= collection
->mPlayers
[playerIdx
];
3157 if (player
->HasCurrentSource() || player
->HasInEffectSource()) {
3158 aPlayers
.AppendElement(player
);
3165 Element::GetInnerHTML(nsAString
& aInnerHTML
)
3167 GetMarkup(false, aInnerHTML
);
3172 Element::SetInnerHTML(const nsAString
& aInnerHTML
, ErrorResult
& aError
)
3174 SetInnerHTMLInternal(aInnerHTML
, aError
);
3178 Element::GetOuterHTML(nsAString
& aOuterHTML
)
3180 GetMarkup(true, aOuterHTML
);
3184 Element::SetOuterHTML(const nsAString
& aOuterHTML
, ErrorResult
& aError
)
3186 nsCOMPtr
<nsINode
> parent
= GetParentNode();
3191 if (parent
->NodeType() == nsIDOMNode::DOCUMENT_NODE
) {
3192 aError
.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR
);
3196 if (OwnerDoc()->IsHTML()) {
3198 int32_t namespaceID
;
3199 if (parent
->IsElement()) {
3200 localName
= static_cast<nsIContent
*>(parent
.get())->Tag();
3201 namespaceID
= static_cast<nsIContent
*>(parent
.get())->GetNameSpaceID();
3203 NS_ASSERTION(parent
->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE
,
3204 "How come the parent isn't a document, a fragment or an element?");
3205 localName
= nsGkAtoms::body
;
3206 namespaceID
= kNameSpaceID_XHTML
;
3208 nsRefPtr
<DocumentFragment
> fragment
=
3209 new DocumentFragment(OwnerDoc()->NodeInfoManager());
3210 nsContentUtils::ParseFragmentHTML(aOuterHTML
,
3214 OwnerDoc()->GetCompatibilityMode() ==
3215 eCompatibility_NavQuirks
,
3217 parent
->ReplaceChild(*fragment
, *this, aError
);
3221 nsCOMPtr
<nsINode
> context
;
3222 if (parent
->IsElement()) {
3225 NS_ASSERTION(parent
->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE
,
3226 "How come the parent isn't a document, a fragment or an element?");
3227 nsRefPtr
<mozilla::dom::NodeInfo
> info
=
3228 OwnerDoc()->NodeInfoManager()->GetNodeInfo(nsGkAtoms::body
,
3231 nsIDOMNode::ELEMENT_NODE
);
3232 context
= NS_NewHTMLBodyElement(info
.forget(), FROM_PARSER_FRAGMENT
);
3235 nsCOMPtr
<nsIDOMDocumentFragment
> df
;
3236 aError
= nsContentUtils::CreateContextualFragment(context
,
3239 getter_AddRefs(df
));
3240 if (aError
.Failed()) {
3243 nsCOMPtr
<nsINode
> fragment
= do_QueryInterface(df
);
3244 parent
->ReplaceChild(*fragment
, *this, aError
);
3247 enum nsAdjacentPosition
{
3255 Element::InsertAdjacentHTML(const nsAString
& aPosition
, const nsAString
& aText
,
3256 ErrorResult
& aError
)
3258 nsAdjacentPosition position
;
3259 if (aPosition
.LowerCaseEqualsLiteral("beforebegin")) {
3260 position
= eBeforeBegin
;
3261 } else if (aPosition
.LowerCaseEqualsLiteral("afterbegin")) {
3262 position
= eAfterBegin
;
3263 } else if (aPosition
.LowerCaseEqualsLiteral("beforeend")) {
3264 position
= eBeforeEnd
;
3265 } else if (aPosition
.LowerCaseEqualsLiteral("afterend")) {
3266 position
= eAfterEnd
;
3268 aError
.Throw(NS_ERROR_DOM_SYNTAX_ERR
);
3272 nsCOMPtr
<nsIContent
> destination
;
3273 if (position
== eBeforeBegin
|| position
== eAfterEnd
) {
3274 destination
= GetParent();
3276 aError
.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR
);
3283 nsIDocument
* doc
= OwnerDoc();
3285 // Needed when insertAdjacentHTML is used in combination with contenteditable
3286 mozAutoDocUpdate
updateBatch(doc
, UPDATE_CONTENT_MODEL
, true);
3287 nsAutoScriptLoaderDisabler
sld(doc
);
3289 // Batch possible DOMSubtreeModified events.
3290 mozAutoSubtreeModified
subtree(doc
, nullptr);
3292 // Parse directly into destination if possible
3293 if (doc
->IsHTML() && !OwnerDoc()->MayHaveDOMMutationObservers() &&
3294 (position
== eBeforeEnd
||
3295 (position
== eAfterEnd
&& !GetNextSibling()) ||
3296 (position
== eAfterBegin
&& !GetFirstChild()))) {
3297 int32_t oldChildCount
= destination
->GetChildCount();
3298 int32_t contextNs
= destination
->GetNameSpaceID();
3299 nsIAtom
* contextLocal
= destination
->Tag();
3300 if (contextLocal
== nsGkAtoms::html
&& contextNs
== kNameSpaceID_XHTML
) {
3301 // For compat with IE6 through IE9. Willful violation of HTML5 as of
3302 // 2011-04-06. CreateContextualFragment does the same already.
3303 // Spec bug: http://www.w3.org/Bugs/Public/show_bug.cgi?id=12434
3304 contextLocal
= nsGkAtoms::body
;
3306 aError
= nsContentUtils::ParseFragmentHTML(aText
,
3310 doc
->GetCompatibilityMode() ==
3311 eCompatibility_NavQuirks
,
3313 // HTML5 parser has notified, but not fired mutation events.
3314 nsContentUtils::FireMutationEventsForDirectParsing(doc
, destination
,
3319 // couldn't parse directly
3320 nsCOMPtr
<nsIDOMDocumentFragment
> df
;
3321 aError
= nsContentUtils::CreateContextualFragment(destination
,
3324 getter_AddRefs(df
));
3325 if (aError
.Failed()) {
3329 nsCOMPtr
<nsINode
> fragment
= do_QueryInterface(df
);
3331 // Suppress assertion about node removal mutation events that can't have
3332 // listeners anyway, because no one has had the chance to register mutation
3333 // listeners on the fragment that comes from the parser.
3334 nsAutoScriptBlockerSuppressNodeRemoved scriptBlocker
;
3336 nsAutoMutationBatch
mb(destination
, true, false);
3339 destination
->InsertBefore(*fragment
, this, aError
);
3342 static_cast<nsINode
*>(this)->InsertBefore(*fragment
, GetFirstChild(),
3346 static_cast<nsINode
*>(this)->AppendChild(*fragment
, aError
);
3349 destination
->InsertBefore(*fragment
, GetNextSibling(), aError
);
3355 Element::GetEditorInternal()
3357 nsCOMPtr
<nsITextControlElement
> textCtrl
= do_QueryInterface(this);
3358 return textCtrl
? textCtrl
->GetTextEditor() : nullptr;
3362 Element::SetBoolAttr(nsIAtom
* aAttr
, bool aValue
)
3365 return SetAttr(kNameSpaceID_None
, aAttr
, EmptyString(), true);
3368 return UnsetAttr(kNameSpaceID_None
, aAttr
, true);
3372 Element::GetEnumAttr(nsIAtom
* aAttr
,
3373 const char* aDefault
,
3374 nsAString
& aResult
) const
3376 GetEnumAttr(aAttr
, aDefault
, aDefault
, aResult
);
3380 Element::GetEnumAttr(nsIAtom
* aAttr
,
3381 const char* aDefaultMissing
,
3382 const char* aDefaultInvalid
,
3383 nsAString
& aResult
) const
3385 const nsAttrValue
* attrVal
= mAttrsAndChildren
.GetAttr(aAttr
);
3390 if (aDefaultMissing
) {
3391 AppendASCIItoUTF16(nsDependentCString(aDefaultMissing
), aResult
);
3393 SetDOMStringToNull(aResult
);
3396 if (attrVal
->Type() == nsAttrValue::eEnum
) {
3397 attrVal
->GetEnumString(aResult
, true);
3398 } else if (aDefaultInvalid
) {
3399 AppendASCIItoUTF16(nsDependentCString(aDefaultInvalid
), aResult
);
3405 Element::SetOrRemoveNullableStringAttr(nsIAtom
* aName
, const nsAString
& aValue
,
3406 ErrorResult
& aError
)
3408 if (DOMStringIsNull(aValue
)) {
3409 UnsetAttr(aName
, aError
);
3411 SetAttr(aName
, aValue
, aError
);
3416 Element::GetComputedDirectionality() const
3418 nsIFrame
* frame
= GetPrimaryFrame();
3420 return frame
->StyleVisibility()->mDirection
== NS_STYLE_DIRECTION_LTR
3421 ? eDir_LTR
: eDir_RTL
;
3424 return GetDirectionality();
3428 Element::FontSizeInflation()
3430 nsIFrame
* frame
= GetPrimaryFrame();
3435 if (nsLayoutUtils::FontSizeInflationEnabled(frame
->PresContext())) {
3436 return nsLayoutUtils::FontSizeInflationFor(frame
);