/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Peter Kelly (pmk@post.com)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#pragma once

#include "Document.h"
#include "ElementAttributeData.h"
#include "FocusOptions.h"
#include "ParserContentPolicy.h"
#include "GetAnimationsOptions.h"
#include "HTMLNames.h"
#include "KeyframeAnimationOptions.h"
#include "RenderStyle.h"
#include "ScrollToOptions.h"
#include "ScrollTypes.h"
#include "ShadowRootInit.h"
#include "StyleChange.h"
#include "WebAnimationTypes.h"

namespace WebCore {

class Attr;
class Attribute;
class ClientRect;
class ClientRectList;
class DatasetDOMStringMap;
class DOMRect;
class DOMRectList;
class Dictionary;
class DOMTokenList;
class ElementAnimationRareData;
class ElementRareData;
class Frame;
class HTMLDocument;
class IntSize;
class KeyframeEffectStack;
class KeyboardEvent;
class Locale;
class PlatformKeyboardEvent;
class PlatformMouseEvent;
class PseudoElement;
class RenderTreePosition;
struct ElementStyle;

enum SpellcheckAttributeState {
    SpellcheckAttributeTrue,
    SpellcheckAttributeFalse,
    SpellcheckAttributeDefault
};

#if ENABLE(INTERSECTION_OBSERVER)
struct IntersectionObserverData;
#endif

#if ENABLE(RESIZE_OBSERVER)
struct ResizeObserverData;
#endif

enum class SelectionRevealMode {
    Reveal,
    RevealUpToMainFrame, // Scroll overflow and iframes, but not the main frame.
    DoNotReveal
};

namespace Style {
struct ResolutionContext;
}

class Element : public ContainerNode {
public:
    static PassRefPtr<Element> create(const QualifiedName&, Document*);
    virtual ~Element();

    bool hasAttribute(const QualifiedName&) const;
    const AtomicString& getAttribute(const QualifiedName&) const;
    template<typename... QualifiedNames>
    const AtomicString& getAttribute(const QualifiedName&, const QualifiedNames&...) const;
    void setAttribute(const QualifiedName&, const AtomicString& value);
    void setAttributeWithoutSynchronization(const QualifiedName&, const AtomicString& value);
	void setSynchronizedLazyAttribute(const QualifiedName&, const AtomicString& value);
	bool removeAttribute(const QualifiedName&);
    Vector<String> getAttributeNames() const;

    // Typed getters and setters for language bindings.
    int getIntegralAttribute(const QualifiedName& attributeName) const;
    void setIntegralAttribute(const QualifiedName& attributeName, int value);
    unsigned getUnsignedIntegralAttribute(const QualifiedName& attributeName) const;
    void setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value);

    // Call this to get the value of an attribute that is known not to be the style
    // attribute or one of the SVG animatable attributes.
    bool hasAttributeWithoutSynchronization(const QualifiedName&) const;
    const AtomicString& attributeWithoutSynchronization(const QualifiedName&) const;
#ifndef NDEBUG
    bool fastAttributeLookupAllowed(const QualifiedName&) const;
#endif

#if defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS
    bool hasNamedNodeMap() const;
#endif
    bool hasAttributes() const;
    // This variant will not update the potentially invalid attributes. To be used when not interested
    // in style attribute or one of the SVG animation attributes.
    bool hasAttributesWithoutUpdate() const;

    bool hasAttribute(const char* name) const;
    bool hasAttribute(const AtomicString& name) const;
    bool hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;

    const AtomicString& getAttribute(const char* name) const;
    const AtomicString& getAttribute(const AtomicString& name) const;
    const AtomicString& getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;

    void setAttribute(const AtomicString& name, const AtomicString& value, ExceptionCode&);
    static bool parseAttributeName(QualifiedName&, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode&);
    void setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode&);

    const AtomicString& getIdAttribute() const;
    void setIdAttribute(const AtomicString&);

    const AtomicString& getNameAttribute() const;

    // Call this to get the value of the id attribute for style resolution purposes.
    // The value will already be lowercased if the document is in compatibility mode,
    // so this function is not suitable for non-style uses.
    const AtomicString& idForStyleResolution() const;

    // Internal methods that assume the existence of attribute storage, one should use hasAttributes()
    // before calling them.
    AttributeIteratorAccessor attributesIterator() const { return elementData()->attributesIterator(); }
	unsigned attributeCount() const;
    const Attribute& attributeAt(unsigned index) const;
    const Attribute* findAttributeByName(const QualifiedName&) const;
    unsigned findAttributeIndexByName(const QualifiedName& name) const { return elementData()->findAttributeIndexByName(name); }
    unsigned findAttributeIndexByName(const AtomicString& name, bool shouldIgnoreAttributeCase) const { return elementData()->findAttributeIndexByName(name, shouldIgnoreAttributeCase); }

    void scrollIntoView(bool alignToTop = true);
    void scrollIntoViewIfNeeded(bool centerIfNeeded = true);

    void scrollBy(const ScrollToOptions&);
    void scrollBy(double x, double y);
    virtual void scrollTo(const ScrollToOptions&);
    void scrollTo(double x, double y);

    void scrollByLines(int lines);
    void scrollByPages(int pages);

    WEBCORE_EXPORT int offsetLeftForBindings();
    WEBCORE_EXPORT int offsetLeft();
    WEBCORE_EXPORT int offsetTopForBindings();
    WEBCORE_EXPORT int offsetTop();
    WEBCORE_EXPORT int offsetWidth();
    WEBCORE_EXPORT int offsetHeight();

    // FIXME: Replace uses of offsetParent in the platform with calls
    // to the render layer and merge bindingsOffsetParent and offsetParent.
    Element* offsetParentForBindings();

    const Element* rootElement() const;

    Element* offsetParent();
    int clientLeft();
    int clientTop();
    int clientWidth();
    int clientHeight();

    virtual int scrollLeft();
    virtual int scrollTop();
    virtual void setScrollLeft(int);
    virtual void setScrollTop(int);
    virtual int scrollWidth();
    virtual int scrollHeight();

    IntRect boundsInRootViewSpace();

    FloatRect boundingClientRect();

    Optional<std::pair<RenderElement*, FloatRect>> boundingAbsoluteRectWithoutLayout();

    PassRefPtr<DOMRectList> getClientRects();
    PassRefPtr<DOMRect> getBoundingClientRect();

    // Returns the absolute bounding box translated into client coordinates.
    IntRect clientRect() const;
    // Returns the absolute bounding box translated into screen coordinates.
    IntRect screenRect() const;

    bool removeAttribute(const AtomicString& name);
    bool removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName);

    PassRefPtr<Attr> detachAttribute(unsigned index);

    PassRefPtr<Attr> getAttributeNode(const AtomicString& name);
    PassRefPtr<Attr> getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName);
    PassRefPtr<Attr> setAttributeNode(Attr&, ExceptionCode&);
    PassRefPtr<Attr> setAttributeNodeNS(Attr&, ExceptionCode&);
    PassRefPtr<Attr> removeAttributeNode(Attr&, ExceptionCode&);

    PassRefPtr<Attr> attrIfExists(const QualifiedName&);
	Ref<Attr> ensureAttr(const QualifiedName&);

    const Vector<RefPtr<Attr>>& attrNodeList();

#if ENABLE(BML)
    virtual CSSStyleDeclaration* normalStyle() { return 0; }
    virtual CSSStyleDeclaration* focusStyle() { return 0; }
    virtual CSSStyleDeclaration* activeStyle() { return 0; }
#endif
    
    const QualifiedName& tagQName() const { return m_tagName; }
    ALWAYS_INLINE String tagName() const { return nodeName(); }
    ALWAYS_INLINE bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }
    bool hasTagName(const HTMLQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
	bool hasTagName(const MathMLQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
	bool hasTagName(const SVGQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }

    // A fast function for checking the local name against another atomic string.
    ALWAYS_INLINE bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }

    virtual const AtomicString& localName() const FINAL { return m_tagName.localName(); }
    virtual const AtomicString& prefix() const FINAL { return m_tagName.prefix(); }
    virtual const AtomicString& namespaceURI() const FINAL { return m_tagName.namespaceURI(); }

    virtual void setPrefix(const AtomicString&, ExceptionCode&) FINAL;

    virtual KURL baseURI() const FINAL;

    virtual String nodeName() const OVERRIDE;

    Ref<Element> cloneElementWithChildren(Document&);
    Ref<Element> cloneElementWithoutChildren(Document&);

    void normalizeAttributes();
    String nodeNamePreservingCase() const;

    void setBooleanAttribute(const QualifiedName& name, bool);

    // For exposing to DOM only.
    NamedNodeMap* attributes() const;

    enum AttributeModificationReason {
        ModifiedDirectly,
        ModifiedByCloning
    };

    // This function is called whenever an attribute is added, changed or removed.
    // Do not call this function directly. notifyAttributeChanged() should be used instead
    // in order to update state dependent on attribute changes.
    virtual void attributeChanged(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason = ModifiedDirectly);

    // Only called by the parser immediately after element construction.
    void parserSetAttributes(const Vector<Attribute>&);

    void stripJavaScriptAttributes(Vector<Attribute>&);

    ALWAYS_INLINE const ElementData* elementData() const { return m_elementData.get(); }
    UniqueElementData* ensureUniqueElementData();

    void synchronizeAllAttributes() const;

    // Clones attributes only.
    void cloneAttributesFromElement(const Element&);

    // Clones all attribute-derived data, including subclass specifics (through copyNonAttributeProperties.)
    void cloneDataFromElement(const Element&);

    virtual void didMoveToNewDocument(Document& oldDocument, Document& newDocument);

    bool hasEquivalentAttributes(const Element& other) const;

    virtual void copyNonAttributePropertiesFromElement(const Element&) { }

    virtual RenderPtr<RenderElement> createElementRenderer(PassOwnPtr<RenderStyle>, const RenderTreePosition&);
    virtual bool rendererIsNeeded(const RenderStyle&);
    virtual bool rendererIsEverNeeded() { return true; }

    const RenderStyle* renderStyle() const;

    ShadowRoot* shadowRoot() const;
    PassRefPtr<ShadowRoot> createShadowRoot(ExceptionCode&);

    ShadowRoot* bindingShadowRoot() const;
    RefPtr<ShadowRoot> attachShadow(const ShadowRootInit&, ExceptionCode&);

    RefPtr<ShadowRoot> userAgentShadowRoot() const;
    ShadowRoot& ensureUserAgentShadowRoot();

    virtual const AtomicString& shadowPseudoId() const;

    bool inActiveChain() const { return isUserActionElement() && isUserActionElementInActiveChain(); }
    bool active() const { return isUserActionElement() && isUserActionElementActive(); }
    bool hovered() const { return isUserActionElement() && isUserActionElementHovered(); }
    bool focused() const { return isUserActionElement() && isUserActionElementFocused(); }
    bool isBeingDragged() const { return isUserActionElement() && isUserActionElementDragged(); }
    bool hasFocusVisible() const { return isUserActionElement() && isUserActionElementHasFocusVisible(); }
	bool hasFocusWithin() const { return isUserActionElement() && isUserActionElementHasFocusWithin(); };

    virtual void setActive(bool = true, bool pause = false);
    virtual void setHovered(bool = true);
	virtual void setFocus(bool, FocusVisibility = FocusVisibility::Invisible);
    void setBeingDragged(bool);
    void setHasFocusVisible(bool);
    void setHasFocusWithin(bool);
    void setHasTentativeFocus(bool);

    Optional<int> tabIndexSetExplicitly() const;
    bool shouldBeIgnoredInSequentialFocusNavigation() const { return defaultTabIndex() < 0 && !supportsFocus(); }
    bool hasFocusableStyle() const;
	virtual bool supportsFocus() const;
    virtual bool isFocusable() const;
    virtual bool isKeyboardFocusable(KeyboardEvent*) const;
    virtual bool isMouseFocusable() const;

    virtual int tabIndexForBindings() const;
    WEBCORE_EXPORT void setTabIndexForBindings(int);

    // Used by the HTMLElement and SVGElement IDLs.
    WEBCORE_EXPORT const AtomString& nonce() const;
    WEBCORE_EXPORT void setNonce(const AtomString&);
    void hideNonce();

    Element* insertAdjacentElement(const String& where, Element& newChild, ExceptionCode&);
    void insertAdjacentHTML(const String& where, const String& html, ExceptionCode&);
    void insertAdjacentText(const String& where, const String& text, ExceptionCode&);

    virtual RenderStyle* computedStyle(PseudoId = PseudoId::None) OVERRIDE;

    bool needsStyleInvalidation() const;

    // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
    bool styleAffectedByEmpty() const { return hasStyleFlag(NodeStyleFlag::StyleAffectedByEmpty); }
	bool descendantsAffectedByPreviousSibling() const { return hasStyleFlag(NodeStyleFlag::DescendantsAffectedByPreviousSibling); }
	bool childrenAffectedByFirstChildRules() const { return hasStyleFlag(NodeStyleFlag::ChildrenAffectedByFirstChildRules); }
	bool childrenAffectedByLastChildRules() const { return hasStyleFlag(NodeStyleFlag::ChildrenAffectedByLastChildRules); }
	bool childrenAffectedByForwardPositionalRules() const { return hasStyleFlag(NodeStyleFlag::ChildrenAffectedByForwardPositionalRules); }
	bool descendantsAffectedByForwardPositionalRules() const { return hasStyleFlag(NodeStyleFlag::DescendantsAffectedByForwardPositionalRules); }
	bool childrenAffectedByBackwardPositionalRules() const { return hasStyleFlag(NodeStyleFlag::ChildrenAffectedByBackwardPositionalRules); }
	bool descendantsAffectedByBackwardPositionalRules() const { return hasStyleFlag(NodeStyleFlag::DescendantsAffectedByBackwardPositionalRules); }
	bool affectsNextSiblingElementStyle() const { return hasStyleFlag(NodeStyleFlag::AffectsNextSiblingElementStyle); }
	bool styleIsAffectedByPreviousSibling() const { return hasStyleFlag(NodeStyleFlag::StyleIsAffectedByPreviousSibling); }
	unsigned childIndex() const { return hasRareData() ? rareDataChildIndex() : 0; }

    void setStyleAffectedByEmpty() { setStyleFlag(NodeStyleFlag::StyleAffectedByEmpty); }
    void setDescendantsAffectedByPreviousSibling() { setStyleFlag(NodeStyleFlag::DescendantsAffectedByPreviousSibling); }
    void setChildrenAffectedByFirstChildRules() { setStyleFlag(NodeStyleFlag::ChildrenAffectedByFirstChildRules); }
    void setChildrenAffectedByLastChildRules() { setStyleFlag(NodeStyleFlag::ChildrenAffectedByLastChildRules); }
    void setChildrenAffectedByForwardPositionalRules() { setStyleFlag(NodeStyleFlag::ChildrenAffectedByForwardPositionalRules); }
    void setDescendantsAffectedByForwardPositionalRules() { setStyleFlag(NodeStyleFlag::DescendantsAffectedByForwardPositionalRules); }
    void setChildrenAffectedByBackwardPositionalRules() { setStyleFlag(NodeStyleFlag::ChildrenAffectedByBackwardPositionalRules); }
    void setDescendantsAffectedByBackwardPositionalRules() { setStyleFlag(NodeStyleFlag::DescendantsAffectedByBackwardPositionalRules); }
    void setAffectsNextSiblingElementStyle() { setStyleFlag(NodeStyleFlag::AffectsNextSiblingElementStyle); }
    void setStyleIsAffectedByPreviousSibling() { setStyleFlag(NodeStyleFlag::StyleIsAffectedByPreviousSibling); }
    void setChildIndex(unsigned);

    bool hasFlagsSetDuringStylingOfChildren() const;

    AtomicString computeInheritedLanguage() const;
    Locale& locale() const;

    virtual bool accessKeyAction(bool /*sendToAnyEvent*/) { return false; }

    virtual bool isURLAttribute(const Attribute&) const { return false; }

    KURL getURLAttribute(const QualifiedName&) const;
    KURL getNonEmptyURLAttribute(const QualifiedName&) const;

    virtual const AtomicString& imageSourceURL() const;
    virtual String target() const { return String(); }

    virtual void focus(const FocusOptions& = FocusOptions());
    virtual void focusForBindings();
    virtual RefPtr<Element> focusAppearanceUpdateTarget();
    virtual void updateFocusAppearance(SelectionRestorationMode, SelectionRevealMode = SelectionRevealMode::Reveal);
	virtual void blur(bool byUser = false);
    virtual void runFocusingStepsForAutofocus();

    String innerHTML() const;
    String outerHTML() const;
    void setInnerHTML(const String&, ExceptionCode&);
    void setOuterHTML(const String&, ExceptionCode&);
    String innerText();
    String outerText();
 
    virtual String title() const;

    const AtomicString& pseudo() const;
    void setPseudo(const AtomicString&);

    void updateName(const AtomicString& oldName, const AtomicString& newName);
	void updateNameForTreeScope(TreeScope*, const AtomicString& oldName, const AtomicString& newName);
	void updateNameForDocument(HTMLDocument*, const AtomicString& oldName, const AtomicString& newName);

    enum class NotifyObservers { No, Yes };
    void updateId(const AtomicString& oldId, const AtomicString& newId, NotifyObservers = NotifyObservers::Yes);
    void updateIdForTreeScope(TreeScope*, const AtomicString& oldId, const AtomicString& newId, NotifyObservers = NotifyObservers::Yes);

	enum HTMLDocumentNamedItemMapsUpdatingCondition { AlwaysUpdateHTMLDocumentNamedItemMaps, UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute };
	void updateIdForDocument(HTMLDocument*, const AtomicString& oldId, const AtomicString& newId, HTMLDocumentNamedItemMapsUpdatingCondition);

    LayoutSize minimumSizeForResizing() const;
    void setMinimumSizeForResizing(const LayoutSize&);

    // Use Document::registerForDocumentActivationCallbacks() to subscribe to these
    virtual void documentWillSuspendForPageCache() { }
    virtual void documentDidResumeFromPageCache() { }

    // Use Document::registerForDocumentActivationCallbacks() to subscribe to these
    virtual void documentWillBecomeInactive() { }

    virtual void didBecomeFullscreenElement() { }
    virtual void willStopBeingFullscreenElement() { }

#if ENABLE(PAGE_VISIBILITY_API)
    // Use Document::registerForVisibilityStateChangedCallbacks() to subscribe to this.
    virtual void visibilityStateChanged() { }
#endif

    ALWAYS_INLINE bool isFinishedParsingChildren() const { return isParsingChildrenFinished(); }
    virtual void finishParsingChildren() OVERRIDE;
    virtual void beginParsingChildren() FINAL;

    PseudoElement& ensurePseudoElement(PseudoId);
    PseudoElement* beforePseudoElement() const;
    PseudoElement* afterPseudoElement() const;
    bool childNeedsShadowWalker() const;
    void didShadowTreeAwareChildrenChange();

    virtual bool matchesValidPseudoClass() const;
    virtual bool matchesInvalidPseudoClass() const;
    virtual bool matchesReadWritePseudoClass() const;
    virtual bool matchesIndeterminatePseudoClass() const;
    virtual bool matchesDefaultPseudoClass() const;
    bool matches(const String& selectors, ExceptionCode&);
    Element* closest(const String& selectors, ExceptionCode&);
    bool webkitMatchesSelector(const String& selectors, ExceptionCode& ec) { return matches(selectors, ec); }
    virtual bool shouldAppearIndeterminate() const;

    DOMTokenList* classList();

    SpaceSplitString partNames() const;
    DOMTokenList& part();

    DatasetDOMStringMap* dataset();

#if ENABLE(VIDEO)
    virtual bool isMediaElement() const { return false; }
#endif

#if ENABLE(INPUT_SPEECH)
    virtual bool isInputFieldSpeechButtonElement() const { return false; }
#endif

    virtual bool isFormControlElement() const { return false; }
    virtual bool isSpinButtonElement() const { return false; }
    virtual bool isTextFormControlElement() const { return false; }
    virtual bool isTextField() const { return false; }
    virtual bool isOptionalFormControl() const { return false; }
    virtual bool isRequiredFormControl() const { return false; }
    virtual bool isInRange() const { return false; }
    virtual bool isOutOfRange() const { return false; }
    virtual bool isUploadButton() const { return false; }
    virtual bool isSliderContainerElement() const { return false; }
    virtual bool isSliderThumbElement() const { return false; }

    virtual bool canContainRangeEndPoint() const override { return true; }

    // Used for disabled form elements; if true, prevents mouse events from being dispatched
    // to event listeners, and prevents DOMActivate events from being sent at all.
    virtual bool isDisabledFormControl() const { return false; }

    virtual bool childShouldCreateRenderer(const Node*) const;

    KeyframeEffectStack* keyframeEffectStack(PseudoId) const;
    KeyframeEffectStack& ensureKeyframeEffectStack(PseudoId);
    bool hasKeyframeEffects(PseudoId) const;

    const AnimationCollection* animations(PseudoId) const;
    bool hasCompletedTransitionsForProperty(PseudoId, CSSPropertyID) const;
    bool hasRunningTransitionsForProperty(PseudoId, CSSPropertyID) const;
    bool hasRunningTransitions(PseudoId) const;
    AnimationCollection& ensureAnimations(PseudoId);

    PropertyToTransitionMap& ensureCompletedTransitionsByProperty(PseudoId);
    PropertyToTransitionMap& ensureRunningTransitionsByProperty(PseudoId);
    CSSAnimationCollection& animationsCreatedByMarkup(PseudoId);
    void setAnimationsCreatedByMarkup(PseudoId, CSSAnimationCollection&&);

    const RenderStyle* lastStyleChangeEventStyle(PseudoId) const;
    void setLastStyleChangeEventStyle(PseudoId, PassOwnPtr<const RenderStyle>);

    void cssAnimationsDidUpdate(PseudoId);
    void keyframesRuleDidChange(PseudoId);
    bool hasPendingKeyframesUpdate(PseudoId) const;

    bool isInTopLayer() const { return getFlag(NodeFlags::IsInTopLayer); }
    void addToTopLayer();
    void removeFromTopLayer();

#if ENABLE(FULLSCREEN_API)
    enum {
        ALLOW_KEYBOARD_INPUT = 1 << 0,
        LEGACY_MOZILLA_REQUEST = 1 << 1,
    };
    
    void webkitRequestFullScreen(unsigned short flags);
    bool containsFullScreenElement() const { return getFlag(ContainsFullScreenElementFlag); }
    void setContainsFullScreenElement(bool);
    void setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool);

    // W3C API
    void webkitRequestFullscreen();
#endif

#if ENABLE(POINTER_LOCK)
    void requestPointerLock();
#endif

    virtual bool isSpellCheckingEnabled() const;

    bool hasID() const;
    bool hasClass() const;
    bool hasName() const;
    const SpaceSplitString& classNames() const;

    IntPoint savedLayerScrollPosition() const;
    void setSavedLayerScrollPosition(const IntPoint&);

    bool dispatchMouseEvent(const PlatformMouseEvent&, const AtomicString& eventType, int clickCount = 0, Element* relatedTarget = nullptr);
    bool dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents, SimulatedClickVisualOptions = ShowPressedLook);

    // FIXME: Consider changing signature to accept Element* because all callers perform copyRef().
    void dispatchFocusInEventIfNeeded(PassRefPtr<Element> oldFocusedElement);
	void dispatchFocusOutEventIfNeeded(PassRefPtr<Element> newFocusedElement);
	virtual void dispatchFocusEvent(PassRefPtr<Element> oldFocusedElement, const FocusOptions&);
	virtual void dispatchBlurEvent(PassRefPtr<Element> newFocusedElement);

    virtual bool willRecalcStyle(Style::Change);
    virtual void didRecalcStyle(Style::Change);
    virtual void willAttachRenderers();
    virtual void didAttachRenderers();
    virtual void willDetachRenderers();
    virtual void didDetachRenderers();
    virtual void willResetComputedStyle();
    virtual Optional<ElementStyle> resolveCustomStyle(const Style::ResolutionContext&, const RenderStyle* shadowHostStyle);

    const RenderStyle* existingComputedStyle() const;
    const RenderStyle* renderOrDisplayContentsStyle(PseudoId = PseudoId::None) const;

    void clearBeforePseudoElement();
    void clearAfterPseudoElement();
    void resetComputedStyle();
    void resetStyleRelations();
    void resetChildStyleRelations();
    void resetAllDescendantStyleRelations();
    void clearHoverAndActiveStatusBeforeDetachingRenderer();

    KURL absoluteLinkURL() const;

    StyleResolver& styleResolver();
    ElementStyle resolveStyle(const Style::ResolutionContext&);

    // Invalidates the style of a single element. Style is resolved lazily.
    // Descendant elements are resolved as needed, for example if an inherited property changes.
    // This should be called whenever an element changes in a manner that can affect its style.
    void invalidateStyle();

    // As above but also call RenderElement::setStyle with StyleDifferenceRecompositeLayer flag for
    // the element even when the style doesn't change. This is mostly needed by the animation code.
    void invalidateStyleAndLayerComposition();

    // Invalidate the element and all its descendants. This is used when there is some sort of change
    // in the tree that may affect the style of any of the descendants and we don't know how to optimize
    // the case to limit the scope. This is expensive and should be avoided.
    void invalidateStyleForSubtree();

    // Invalidates renderers for the element and all its descendants causing them to be torn down
    // and rebuild during style resolution. Style is also recomputed. This is used in code dealing with
    // custom (not style based) renderers. This is expensive and should be avoided.
    // Elements newly added to the tree are also in this state.
    void invalidateStyleAndRenderersForSubtree();
    void invalidateRenderer();

    void invalidateStyleInternal();
    void invalidateStyleForSubtreeInternal();

    bool hasDisplayContents() const;
    void storeDisplayContentsStyle(PassOwnPtr<RenderStyle>);

    virtual bool isSpatialNavigationFocusable() const OVERRIDE;

    using ContainerNode::setAttributeEventListener;
    void setAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& value);

#if ENABLE(INTERSECTION_OBSERVER)
    IntersectionObserverData& ensureIntersectionObserverData();
    IntersectionObserverData* intersectionObserverDataIfExists();
#endif

#if ENABLE(RESIZE_OBSERVER)
    ResizeObserverData& ensureResizeObserverData();
    ResizeObserverData* resizeObserverData();
#endif

    PassRefPtr<WebAnimation> animate(JSC::ExecState*, JSC::JSValue, ExceptionCode&);
    PassRefPtr<WebAnimation> animate(JSC::ExecState*, JSC::JSValue, JSC::JSValue options, ExceptionCode&);
	Vector<RefPtr<WebAnimation>> getAnimations(Optional<GetAnimationsOptions>);

    virtual void updateUserAgentShadowTree() { }

    bool hasDuplicateAttribute() const { return m_hasDuplicateAttribute; };
    void setHasDuplicateAttribute(bool hasDuplicateAttribute) { m_hasDuplicateAttribute = hasDuplicateAttribute; };

    bool displayContentsChanged() const { return m_displayContentsChanged; }
    void setDisplayContentsChanged(bool changed = true) { m_displayContentsChanged = changed; }

protected:
    Element(const QualifiedName&, Document*, ConstructionType);

    virtual InsertedIntoResult insertedIntoAncestor(const InsertionType&, ContainerNode&) OVERRIDE;
    virtual void removedFromAncestor(const RemovalType&, ContainerNode&) OVERRIDE;
    virtual void childrenChanged(const ChildChange&) OVERRIDE;
    virtual void parserDidSetAttributes();
    virtual void removeAllEventListeners() FINAL;

    void setTabIndexExplicitly(Optional<int>);

    void classAttributeChanged(const AtomicString& newClassString);
    void partAttributeChanged(const AtomicString& newValue);

    void addShadowRoot(Ref<ShadowRoot>&&);

    static void mergeWithNextTextNode(PassRefPtr<Text> node, ExceptionCode&);

    ElementRareData* elementRareData() const;
    ElementRareData& ensureElementRareData();

    ElementAnimationRareData* animationRareData(PseudoId) const;
    ElementAnimationRareData& ensureAnimationRareData(PseudoId);

private:
    Frame* documentFrameWithNonNullView() const;

    bool isTextNode() const;

    bool isUserActionElementInActiveChain() const;
    bool isUserActionElementActive() const;
    bool isUserActionElementFocused() const;
    bool isUserActionElementHovered() const;
    bool isUserActionElementDragged() const;
    bool isUserActionElementHasFocusVisible() const;
    bool isUserActionElementHasFocusWithin() const;

    bool isNonceable() const;

    virtual void didAddUserAgentShadowRoot(ShadowRoot*) { }
    virtual bool alwaysCreateUserAgentShadowRoot() const { return false; }

    // FIXME: Remove the need for Attr to call willModifyAttribute/didModifyAttribute.
    friend class Attr;

    enum SynchronizationOfLazyAttribute { NotInSynchronizationOfLazyAttribute = 0, InSynchronizationOfLazyAttribute };

    void didAddAttribute(const QualifiedName&, const AtomicString&);
    void willModifyAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
    void didModifyAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
	void didRemoveAttribute(const QualifiedName&, const AtomicString& oldValue);

    void synchronizeAttribute(const QualifiedName&) const;
    void synchronizeAttribute(const AtomicString& localName) const;

    Node* insertAdjacent(const String& where, Ref<Node>&& newChild, ExceptionCode&);

    void scrollByUnits(int units, ScrollGranularity);

    virtual NodeType nodeType() const FINAL;
    virtual bool childTypeAllowed(NodeType) const FINAL;

    void notifyAttributeChanged(const QualifiedName&, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason = ModifiedDirectly);
    void setAttributeInternal(unsigned index, const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
    void addAttributeInternal(const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
    void removeAttributeInternal(unsigned index, SynchronizationOfLazyAttribute);

    void setSavedLayerScrollPositionSlow(const IntPoint&);
    void clearBeforePseudoElementSlow();
    void clearAfterPseudoElementSlow();

#ifndef NDEBUG
    virtual void formatForDebugger(char* buffer, unsigned length) const;
#endif

#if ENABLE(INTERSECTION_OBSERVER)
    void disconnectFromIntersectionObservers();
#endif

#if ENABLE(RESIZE_OBSERVER)
    void disconnectFromResizeObservers();
#endif

    // The cloneNode function is private so that non-virtual cloneElementWith/WithoutChildren are used instead.
    virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) OVERRIDE;
    virtual Ref<Element> cloneElementWithoutAttributesAndChildren(Document&);

    virtual bool canHaveUserAgentShadowRoot() const;
    void removeShadowRoot();

    enum class ResolveComputedStyleMode { Normal, RenderedOnly };
    const RenderStyle* resolveComputedStyle(ResolveComputedStyleMode = ResolveComputedStyleMode::Normal);
    const RenderStyle& resolvePseudoElementStyle(PseudoId);

    unsigned rareDataChildIndex() const;

    SpellcheckAttributeState spellcheckAttributeState() const;

    void createUniqueElementData();

    virtual int defaultTabIndex() const;

    void detachAllAttrNodesFromElement();
    void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);

    static void doResetComputedStyle(Element&);

    void attachAttributeNodeIfNeeded(Attr&);

    // Anyone thinking of using this should call document instead of ownerDocument.
    void ownerDocument() const WTF_DELETED_FUNCTION;

    bool isJavaScriptAttribute(const Attribute&);
    bool isJavaScriptURLAttribute(const Attribute&);

    QualifiedName m_tagName;
    RefPtr<ElementData> m_elementData;

    // FIXME: these flags should move somewhere else and then we should have a static assert on
    // Element size and ideally stick to that size.
    bool m_hasDuplicateAttribute { false };
    bool m_displayContentsChanged { false };
};

inline Element::Element(const QualifiedName& tagName, Document* document, ConstructionType type)
: ContainerNode(document, type)
, m_tagName(tagName)
{
}

inline bool isElement(const EventTarget& target) { return target.isNode() && static_cast<const Node&>(target).isElementNode(); }
inline bool isElement(const Node& node) { return node.isElementNode(); }
inline bool isElement(const Node* node) { return node && node->isElementNode(); }

ALWAYS_INLINE Element& toElement(EventTarget& target)
{
    ASSERT(isElement(target));
    return static_cast<Element&>(target);
}

ALWAYS_INLINE const Element& toElement(const EventTarget& target)
{
    ASSERT(isElement(target));
    return static_cast<const Element&>(target);
}

NODE_TYPE_CASTS(Element)

template <typename ExpectedType, typename ArgType>
struct ElementTypeCastTraits {
    static bool is(ArgType&);
    static bool is(ArgType* node) { return node && is(*node); }
};

// This is needed so that the compiler can deduce the second template parameter (ArgType).
template <typename ExpectedType, typename ArgType>
inline bool isElementOfType(const ArgType& node) { return ElementTypeCastTraits<ExpectedType, const ArgType>::is(node); }

template <>
struct ElementTypeCastTraits<const Element, const Node> {
    static bool is(const Node& node) { return node.isElementNode(); }
};

template <typename ExpectedType>
struct ElementTypeCastTraits<ExpectedType, ExpectedType> {
    static bool is(ExpectedType&) { return true; }
};

inline bool isDisabledFormControl(const Node* node)
{
    return node->isElementNode() && toElement(node)->isDisabledFormControl();
}

inline bool isDisabledFormControl(const Element* element)
{
    return element->isDisabledFormControl();
}

ALWAYS_INLINE bool Node::hasAttributes() const
{
    return isElementNode() && toElement(this)->hasAttributes();
}

ALWAYS_INLINE NamedNodeMap* Node::attributes() const
{
    return isElementNode() ? toElement(this)->attributes() : nullptr;
}

inline Element* Node::parentElement() const
{
    ContainerNode* parent = parentNode();
    return parent && parent->isElementNode() ? toElement(parent) : nullptr;
}

inline const Element* Element::rootElement() const
{
    if (inDocument())
        return document().documentElement();

    const Element* highest = this;
    while (highest->parentElement())
        highest = highest->parentElement();
    return highest;
}

ALWAYS_INLINE bool Element::hasAttributeWithoutSynchronization(const QualifiedName& name) const
{
    ASSERT(fastAttributeLookupAllowed(name));
    return elementData() && findAttributeByName(name);
}

ALWAYS_INLINE const AtomicString& Element::attributeWithoutSynchronization(const QualifiedName& name) const
{
    if (elementData()) {
        if (const Attribute* attribute = findAttributeByName(name))
            return attribute->value();
    }
    return nullAtom;
}

ALWAYS_INLINE bool Element::hasAttributesWithoutUpdate() const
{
    return elementData() && !elementData()->isEmpty();
}

ALWAYS_INLINE const AtomicString& Element::idForStyleResolution() const
{
    return hasID() ? elementData()->idForStyleResolution() : nullAtom;
}

ALWAYS_INLINE const AtomicString& Element::getIdAttribute() const
{
    if (hasID())
        return elementData()->findAttributeByName(document().idAttributeName())->value();
    return nullAtom;
}

ALWAYS_INLINE const AtomicString& Element::getNameAttribute() const
{
    if (hasName())
        return elementData()->findAttributeByName(HTMLNames::nameAttr)->value();
    return nullAtom;
}

ALWAYS_INLINE void Element::setIdAttribute(const AtomicString& value)
{
    setAttributeWithoutSynchronization(HTMLNames::idAttr, value);
}

ALWAYS_INLINE const SpaceSplitString& Element::classNames() const
{
    ASSERT(hasClass());
    ASSERT(elementData());
    return elementData()->classNames();
}

ALWAYS_INLINE unsigned Element::attributeCount() const
{
    ASSERT(elementData());
    return elementData()->length();
}

inline const Attribute& Element::attributeAt(unsigned index) const
{
    ASSERT(elementData());
    return elementData()->attributeAt(index);
}

inline const Attribute* Element::findAttributeByName(const QualifiedName& name) const
{
    ASSERT(elementData());
    return elementData()->findAttributeByName(name);
}

ALWAYS_INLINE bool Element::hasID() const
{
    return elementData() && elementData()->hasID();
}

ALWAYS_INLINE bool Element::hasClass() const
{
    return elementData() && elementData()->hasClass();
}

inline bool Element::hasName() const
{
    return elementData() && elementData()->hasName();
}

inline UniqueElementData* Element::ensureUniqueElementData()
{
    if (!elementData() || !elementData()->isUnique())
    	createUniqueElementData();
    return static_cast<UniqueElementData*>(m_elementData.get());
}

template<typename... QualifiedNames>
inline const AtomicString& Element::getAttribute(const QualifiedName& name, const QualifiedNames&... names) const
{
    const AtomicString& value = getAttribute(name);
    if (!value.isEmpty())
        return value;
    return getAttribute(names...);
}

// Put here to make them inline.
ALWAYS_INLINE bool Node::hasID() const
{
    return isElementNode() && toElement(this)->hasID();
}

ALWAYS_INLINE bool Node::hasClass() const
{
    return isElementNode() && toElement(this)->hasClass();
}

inline bool isInTopLayerOrBackdrop(const RenderStyle& style, const Element* element)
{
    return (element && element->isInTopLayer()) || style.styleType() == PseudoId::Backdrop;
}

inline void Element::setSavedLayerScrollPosition(const IntPoint& position)
{
    if (position.isZero() && !hasRareData())
        return;
    setSavedLayerScrollPositionSlow(position);
}

inline void Element::clearBeforePseudoElement()
{
    if (hasRareData())
        clearBeforePseudoElementSlow();
}

inline void Element::clearAfterPseudoElement()
{
    if (hasRareData())
        clearAfterPseudoElementSlow();
}

void invalidateForSiblingCombinators(Element* sibling);

} // namespace

#if 0
SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Element)
    static bool isType(const WebCore::Node& node) { return node.isElementNode(); }
    static bool isType(const WebCore::EventTarget& target) { return is<WebCore::Node>(target) && isType(downcast<WebCore::Node>(target)); }
SPECIALIZE_TYPE_TRAITS_END()
#endif
