Bumping manifests a=b2g-bump
[gecko.git] / dom / base / Element.cpp
bloba9ba38d6370715c9bdd7a3e5933efcc74e585366
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/. */
7 /*
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"
20 #include "nsIAtom.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"
31 #include "nsIURL.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"
38 #include "nsString.h"
39 #include "nsUnicharUtils.h"
40 #include "nsIDOMEvent.h"
41 #include "nsDOMCID.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"
51 #include "nsError.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"
69 #ifdef MOZ_XUL
70 #include "nsXULElement.h"
71 #endif /* MOZ_XUL */
72 #include "nsSVGElement.h"
73 #include "nsFrameSelection.h"
74 #ifdef DEBUG
75 #include "nsRange.h"
76 #endif
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"
102 #include "nsView.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"
110 #ifdef MOZ_XUL
111 #include "nsIXULDocument.h"
112 #endif /* MOZ_XUL */
114 #include "nsCycleCollectionParticipant.h"
115 #include "nsCCUncollectableMarker.h"
117 #include "mozAutoDocUpdate.h"
119 #include "nsCSSParser.h"
120 #include "prprf.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;
146 nsIAtom*
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();
155 const nsAttrValue*
156 nsIContent::DoGetClasses() const
158 MOZ_ASSERT(HasFlag(NODE_MAY_HAVE_CLASS), "Unexpected call");
159 MOZ_ASSERT(IsElement(), "Only elements can have classes");
161 if (IsSVG()) {
162 const nsAttrValue* animClass =
163 static_cast<const nsSVGElement*>(this)->GetAnimatedClassName();
164 if (animClass) {
165 return animClass;
169 return AsElement()->GetParsedAttr(nsGkAtoms::_class);
172 NS_IMETHODIMP
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)) {
179 return NS_OK;
182 // Give the binding manager a chance to get an interface for this element.
183 return OwnerDoc()->BindingManager()->GetBindingImplementation(this, aIID,
184 aInstancePtr);
187 EventStates
188 Element::IntrinsicState() const
190 return IsEditable() ? NS_EVENT_STATE_MOZ_READWRITE :
191 NS_EVENT_STATE_MOZ_READONLY;
194 void
195 Element::NotifyStateChange(EventStates aStates)
197 nsIDocument* doc = GetCrossShadowCurrentDoc();
198 if (doc) {
199 nsAutoScriptBlocker scriptBlocker;
200 doc->ContentStateChanged(this, aStates);
204 void
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");
210 mState =
211 (mState & ~(NS_EVENT_STATE_VISITED | NS_EVENT_STATE_UNVISITED)) |
212 aState;
215 void
216 Element::UpdateState(bool aNotify)
218 EventStates oldState = mState;
219 mState = IntrinsicState() | (oldState & ESM_MANAGED_STATES);
220 if (aNotify) {
221 EventStates changedStates = oldState ^ mState;
222 if (!changedStates.IsEmpty()) {
223 nsIDocument* doc = GetCrossShadowCurrentDoc();
224 if (doc) {
225 nsAutoScriptBlocker scriptBlocker;
226 doc->ContentStateChanged(this, changedStates);
232 void
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
240 // can't clear later
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
249 if (root) {
250 nsIFrame* rootFrame = root->GetPrimaryFrame();
251 if (rootFrame) {
252 nsContainerFrame* parentFrame = rootFrame->GetParent();
253 nsITextControlFrame* textCtrl = do_QueryFrame(parentFrame);
254 isUnknownNativeAnon = !textCtrl;
259 SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE) &&
260 !isUnknownNativeAnon);
263 void
264 Element::UpdateEditableState(bool aNotify)
266 nsIContent *parent = GetParent();
268 SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE));
269 if (aNotify) {
270 UpdateState(aNotify);
271 } else {
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.
276 if (IsEditable()) {
277 RemoveStatesSilently(NS_EVENT_STATE_MOZ_READONLY);
278 AddStatesSilently(NS_EVENT_STATE_MOZ_READWRITE);
279 } else {
280 RemoveStatesSilently(NS_EVENT_STATE_MOZ_READWRITE);
281 AddStatesSilently(NS_EVENT_STATE_MOZ_READONLY);
286 EventStates
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;
298 return state;
301 EventStates
302 Element::LockedStyleStates() const
304 EventStates* locks =
305 static_cast<EventStates*>(GetProperty(nsGkAtoms::lockedStyleStates));
306 if (locks) {
307 return *locks;
309 return EventStates();
312 void
313 Element::NotifyStyleStateChange(EventStates aStates)
315 nsIDocument* doc = GetComposedDoc();
316 if (doc) {
317 nsIPresShell *presShell = doc->GetShell();
318 if (presShell) {
319 nsAutoScriptBlocker scriptBlocker;
320 presShell->ContentStateChanged(doc, this, aStates);
325 void
326 Element::LockStyleStates(EventStates aStates)
328 EventStates* locks = new EventStates(LockedStyleStates());
330 *locks |= aStates;
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);
346 void
347 Element::UnlockStyleStates(EventStates aStates)
349 EventStates* locks = new EventStates(LockedStyleStates());
351 *locks &= ~aStates;
353 if (locks->IsEmpty()) {
354 DeleteProperty(nsGkAtoms::lockedStyleStates);
355 ClearHasLockedStyleStates();
356 delete locks;
358 else {
359 SetProperty(nsGkAtoms::lockedStyleStates, locks,
360 nsINode::DeleteProperty<EventStates>);
363 NotifyStyleStateChange(aStates);
366 void
367 Element::ClearStyleStateLocks()
369 EventStates locks = LockedStyleStates();
371 DeleteProperty(nsGkAtoms::lockedStyleStates);
372 ClearHasLockedStyleStates();
374 NotifyStyleStateChange(locks);
377 bool
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) {
390 *aResult = nullptr;
392 return true;
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,
400 nullptr);
401 NS_ENSURE_TRUE(sc, false);
403 *aResult = sc->StyleDisplay()->mBinding;
405 return true;
408 JSObject*
409 Element::WrapObject(JSContext *aCx)
411 JS::Rooted<JSObject*> obj(aCx, nsINode::WrapObject(aCx));
412 if (!obj) {
413 return nullptr;
416 // Custom element prototype swizzling.
417 CustomElementData* data = GetCustomElementData();
418 if (obj && data) {
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);
424 if (prototype) {
425 if (!JS_WrapObject(aCx, &prototype) || !JS_SetPrototype(aCx, obj, prototype)) {
426 dom::Throw(aCx, NS_ERROR_FAILURE);
427 return nullptr;
432 nsIDocument* doc;
433 if (HasFlag(NODE_FORCE_XBL_BINDINGS)) {
434 doc = OwnerDoc();
436 else {
437 doc = GetComposedDoc();
440 if (!doc) {
441 // There's no baseclass that cares about this call so we just
442 // return here.
443 return obj;
446 // We must ensure that the XBL Binding is installed before we hand
447 // back this object.
449 if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR) && GetXBLBinding()) {
450 // There's already a binding for this element so nothing left to
451 // be done here.
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
456 // inconsistencies.
457 return obj;
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);
464 if (!ok) {
465 dom::Throw(aCx, NS_ERROR_FAILURE);
466 return nullptr;
469 if (!bindingURL) {
470 // No binding, nothing left to do here.
471 return obj;
474 nsCOMPtr<nsIURI> uri = bindingURL->GetURI();
475 nsCOMPtr<nsIPrincipal> principal = bindingURL->mOriginPrincipal;
477 // We have a binding that must be installed.
478 bool dummy;
480 nsXBLService* xblService = nsXBLService::GetInstance();
481 if (!xblService) {
482 dom::Throw(aCx, NS_ERROR_NOT_AVAILABLE);
483 return nullptr;
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);
491 if (binding) {
492 if (nsContentUtils::IsSafeToRunScript()) {
493 binding->ExecuteAttachedHandler();
495 else {
496 nsContentUtils::AddScriptRunner(
497 NS_NewRunnableMethod(binding, &nsXBLBinding::ExecuteAttachedHandler));
502 return obj;
505 /* virtual */
506 nsINode*
507 Element::GetScopeChainParent() const
509 return OwnerDoc();
512 nsDOMTokenList*
513 Element::ClassList()
515 Element::nsDOMSlots* slots = DOMSlots();
517 if (!slots->mClassList) {
518 slots->mClassList = new nsDOMTokenList(this, nsGkAtoms::_class);
521 return slots->mClassList;
524 void
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);
536 void
537 Element::GetElementsByTagName(const nsAString& aLocalName,
538 nsIDOMHTMLCollection** aResult)
540 *aResult = GetElementsByTagName(aLocalName).take();
543 nsIFrame*
544 Element::GetStyledFrame()
546 nsIFrame *frame = GetPrimaryFrame(Flush_Layout);
547 return frame ? nsLayoutUtils::GetStyleFrame(frame) : nullptr;
550 nsIScrollableFrame*
551 Element::GetScrollFrame(nsIFrame **aStyledFrame, bool aFlushLayout)
553 // it isn't clear what to return for SVG nodes, so just return nothing
554 if (IsSVG()) {
555 if (aStyledFrame) {
556 *aStyledFrame = nullptr;
558 return nullptr;
561 // Inline version of GetStyledFrame to use Flush_None if needed.
562 nsIFrame* frame = GetPrimaryFrame(aFlushLayout ? Flush_Layout : Flush_None);
563 if (frame) {
564 frame = nsLayoutUtils::GetStyleFrame(frame);
567 if (aStyledFrame) {
568 *aStyledFrame = frame;
570 if (!frame) {
571 return nullptr;
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();
579 if (scrollFrame)
580 return scrollFrame;
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();
595 return nullptr;
598 void
599 Element::ScrollIntoView()
601 ScrollIntoView(ScrollIntoViewOptions());
604 void
605 Element::ScrollIntoView(bool aTop)
607 ScrollIntoViewOptions options;
608 if (!aTop) {
609 options.mBlock = ScrollLogicalPosition::End;
611 ScrollIntoView(options);
614 void
615 Element::ScrollIntoView(const ScrollIntoViewOptions &aOptions)
617 nsIDocument *document = GetComposedDoc();
618 if (!document) {
619 return;
622 // Get the presentation shell
623 nsCOMPtr<nsIPresShell> presShell = document->GetShell();
624 if (!presShell) {
625 return;
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(
641 vpercent,
642 nsIPresShell::SCROLL_ALWAYS),
643 nsIPresShell::ScrollAxis(),
644 flags);
647 void
648 Element::Scroll(const CSSIntPoint& aScroll, const ScrollOptions& aOptions)
650 nsIScrollableFrame* sf = GetScrollFrame();
651 if (sf) {
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);
666 void
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());
676 void
677 Element::Scroll(const ScrollToOptions& aOptions)
679 nsIScrollableFrame *sf = GetScrollFrame();
680 if (sf) {
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);
692 void
693 Element::ScrollTo(double aXScroll, double aYScroll)
695 Scroll(aXScroll, aYScroll);
698 void
699 Element::ScrollTo(const ScrollToOptions& aOptions)
701 Scroll(aOptions);
704 void
705 Element::ScrollBy(double aXScrollDif, double aYScrollDif)
707 nsIScrollableFrame *sf = GetScrollFrame();
708 if (sf) {
709 CSSIntPoint scrollPos = sf->GetScrollPositionCSSPixels();
710 scrollPos += CSSIntPoint(mozilla::ToZeroIfNonfinite(aXScrollDif),
711 mozilla::ToZeroIfNonfinite(aYScrollDif));
712 Scroll(scrollPos, ScrollOptions());
716 void
717 Element::ScrollBy(const ScrollToOptions& aOptions)
719 nsIScrollableFrame *sf = GetScrollFrame();
720 if (sf) {
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);
732 int32_t
733 Element::ScrollTop()
735 nsIScrollableFrame* sf = GetScrollFrame();
736 return sf ? sf->GetScrollPositionCSSPixels().y : 0;
739 void
740 Element::SetScrollTop(int32_t aScrollTop)
742 nsIScrollableFrame* sf = GetScrollFrame();
743 if (sf) {
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,
749 aScrollTop),
750 scrollMode);
754 int32_t
755 Element::ScrollLeft()
757 nsIScrollableFrame* sf = GetScrollFrame();
758 return sf ? sf->GetScrollPositionCSSPixels().x : 0;
761 void
762 Element::SetScrollLeft(int32_t aScrollLeft)
764 nsIScrollableFrame* sf = GetScrollFrame();
765 if (sf) {
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),
773 scrollMode);
778 bool
779 Element::ScrollByNoFlush(int32_t aDx, int32_t aDy)
781 nsIScrollableFrame* sf = GetScrollFrame(nullptr, false);
782 if (!sf) {
783 return 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()) {
793 return false;
796 CSSIntPoint after = sf->GetScrollPositionCSSPixels();
797 return (before != after);
800 static nsSize GetScrollRectSizeForOverflowVisibleFrame(nsIFrame* aFrame)
802 if (!aFrame) {
803 return nsSize(0,0);
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();
822 int32_t
823 Element::ScrollHeight()
825 if (IsSVG())
826 return 0;
828 nsIScrollableFrame* sf = GetScrollFrame();
829 nscoord height;
830 if (sf) {
831 height = sf->GetScrollRange().height + sf->GetScrollPortRect().height;
832 } else {
833 height = GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).height;
836 return nsPresContext::AppUnitsToIntCSSPixels(height);
839 int32_t
840 Element::ScrollWidth()
842 if (IsSVG())
843 return 0;
845 nsIScrollableFrame* sf = GetScrollFrame();
846 nscoord width;
847 if (sf) {
848 width = sf->GetScrollRange().width + sf->GetScrollPortRect().width;
849 } else {
850 width = GetScrollRectSizeForOverflowVisibleFrame(GetStyledFrame()).width;
853 return nsPresContext::AppUnitsToIntCSSPixels(width);
856 nsRect
857 Element::GetClientAreaRect()
859 nsIFrame* styledFrame;
860 nsIScrollableFrame* sf = GetScrollFrame(&styledFrame);
862 if (sf) {
863 return sf->GetScrollPortRect();
866 if (styledFrame &&
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);
884 if (!frame) {
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);
902 if (!frame) {
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 //----------------------------------------------------------------------
917 void
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);
924 } else {
925 nsIDocument* doc = GetUncomposedDoc();
926 if (doc && (!IsInAnonymousSubtree() || doc->IsXUL())) {
927 doc->AddToIdTable(this, aId);
932 void
933 Element::RemoveFromIdTable()
935 if (!HasID()) {
936 return;
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);
947 } else {
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()) {
971 delete protoBinding;
972 return nullptr;
975 nsIDocument* doc = GetCrossShadowCurrentDoc();
976 nsIContent* destroyedFramesFor = nullptr;
977 if (doc) {
978 nsIPresShell* shell = doc->GetShell();
979 if (shell) {
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(),
993 protoBinding);
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);
1001 if (olderShadow) {
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.
1021 if (doc) {
1022 MOZ_ASSERT(doc == GetCrossShadowCurrentDoc());
1023 nsIPresShell* shell = doc->GetShell();
1024 if (shell) {
1025 shell->CreateFramesFor(destroyedFramesFor);
1029 return shadowRoot.forget();
1032 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(DestinationInsertionPointList, mParent,
1033 mDestinationPoints)
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)
1045 : mParent(aElement)
1047 nsTArray<nsIContent*>* destPoints = aElement->GetExistingDestInsertionPoints();
1048 if (destPoints) {
1049 for (uint32_t i = 0; i < destPoints->Length(); i++) {
1050 mDestinationPoints.AppendElement(destPoints->ElementAt(i));
1055 DestinationInsertionPointList::~DestinationInsertionPointList()
1059 nsIContent*
1060 DestinationInsertionPointList::Item(uint32_t aIndex)
1062 return mDestinationPoints.SafeElementAt(aIndex);
1065 NS_IMETHODIMP
1066 DestinationInsertionPointList::Item(uint32_t aIndex, nsIDOMNode** aReturn)
1068 nsIContent* item = Item(aIndex);
1069 if (!item) {
1070 return NS_ERROR_FAILURE;
1073 return CallQueryInterface(item, aReturn);
1076 uint32_t
1077 DestinationInsertionPointList::Length() const
1079 return mDestinationPoints.Length();
1082 NS_IMETHODIMP
1083 DestinationInsertionPointList::GetLength(uint32_t* aLength)
1085 *aLength = Length();
1086 return NS_OK;
1089 int32_t
1090 DestinationInsertionPointList::IndexOf(nsIContent* aContent)
1092 return mDestinationPoints.IndexOf(aContent);
1095 JSObject*
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();
1109 void
1110 Element::GetAttribute(const nsAString& aName, DOMString& aReturn)
1112 const nsAttrValue* val =
1113 mAttrsAndChildren.GetAttr(aName,
1114 IsHTML() && IsInHTMLDocument() ?
1115 eIgnoreCase : eCaseMatters);
1116 if (val) {
1117 val->ToString(aReturn);
1118 } else {
1119 if (IsXUL()) {
1120 // XXX should be SetDOMStringToNull(aReturn);
1121 // See bug 232598
1122 // aReturn is already empty
1123 } else {
1124 aReturn.SetNull();
1129 void
1130 Element::SetAttribute(const nsAString& aName,
1131 const nsAString& aValue,
1132 ErrorResult& aError)
1134 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
1136 if (!name) {
1137 aError = nsContentUtils::CheckQName(aName, false);
1138 if (aError.Failed()) {
1139 return;
1142 nsCOMPtr<nsIAtom> nameAtom;
1143 if (IsHTML() && IsInHTMLDocument()) {
1144 nsAutoString lower;
1145 nsContentUtils::ASCIIToLower(aName, lower);
1146 nameAtom = do_GetAtom(lower);
1148 else {
1149 nameAtom = do_GetAtom(aName);
1151 if (!nameAtom) {
1152 aError.Throw(NS_ERROR_OUT_OF_MEMORY);
1153 return;
1155 aError = SetAttr(kNameSpaceID_None, nameAtom, aValue, true);
1156 return;
1159 aError = SetAttr(name->NamespaceID(), name->LocalName(), name->GetPrefix(),
1160 aValue, true);
1161 return;
1164 void
1165 Element::RemoveAttribute(const nsAString& aName, ErrorResult& aError)
1167 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
1169 if (!name) {
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.
1173 return;
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);
1184 Attr*
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);
1207 void
1208 Element::GetAttributeNS(const nsAString& aNamespaceURI,
1209 const nsAString& aLocalName,
1210 nsAString& aReturn)
1212 int32_t nsid =
1213 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
1215 if (nsid == kNameSpaceID_Unknown) {
1216 // Unknown namespace means no attribute.
1217 SetDOMStringToNull(aReturn);
1218 return;
1221 nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
1222 bool hasAttr = GetAttr(nsid, name, aReturn);
1223 if (!hasAttr) {
1224 SetDOMStringToNull(aReturn);
1228 void
1229 Element::SetAttributeNS(const nsAString& aNamespaceURI,
1230 const nsAString& aQualifiedName,
1231 const nsAString& aValue,
1232 ErrorResult& aError)
1234 nsRefPtr<mozilla::dom::NodeInfo> ni;
1235 aError =
1236 nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName,
1237 mNodeInfo->NodeInfoManager(),
1238 nsIDOMNode::ATTRIBUTE_NODE,
1239 getter_AddRefs(ni));
1240 if (aError.Failed()) {
1241 return;
1244 aError = SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(),
1245 aValue, true);
1248 void
1249 Element::RemoveAttributeNS(const nsAString& aNamespaceURI,
1250 const nsAString& aLocalName,
1251 ErrorResult& aError)
1253 nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
1254 int32_t nsid =
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.
1261 return;
1264 aError = UnsetAttr(nsid, name, true);
1267 Attr*
1268 Element::GetAttributeNodeNS(const nsAString& aNamespaceURI,
1269 const nsAString& aLocalName)
1271 OwnerDoc()->WarnOnceAbout(nsIDocument::eGetAttributeNodeNS);
1273 return GetAttributeNodeNSInternal(aNamespaceURI, aLocalName);
1276 Attr*
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("*")) {
1299 aError =
1300 nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI,
1301 nameSpaceId);
1302 if (aError.Failed()) {
1303 return nullptr;
1307 NS_ASSERTION(nameSpaceId != kNameSpaceID_Unknown, "Unexpected namespace ID!");
1309 return NS_GetContentList(this, nameSpaceId, aLocalName);
1312 nsresult
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);
1320 if (rv.Failed()) {
1321 return rv.ErrorCode();
1323 list.forget(aResult);
1324 return NS_OK;
1327 bool
1328 Element::HasAttributeNS(const nsAString& aNamespaceURI,
1329 const nsAString& aLocalName) const
1331 int32_t nsid =
1332 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
1334 if (nsid == kNameSpaceID_Unknown) {
1335 // Unknown namespace means no attr...
1336 return false;
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);
1349 nsresult
1350 Element::GetElementsByClassName(const nsAString& aClassNames,
1351 nsIDOMHTMLCollection** aResult)
1353 *aResult =
1354 nsContentUtils::GetElementsByClassName(this, aClassNames).take();
1355 return NS_OK;
1358 nsresult
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");
1391 #ifdef MOZ_XUL
1392 // First set the binding parent
1393 nsXULElement* xulElem = nsXULElement::FromContent(this);
1394 if (xulElem) {
1395 xulElem->SetXULBindingParent(aBindingParent);
1397 else
1398 #endif
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!");
1411 if (aParent) {
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.
1431 if (aParent) {
1432 if (!GetParent()) {
1433 NS_ADDREF(aParent);
1435 mParent = aParent;
1437 if (aParent->HasFlag(NODE_FORCE_XBL_BINDINGS)) {
1438 SetFlags(NODE_FORCE_XBL_BINDINGS);
1441 else {
1442 mParent = aDocument;
1444 SetParentIsContent(aParent);
1446 // XXXbz sXBL/XBL2 issue!
1448 // Finally, set the document
1449 if (aDocument) {
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,
1457 // aDocument);
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.
1464 SetInDocument();
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);
1489 } else {
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()) {
1497 nsIContent* parent;
1498 ShadowRoot* shadowRootParent = ShadowRoot::FromNode(mParent);
1499 if (shadowRootParent) {
1500 parent = shadowRootParent->GetHost();
1501 } else {
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.
1514 if (IsHTML()) {
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.
1520 nsresult rv;
1521 if (hadForceXBL) {
1522 nsBindingManager* bmgr = OwnerDoc()->BindingManager();
1524 nsXBLBinding* contBinding = bmgr->GetBindingWithContent(this);
1525 // First check if we have a binding...
1526 if (contBinding) {
1527 nsCOMPtr<nsIContent> anonRoot = contBinding->GetAnonymousContent();
1528 bool allowScripts = contBinding->AllowScripts();
1529 for (nsCOMPtr<nsIContent> child = anonRoot->GetFirstChild();
1530 child;
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);
1550 if (HasID()) {
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);
1561 if (aDocument) {
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();
1567 if (sheet) {
1568 mAttrsAndChildren.SetMappedAttrStyleSheet(sheet);
1572 // Call BindToTree on shadow root children.
1573 ShadowRoot* shadowRoot = GetShadowRoot();
1574 if (shadowRoot) {
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");
1592 return NS_OK;
1595 RemoveFromBindingManagerRunnable::RemoveFromBindingManagerRunnable(nsBindingManager* aManager,
1596 nsIContent* aContent,
1597 nsIDocument* aDoc):
1598 mManager(aManager), mContent(aContent), mDoc(aDoc)
1601 RemoveFromBindingManagerRunnable::~RemoveFromBindingManagerRunnable() {}
1603 NS_IMETHODIMP
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);
1617 return NS_OK;
1621 void
1622 Element::UnbindFromTree(bool aDeep, bool aNullParent)
1624 NS_PRECONDITION(aDeep || (!GetUncomposedDoc() && !GetBindingParent()),
1625 "Shallow unbind won't clear document and binding parent on "
1626 "kids!");
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();
1635 if (aNullParent) {
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();
1649 if (GetParent()) {
1650 nsINode* p = mParent;
1651 mParent = nullptr;
1652 NS_RELEASE(p);
1653 } else {
1654 mParent = nullptr;
1656 SetParentIsContent(false);
1658 ClearInDocument();
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());
1667 if (document) {
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,
1675 document));
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;
1705 #ifdef MOZ_XUL
1706 nsXULElement* xulElem = nsXULElement::FromContent(this);
1707 if (xulElem) {
1708 xulElem->SetXULBindingParent(nullptr);
1709 clearBindingParent = false;
1711 #endif
1713 nsDOMSlots* slots = GetExistingDOMSlots();
1714 if (slots) {
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.
1726 if (IsHTML()) {
1727 ResetDir(this);
1730 if (aDeep) {
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();
1748 if (shadowRoot) {
1749 for (nsIContent* child = shadowRoot->GetFirstChild(); child;
1750 child = child->GetNextSibling()) {
1751 child->UnbindFromTree(true, false);
1756 nsICSSDeclaration*
1757 Element::GetSMILOverrideStyle()
1759 Element::nsDOMSlots *slots = DOMSlots();
1761 if (!slots->mSMILOverrideStyle) {
1762 slots->mSMILOverrideStyle = new nsDOMCSSAttributeDeclaration(this, true);
1765 return slots->mSMILOverrideStyle;
1768 css::StyleRule*
1769 Element::GetSMILOverrideStyleRule()
1771 Element::nsDOMSlots *slots = GetExistingDOMSlots();
1772 return slots ? slots->mSMILOverrideStyleRule.get() : nullptr;
1775 nsresult
1776 Element::SetSMILOverrideStyleRule(css::StyleRule* aStyleRule,
1777 bool aNotify)
1779 Element::nsDOMSlots *slots = DOMSlots();
1781 slots->mSMILOverrideStyleRule = aStyleRule;
1783 if (aNotify) {
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.)
1788 if (doc) {
1789 nsCOMPtr<nsIPresShell> shell = doc->GetShell();
1790 if (shell) {
1791 shell->RestyleForAnimation(this,
1792 eRestyle_StyleAttribute | eRestyle_ChangeAnimationPhase);
1797 return NS_OK;
1800 bool
1801 Element::IsLabelable() const
1803 return false;
1806 css::StyleRule*
1807 Element::GetInlineStyleRule()
1809 return nullptr;
1812 nsresult
1813 Element::SetInlineStyleRule(css::StyleRule* aStyleRule,
1814 const nsAString* aSerialized,
1815 bool aNotify)
1817 NS_NOTYETIMPLEMENTED("Element::SetInlineStyleRule");
1818 return NS_ERROR_NOT_IMPLEMENTED;
1821 NS_IMETHODIMP_(bool)
1822 Element::IsAttributeMapped(const nsIAtom* aAttribute) const
1824 return false;
1827 nsChangeHint
1828 Element::GetAttributeChangeHint(const nsIAtom* aAttribute,
1829 int32_t aModType) const
1831 return nsChangeHint(0);
1834 bool
1835 Element::FindAttributeDependence(const nsIAtom* aAttribute,
1836 const MappedAttributeEntry* const aMaps[],
1837 uint32_t aMapCount)
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) {
1843 return true;
1848 return false;
1851 already_AddRefed<mozilla::dom::NodeInfo>
1852 Element::GetExistingAttrNameFromQName(const nsAString& aStr) const
1854 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aStr);
1855 if (!name) {
1856 return nullptr;
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);
1865 else {
1866 nodeInfo = name->NodeInfo();
1869 return nodeInfo.forget();
1872 // static
1873 bool
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();
1879 if (!document)
1880 return false;
1882 nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(document->GetWindow());
1883 if (!window)
1884 return false;
1886 nsCOMPtr<nsPIDOMWindow> focusedFrame;
1887 nsIContent* contentToBlur =
1888 nsFocusManager::GetFocusedDescendant(window, false, getter_AddRefs(focusedFrame));
1889 if (contentToBlur == aContent)
1890 return true;
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);
1897 bool
1898 Element::IsNodeOfType(uint32_t aFlags) const
1900 return !(aFlags & ~eCONTENT);
1903 /* static */
1904 nsresult
1905 Element::DispatchEvent(nsPresContext* aPresContext,
1906 WidgetEvent* aEvent,
1907 nsIContent* aTarget,
1908 bool aFullDispatch,
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) {
1916 return NS_OK;
1919 nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell();
1920 if (!shell) {
1921 return NS_OK;
1924 if (aFullDispatch) {
1925 return shell->HandleEventWithTarget(aEvent, nullptr, aTarget, aStatus);
1928 return shell->HandleDOMEventWithTarget(aTarget, aEvent, aStatus);
1931 /* static */
1932 nsresult
1933 Element::DispatchClickEvent(nsPresContext* aPresContext,
1934 WidgetInputEvent* aSourceEvent,
1935 nsIContent* aTarget,
1936 bool aFullDispatch,
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;
1948 float pressure = 0;
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);
1970 nsIFrame*
1971 Element::GetPrimaryFrame(mozFlushType aType)
1973 nsIDocument* doc = GetComposedDoc();
1974 if (!doc) {
1975 return nullptr;
1978 // Cause a flush, so we get up-to-date frame
1979 // information
1980 if (aType != Flush_None) {
1981 doc->FlushPendingNotifications(aType);
1984 return GetPrimaryFrame();
1987 //----------------------------------------------------------------------
1988 nsresult
1989 Element::LeaveLink(nsPresContext* aPresContext)
1991 nsILinkHandler *handler = aPresContext->GetLinkHandler();
1992 if (!handler) {
1993 return NS_OK;
1996 return handler->OnLeaveLink();
1999 nsresult
2000 Element::SetEventHandler(nsIAtom* aEventName,
2001 const nsAString& aValue,
2002 bool aDefer)
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.
2008 return NS_OK;
2011 NS_PRECONDITION(aEventName, "Must have event name!");
2012 bool defer = true;
2013 EventListenerManager* manager =
2014 GetEventListenerManagerForAttr(aEventName, &defer);
2015 if (!manager) {
2016 return NS_OK;
2019 defer = defer && aDefer; // only defer if everyone agrees...
2020 manager->SetEventHandler(aEventName, aValue,
2021 defer, !nsContentUtils::IsChromeDoc(ownerDoc),
2022 this);
2023 return NS_OK;
2027 //----------------------------------------------------------------------
2029 const nsAttrName*
2030 Element::InternalGetExistingAttrNameFromQName(const nsAString& aStr) const
2032 return mAttrsAndChildren.GetExistingAttrNameFromQName(aStr);
2035 bool
2036 Element::MaybeCheckSameAttrVal(int32_t aNamespaceID,
2037 nsIAtom* aName,
2038 nsIAtom* aPrefix,
2039 const nsAttrValueOrString& aValue,
2040 bool aNotify,
2041 nsAttrValue& aOldValue,
2042 uint8_t* aModType,
2043 bool* aHasListeners)
2045 bool modification = false;
2046 *aHasListeners = aNotify &&
2047 nsContentUtils::HasMutationListeners(this,
2048 NS_EVENT_BITS_MUTATION_ATTRMODIFIED,
2049 this);
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));
2058 if (info.mValue) {
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()) {
2077 return true;
2079 modification = true;
2082 *aModType = modification ?
2083 static_cast<uint8_t>(nsIDOMMutationEvent::MODIFICATION) :
2084 static_cast<uint8_t>(nsIDOMMutationEvent::ADDITION);
2085 return false;
2088 bool
2089 Element::OnlyNotifySameValueSet(int32_t aNamespaceID, nsIAtom* aName,
2090 nsIAtom* aPrefix,
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)) {
2097 return false;
2100 nsAutoScriptBlocker scriptBlocker;
2101 nsNodeUtils::AttributeSetToCurrentValue(this, aNamespaceID, aName);
2102 return true;
2105 nsresult
2106 Element::SetAttr(int32_t aNamespaceID, nsIAtom* aName,
2107 nsIAtom* aPrefix, const nsAString& aValue,
2108 bool aNotify)
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;
2120 uint8_t modType;
2121 bool hasListeners;
2122 nsAttrValueOrString value(aValue);
2123 nsAttrValue oldValue;
2125 if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify,
2126 oldValue, &modType, &hasListeners)) {
2127 return NS_OK;
2130 nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify);
2131 NS_ENSURE_SUCCESS(rv, rv);
2133 if (aNotify) {
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,
2148 kCallAfterSetAttr);
2151 nsresult
2152 Element::SetParsedAttr(int32_t aNamespaceID, nsIAtom* aName,
2153 nsIAtom* aPrefix, nsAttrValue& aParsedValue,
2154 bool aNotify)
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;
2167 uint8_t modType;
2168 bool hasListeners;
2169 nsAttrValueOrString value(aParsedValue);
2170 nsAttrValue oldValue;
2172 if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify,
2173 oldValue, &modType, &hasListeners)) {
2174 return NS_OK;
2177 nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify);
2178 NS_ENSURE_SUCCESS(rv, rv);
2180 if (aNotify) {
2181 nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType);
2184 return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue,
2185 aParsedValue, modType, hasListeners, aNotify,
2186 kCallAfterSetAttr);
2189 nsresult
2190 Element::SetAttrAndNotify(int32_t aNamespaceID,
2191 nsIAtom* aName,
2192 nsIAtom* aPrefix,
2193 const nsAttrValue& aOldValue,
2194 nsAttrValue& aParsedValue,
2195 uint8_t aModType,
2196 bool aFireMutation,
2197 bool aNotify,
2198 bool aCallAfterSetAttr)
2200 nsresult rv;
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);
2230 else {
2231 nsRefPtr<mozilla::dom::NodeInfo> ni;
2232 ni = mNodeInfo->NodeInfoManager()->GetNodeInfo(aName, aPrefix,
2233 aNamespaceID,
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();
2242 if (binding) {
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);
2273 if (aNotify) {
2274 nsNodeUtils::AttributeChanged(this, aNamespaceID, aName, aModType);
2277 if (aFireMutation) {
2278 InternalMutationEvent mutation(true, NS_MUTATION_ATTRMODIFIED);
2280 nsAutoString ns;
2281 nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID, ns);
2282 Attr* attrNode =
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();
2301 return NS_OK;
2304 bool
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);
2314 return true;
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()) {
2321 ClearHasID();
2322 return false;
2324 aResult.ParseAtom(aValue);
2325 SetHasID();
2326 AddToIdTable(aResult.GetAtomValue());
2327 return true;
2331 return false;
2334 bool
2335 Element::SetMappedAttribute(nsIDocument* aDocument,
2336 nsIAtom* aName,
2337 nsAttrValue& aValue,
2338 nsresult* aRetval)
2340 *aRetval = NS_OK;
2341 return false;
2344 EventListenerManager*
2345 Element::GetEventListenerManagerForAttr(nsIAtom* aAttrName,
2346 bool* aDefer)
2348 *aDefer = true;
2349 return GetOrCreateListenerManager();
2352 Element::nsAttrInfo
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);
2360 if (index >= 0) {
2361 return nsAttrInfo(mAttrsAndChildren.AttrNameAt(index),
2362 mAttrsAndChildren.AttrAt(index));
2365 return nsAttrInfo(nullptr, nullptr);
2369 bool
2370 Element::GetAttr(int32_t aNameSpaceID, nsIAtom* aName,
2371 nsAString& aResult) const
2373 DOMString str;
2374 bool haveAttr = GetAttr(aNameSpaceID, aName, str);
2375 str.ToString(aResult);
2376 return haveAttr;
2379 int32_t
2380 Element::FindAttrValueIn(int32_t aNameSpaceID,
2381 nsIAtom* aName,
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);
2390 if (val) {
2391 for (int32_t i = 0; aValues[i]; ++i) {
2392 if (val->Equals(*aValues[i], aCaseSensitive)) {
2393 return i;
2396 return ATTR_VALUE_NO_MATCH;
2398 return ATTR_MISSING;
2401 nsresult
2402 Element::UnsetAttr(int32_t aNameSpaceID, nsIAtom* aName,
2403 bool aNotify)
2405 NS_ASSERTION(nullptr != aName, "must have attribute name");
2407 int32_t index = mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID);
2408 if (index < 0) {
2409 return NS_OK;
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);
2418 if (aNotify) {
2419 nsNodeUtils::AttributeWillChange(this, aNameSpaceID, aName,
2420 nsIDOMMutationEvent::REMOVAL);
2423 bool hasMutationListeners = aNotify &&
2424 nsContentUtils::HasMutationListeners(this,
2425 NS_EVENT_BITS_MUTATION_ATTRMODIFIED,
2426 this);
2428 // Grab the attr node if needed before we remove it from the attr map
2429 nsRefPtr<Attr> attrNode;
2430 if (hasMutationListeners) {
2431 nsAutoString ns;
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();
2449 ClearHasID();
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();
2466 if (binding) {
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),
2479 NullString()
2482 ownerDoc->EnqueueLifecycleCallback(nsIDocument::eAttributeChanged, this, &args);
2485 if (aNotify) {
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;
2503 nsAutoString value;
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();
2513 return NS_OK;
2516 const nsAttrName*
2517 Element::GetAttrNameAt(uint32_t aIndex) const
2519 return mAttrsAndChildren.GetSafeAttrNameAt(aIndex);
2522 uint32_t
2523 Element::GetAttrCount() const
2525 return mAttrsAndChildren.AttrCount();
2528 void
2529 Element::DescribeAttribute(uint32_t index, nsAString& aOutDescription) const
2531 // name
2532 mAttrsAndChildren.AttrNameAt(index)->GetQualifiedName(aOutDescription);
2534 // value
2535 aOutDescription.AppendLiteral("=\"");
2536 nsAutoString value;
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('"');
2546 #ifdef DEBUG
2547 void
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);
2555 fputs(" ", out);
2556 fputs(NS_LossyConvertUTF16toASCII(attributeDescription).get(), out);
2560 void
2561 Element::List(FILE* out, int32_t aIndent,
2562 const nsCString& aPrefix) const
2564 int32_t indent;
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();
2587 if (child) {
2588 fputs("\n", out);
2590 for (; child; child = child->GetNextSibling()) {
2591 child->List(out, aIndent + 1);
2594 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
2597 fputs(">\n", 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);
2626 fputs(">\n", out);
2628 bool outHeader = false;
2629 ExplicitChildIterator iter(nonConstThis);
2630 for (nsIContent* child = iter.GetNextChild(); child; child = iter.GetNextChild()) {
2631 if (!outHeader) {
2632 outHeader = true;
2634 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
2635 fputs("content-list<\n", out);
2638 child->List(out, aIndent + 1);
2641 if (outHeader) {
2642 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
2643 fputs(">\n", out);
2648 void
2649 Element::DumpContent(FILE* out, int32_t aIndent,
2650 bool aDumpAll) const
2652 int32_t indent;
2653 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
2655 const nsString& buf = mNodeInfo->QualifiedName();
2656 fputs("<", out);
2657 fputs(NS_LossyConvertUTF16toASCII(buf).get(), out);
2659 if(aDumpAll) ListAttributes(out);
2661 fputs(">", out);
2663 if(aIndent) fputs("\n", out);
2665 for (nsIContent* child = GetFirstChild();
2666 child;
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);
2672 fputs("</", out);
2673 fputs(NS_LossyConvertUTF16toASCII(buf).get(), out);
2674 fputs(">", out);
2676 if(aIndent) fputs("\n", out);
2678 #endif
2680 void
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);
2695 bool
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) {
2706 return false;
2709 // Make sure we actually are a link
2710 return IsLink(aURI);
2713 nsresult
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:
2723 break;
2724 default:
2725 return NS_OK;
2728 // Make sure we meet the preconditions before continuing
2729 nsCOMPtr<nsIURI> absURI;
2730 if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
2731 return NS_OK;
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;
2742 // FALL THROUGH
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,
2749 false, true, true);
2750 // Make sure any ancestor links don't also TriggerLink
2751 aVisitor.mEvent->mFlags.mMultipleActionsPrevented = true;
2753 break;
2755 case NS_MOUSE_EXIT_SYNTH:
2756 aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
2757 // FALL THROUGH
2758 case NS_BLUR_CONTENT:
2759 rv = LeaveLink(aVisitor.mPresContext);
2760 if (NS_SUCCEEDED(rv)) {
2761 aVisitor.mEvent->mFlags.mMultipleActionsPrevented = true;
2763 break;
2765 default:
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;
2771 return rv;
2774 nsresult
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:
2783 case NS_KEY_PRESS:
2784 break;
2785 default:
2786 return NS_OK;
2789 // Make sure we meet the preconditions before continuing
2790 nsCOMPtr<nsIURI> absURI;
2791 if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
2792 return NS_OK;
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();
2807 if (fm) {
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);
2819 break;
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()) {
2826 break;
2829 // The default action is simply to dispatch DOMActivate
2830 nsCOMPtr<nsIPresShell> shell = aVisitor.mPresContext->GetPresShell();
2831 if (shell) {
2832 // single-click
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;
2843 break;
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,
2851 true, true,
2852 aVisitor.mEvent->mFlags.mIsTrusted);
2853 aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
2856 break;
2858 case NS_KEY_PRESS:
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;
2870 break;
2872 default:
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;
2878 return rv;
2881 void
2882 Element::GetLinkTarget(nsAString& aTarget)
2884 aTarget.Truncate();
2887 static void
2888 nsDOMSettableTokenListPropertyDestructor(void *aObject, nsIAtom *aProperty,
2889 void *aPropertyValue, void *aData)
2891 nsDOMSettableTokenList* list =
2892 static_cast<nsDOMSettableTokenList*>(aPropertyValue);
2893 NS_RELEASE(list);
2896 static nsIAtom** sPropertiesToTraverseAndUnlink[] =
2898 &nsGkAtoms::microdataProperties,
2899 &nsGkAtoms::itemtype,
2900 &nsGkAtoms::itemref,
2901 &nsGkAtoms::itemprop,
2902 &nsGkAtoms::sandbox,
2903 &nsGkAtoms::sizes,
2904 nullptr
2907 // static
2908 nsIAtom***
2909 Element::HTMLSVGPropertiesToTraverseAndUnlink()
2911 return sPropertiesToTraverseAndUnlink;
2914 nsDOMSettableTokenList*
2915 Element::GetTokenList(nsIAtom* aAtom)
2917 #ifdef DEBUG
2918 nsIAtom*** props =
2919 HTMLSVGPropertiesToTraverseAndUnlink();
2920 bool found = false;
2921 for (uint32_t i = 0; props[i]; ++i) {
2922 if (*props[i] == aAtom) {
2923 found = true;
2924 break;
2927 MOZ_ASSERT(found, "Trying to use an unknown tokenlist!");
2928 #endif
2930 nsDOMSettableTokenList* list = nullptr;
2931 if (HasProperties()) {
2932 list = static_cast<nsDOMSettableTokenList*>(GetProperty(aAtom));
2934 if (!list) {
2935 list = new nsDOMSettableTokenList(this, aAtom);
2936 NS_ADDREF(list);
2937 SetProperty(aAtom, list, nsDOMSettableTokenListPropertyDestructor);
2939 return list;
2942 void
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);
2951 nsresult
2952 Element::SetTokenList(nsIAtom* aAtom, nsIVariant* aValue)
2954 nsDOMSettableTokenList* itemType = GetTokenList(aAtom);
2955 nsAutoString string;
2956 aValue->GetAsAString(string);
2957 ErrorResult rv;
2958 itemType->SetValue(string, rv);
2959 return rv.ErrorCode();
2962 Element*
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.
2969 return nullptr;
2971 OwnerDoc()->FlushPendingLinkUpdates();
2972 TreeMatchContext matchingContext(false,
2973 nsRuleWalker::eRelevantLinkUnvisited,
2974 OwnerDoc(),
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(),
2981 matchingContext,
2982 selectorList)) {
2983 return node->AsElement();
2986 return nullptr;
2989 bool
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.
2996 return false;
2999 OwnerDoc()->FlushPendingLinkUpdates();
3000 TreeMatchContext matchingContext(false,
3001 nsRuleWalker::eRelevantLinkUnvisited,
3002 OwnerDoc(),
3003 TreeMatchContext::eNeverMatchVisited);
3004 matchingContext.SetHasSpecifiedScope();
3005 matchingContext.AddScopeElement(this);
3006 return nsCSSRuleProcessor::SelectorListMatches(this, matchingContext,
3007 selectorList);
3010 static const nsAttrValue::EnumTable kCORSAttributeTable[] = {
3011 // Order matters here
3012 // See ParseCORSValue
3013 { "anonymous", CORS_ANONYMOUS },
3014 { "use-credentials", CORS_USE_CREDENTIALS },
3015 { 0 }
3018 /* static */ void
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()) {
3034 return CORS_NONE;
3037 nsAttrValue val;
3038 Element::ParseCORSValue(aValue, val);
3039 return CORSMode(val.GetEnumValue());
3042 /* static */ CORSMode
3043 Element::AttrValueToCORSMode(const nsAttrValue* aValue)
3045 if (!aValue) {
3046 return CORS_NONE;
3049 return CORSMode(aValue->GetEnumValue());
3052 static const char*
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.
3068 return nullptr;
3071 if (!nsContentUtils::IsRequestFullScreenAllowed()) {
3072 return "FullScreenDeniedNotInputDriven";
3075 if (nsContentUtils::IsSitePermDeny(aDoc->NodePrincipal(), "fullscreen")) {
3076 return "FullScreenDeniedBlocked";
3079 return nullptr;
3082 void
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());
3095 if (error) {
3096 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
3097 NS_LITERAL_CSTRING("DOM"), OwnerDoc(),
3098 nsContentUtils::eDOM_PROPERTIES,
3099 error);
3100 nsRefPtr<AsyncEventDispatcher> asyncDispatcher =
3101 new AsyncEventDispatcher(OwnerDoc(),
3102 NS_LITERAL_STRING("mozfullscreenerror"),
3103 true,
3104 false);
3105 asyncDispatcher->PostDOMEvent();
3106 return;
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);
3118 return;
3121 if (fsOptions.mVrDisplay) {
3122 opts.mVRHMDDevice = fsOptions.mVrDisplay->GetHMD();
3126 OwnerDoc()->AsyncRequestFullScreen(this, opts);
3129 void
3130 Element::MozRequestPointerLock()
3132 OwnerDoc()->RequestPointerLock(this);
3135 void
3136 Element::GetAnimationPlayers(nsTArray<nsRefPtr<AnimationPlayer> >& aPlayers)
3138 nsIDocument* doc = GetComposedDoc();
3139 if (doc) {
3140 doc->FlushPendingNotifications(Flush_Style);
3143 nsIAtom* properties[] = { nsGkAtoms::transitionsProperty,
3144 nsGkAtoms::animationsProperty };
3145 for (size_t propIdx = 0; propIdx < MOZ_ARRAY_LENGTH(properties);
3146 propIdx++) {
3147 AnimationPlayerCollection* collection =
3148 static_cast<AnimationPlayerCollection*>(
3149 GetProperty(properties[propIdx]));
3150 if (!collection) {
3151 continue;
3153 for (size_t playerIdx = 0;
3154 playerIdx < collection->mPlayers.Length();
3155 playerIdx++) {
3156 AnimationPlayer* player = collection->mPlayers[playerIdx];
3157 if (player->HasCurrentSource() || player->HasInEffectSource()) {
3158 aPlayers.AppendElement(player);
3164 NS_IMETHODIMP
3165 Element::GetInnerHTML(nsAString& aInnerHTML)
3167 GetMarkup(false, aInnerHTML);
3168 return NS_OK;
3171 void
3172 Element::SetInnerHTML(const nsAString& aInnerHTML, ErrorResult& aError)
3174 SetInnerHTMLInternal(aInnerHTML, aError);
3177 void
3178 Element::GetOuterHTML(nsAString& aOuterHTML)
3180 GetMarkup(true, aOuterHTML);
3183 void
3184 Element::SetOuterHTML(const nsAString& aOuterHTML, ErrorResult& aError)
3186 nsCOMPtr<nsINode> parent = GetParentNode();
3187 if (!parent) {
3188 return;
3191 if (parent->NodeType() == nsIDOMNode::DOCUMENT_NODE) {
3192 aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
3193 return;
3196 if (OwnerDoc()->IsHTML()) {
3197 nsIAtom* localName;
3198 int32_t namespaceID;
3199 if (parent->IsElement()) {
3200 localName = static_cast<nsIContent*>(parent.get())->Tag();
3201 namespaceID = static_cast<nsIContent*>(parent.get())->GetNameSpaceID();
3202 } else {
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,
3211 fragment,
3212 localName,
3213 namespaceID,
3214 OwnerDoc()->GetCompatibilityMode() ==
3215 eCompatibility_NavQuirks,
3216 true);
3217 parent->ReplaceChild(*fragment, *this, aError);
3218 return;
3221 nsCOMPtr<nsINode> context;
3222 if (parent->IsElement()) {
3223 context = parent;
3224 } else {
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,
3229 nullptr,
3230 kNameSpaceID_XHTML,
3231 nsIDOMNode::ELEMENT_NODE);
3232 context = NS_NewHTMLBodyElement(info.forget(), FROM_PARSER_FRAGMENT);
3235 nsCOMPtr<nsIDOMDocumentFragment> df;
3236 aError = nsContentUtils::CreateContextualFragment(context,
3237 aOuterHTML,
3238 true,
3239 getter_AddRefs(df));
3240 if (aError.Failed()) {
3241 return;
3243 nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
3244 parent->ReplaceChild(*fragment, *this, aError);
3247 enum nsAdjacentPosition {
3248 eBeforeBegin,
3249 eAfterBegin,
3250 eBeforeEnd,
3251 eAfterEnd
3254 void
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;
3267 } else {
3268 aError.Throw(NS_ERROR_DOM_SYNTAX_ERR);
3269 return;
3272 nsCOMPtr<nsIContent> destination;
3273 if (position == eBeforeBegin || position == eAfterEnd) {
3274 destination = GetParent();
3275 if (!destination) {
3276 aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
3277 return;
3279 } else {
3280 destination = this;
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,
3307 destination,
3308 contextLocal,
3309 contextNs,
3310 doc->GetCompatibilityMode() ==
3311 eCompatibility_NavQuirks,
3312 true);
3313 // HTML5 parser has notified, but not fired mutation events.
3314 nsContentUtils::FireMutationEventsForDirectParsing(doc, destination,
3315 oldChildCount);
3316 return;
3319 // couldn't parse directly
3320 nsCOMPtr<nsIDOMDocumentFragment> df;
3321 aError = nsContentUtils::CreateContextualFragment(destination,
3322 aText,
3323 true,
3324 getter_AddRefs(df));
3325 if (aError.Failed()) {
3326 return;
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);
3337 switch (position) {
3338 case eBeforeBegin:
3339 destination->InsertBefore(*fragment, this, aError);
3340 break;
3341 case eAfterBegin:
3342 static_cast<nsINode*>(this)->InsertBefore(*fragment, GetFirstChild(),
3343 aError);
3344 break;
3345 case eBeforeEnd:
3346 static_cast<nsINode*>(this)->AppendChild(*fragment, aError);
3347 break;
3348 case eAfterEnd:
3349 destination->InsertBefore(*fragment, GetNextSibling(), aError);
3350 break;
3354 nsIEditor*
3355 Element::GetEditorInternal()
3357 nsCOMPtr<nsITextControlElement> textCtrl = do_QueryInterface(this);
3358 return textCtrl ? textCtrl->GetTextEditor() : nullptr;
3361 nsresult
3362 Element::SetBoolAttr(nsIAtom* aAttr, bool aValue)
3364 if (aValue) {
3365 return SetAttr(kNameSpaceID_None, aAttr, EmptyString(), true);
3368 return UnsetAttr(kNameSpaceID_None, aAttr, true);
3371 void
3372 Element::GetEnumAttr(nsIAtom* aAttr,
3373 const char* aDefault,
3374 nsAString& aResult) const
3376 GetEnumAttr(aAttr, aDefault, aDefault, aResult);
3379 void
3380 Element::GetEnumAttr(nsIAtom* aAttr,
3381 const char* aDefaultMissing,
3382 const char* aDefaultInvalid,
3383 nsAString& aResult) const
3385 const nsAttrValue* attrVal = mAttrsAndChildren.GetAttr(aAttr);
3387 aResult.Truncate();
3389 if (!attrVal) {
3390 if (aDefaultMissing) {
3391 AppendASCIItoUTF16(nsDependentCString(aDefaultMissing), aResult);
3392 } else {
3393 SetDOMStringToNull(aResult);
3395 } else {
3396 if (attrVal->Type() == nsAttrValue::eEnum) {
3397 attrVal->GetEnumString(aResult, true);
3398 } else if (aDefaultInvalid) {
3399 AppendASCIItoUTF16(nsDependentCString(aDefaultInvalid), aResult);
3404 void
3405 Element::SetOrRemoveNullableStringAttr(nsIAtom* aName, const nsAString& aValue,
3406 ErrorResult& aError)
3408 if (DOMStringIsNull(aValue)) {
3409 UnsetAttr(aName, aError);
3410 } else {
3411 SetAttr(aName, aValue, aError);
3415 Directionality
3416 Element::GetComputedDirectionality() const
3418 nsIFrame* frame = GetPrimaryFrame();
3419 if (frame) {
3420 return frame->StyleVisibility()->mDirection == NS_STYLE_DIRECTION_LTR
3421 ? eDir_LTR : eDir_RTL;
3424 return GetDirectionality();
3427 float
3428 Element::FontSizeInflation()
3430 nsIFrame* frame = GetPrimaryFrame();
3431 if (!frame) {
3432 return -1.0;
3435 if (nsLayoutUtils::FontSizeInflationEnabled(frame->PresContext())) {
3436 return nsLayoutUtils::FontSizeInflationFor(frame);
3439 return 1.0;