Home | History | Annotate | Download | only in html
      1 /*
      2  * Copyright (C) 1999 Lars Knoll (knoll (at) kde.org)
      3  *           (C) 1999 Antti Koivisto (koivisto (at) kde.org)
      4  * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
      5  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
      6  * Copyright (C) 2011 Motorola Mobility. All rights reserved.
      7  *
      8  * This library is free software; you can redistribute it and/or
      9  * modify it under the terms of the GNU Library General Public
     10  * License as published by the Free Software Foundation; either
     11  * version 2 of the License, or (at your option) any later version.
     12  *
     13  * This library is distributed in the hope that it will be useful,
     14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     16  * Library General Public License for more details.
     17  *
     18  * You should have received a copy of the GNU Library General Public License
     19  * along with this library; see the file COPYING.LIB.  If not, write to
     20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     21  * Boston, MA 02110-1301, USA.
     22  *
     23  */
     24 
     25 #include "config.h"
     26 #include "core/html/HTMLElement.h"
     27 
     28 #include "CSSPropertyNames.h"
     29 #include "CSSValueKeywords.h"
     30 #include "HTMLNames.h"
     31 #include "XMLNames.h"
     32 #include "bindings/v8/ExceptionState.h"
     33 #include "bindings/v8/ScriptController.h"
     34 #include "bindings/v8/ScriptEventListener.h"
     35 #include "core/css/CSSParser.h"
     36 #include "core/css/CSSValuePool.h"
     37 #include "core/css/StylePropertySet.h"
     38 #include "core/dom/DocumentFragment.h"
     39 #include "core/dom/EventListener.h"
     40 #include "core/dom/EventNames.h"
     41 #include "core/dom/ExceptionCode.h"
     42 #include "core/dom/KeyboardEvent.h"
     43 #include "core/dom/NodeTraversal.h"
     44 #include "core/dom/Text.h"
     45 #include "core/editing/markup.h"
     46 #include "core/html/HTMLBRElement.h"
     47 #include "core/html/HTMLFormElement.h"
     48 #include "core/html/HTMLTemplateElement.h"
     49 #include "core/html/HTMLTextFormControlElement.h"
     50 #include "core/html/parser/HTMLParserIdioms.h"
     51 #include "core/loader/FrameLoader.h"
     52 #include "core/page/Frame.h"
     53 #include "core/page/Settings.h"
     54 #include "core/rendering/RenderWordBreak.h"
     55 #include "wtf/StdLibExtras.h"
     56 #include "wtf/text/CString.h"
     57 
     58 namespace WebCore {
     59 
     60 using namespace HTMLNames;
     61 using namespace WTF;
     62 
     63 using std::min;
     64 using std::max;
     65 
     66 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
     67 {
     68     return adoptRef(new HTMLElement(tagName, document));
     69 }
     70 
     71 String HTMLElement::nodeName() const
     72 {
     73     // FIXME: Would be nice to have an atomicstring lookup based off uppercase
     74     // chars that does not have to copy the string on a hit in the hash.
     75     // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
     76     if (document()->isHTMLDocument() && !tagQName().hasPrefix())
     77         return tagQName().localNameUpper();
     78     return Element::nodeName();
     79 }
     80 
     81 bool HTMLElement::ieForbidsInsertHTML() const
     82 {
     83     // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
     84     // and createContextualFragment on these tags.  We have no tests to
     85     // verify this however, so this list could be totally wrong.
     86     // This list was moved from the previous endTagRequirement() implementation.
     87     // This is also called from editing and assumed to be the list of tags
     88     // for which no end tag should be serialized. It's unclear if the list for
     89     // IE compat and the list for serialization sanity are the same.
     90     if (hasLocalName(areaTag)
     91         || hasLocalName(baseTag)
     92         || hasLocalName(basefontTag)
     93         || hasLocalName(brTag)
     94         || hasLocalName(colTag)
     95         || hasLocalName(embedTag)
     96         || hasLocalName(frameTag)
     97         || hasLocalName(hrTag)
     98         || hasLocalName(imageTag)
     99         || hasLocalName(imgTag)
    100         || hasLocalName(inputTag)
    101         || hasLocalName(isindexTag)
    102         || hasLocalName(linkTag)
    103         || hasLocalName(metaTag)
    104         || hasLocalName(paramTag)
    105         || hasLocalName(sourceTag)
    106         || hasLocalName(wbrTag))
    107         return true;
    108     return false;
    109 }
    110 
    111 static inline CSSValueID unicodeBidiAttributeForDirAuto(HTMLElement* element)
    112 {
    113     if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
    114         return CSSValueWebkitPlaintext;
    115     // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
    116     // See https://bugs.webkit.org/show_bug.cgi?id=73164.
    117     return CSSValueWebkitIsolate;
    118 }
    119 
    120 unsigned HTMLElement::parseBorderWidthAttribute(const AtomicString& value) const
    121 {
    122     unsigned borderWidth = 0;
    123     if (value.isEmpty() || !parseHTMLNonNegativeInteger(value, borderWidth))
    124         return hasLocalName(tableTag) ? 1 : borderWidth;
    125     return borderWidth;
    126 }
    127 
    128 void HTMLElement::applyBorderAttributeToStyle(const AtomicString& value, MutableStylePropertySet* style)
    129 {
    130     addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(value), CSSPrimitiveValue::CSS_PX);
    131     addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
    132 }
    133 
    134 void HTMLElement::mapLanguageAttributeToLocale(const AtomicString& value, MutableStylePropertySet* style)
    135 {
    136     if (!value.isEmpty()) {
    137         // Have to quote so the locale id is treated as a string instead of as a CSS keyword.
    138         addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, quoteCSSString(value));
    139     } else {
    140         // The empty string means the language is explicitly unknown.
    141         addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
    142     }
    143 }
    144 
    145 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
    146 {
    147     if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
    148         return true;
    149     return Element::isPresentationAttribute(name);
    150 }
    151 
    152 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
    153 {
    154     if (name == alignAttr) {
    155         if (equalIgnoringCase(value, "middle"))
    156             addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
    157         else
    158             addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, value);
    159     } else if (name == contenteditableAttr) {
    160         if (value.isEmpty() || equalIgnoringCase(value, "true")) {
    161             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
    162             addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
    163             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
    164         } else if (equalIgnoringCase(value, "plaintext-only")) {
    165             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
    166             addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
    167             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
    168         } else if (equalIgnoringCase(value, "false"))
    169             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
    170     } else if (name == hiddenAttr) {
    171         addPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
    172     } else if (name == draggableAttr) {
    173         if (equalIgnoringCase(value, "true")) {
    174             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
    175             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
    176         } else if (equalIgnoringCase(value, "false"))
    177             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
    178     } else if (name == dirAttr) {
    179         if (equalIgnoringCase(value, "auto"))
    180             addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
    181         else {
    182             addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
    183             if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
    184                 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
    185         }
    186     } else if (name.matches(XMLNames::langAttr))
    187         mapLanguageAttributeToLocale(value, style);
    188     else if (name == langAttr) {
    189         // xml:lang has a higher priority than lang.
    190         if (!fastHasAttribute(XMLNames::langAttr))
    191             mapLanguageAttributeToLocale(value, style);
    192     } else
    193         Element::collectStyleForPresentationAttribute(name, value, style);
    194 }
    195 
    196 AtomicString HTMLElement::eventNameForAttributeName(const QualifiedName& attrName) const
    197 {
    198     if (!attrName.namespaceURI().isNull())
    199         return AtomicString();
    200 
    201     typedef HashMap<AtomicString, AtomicString> StringToStringMap;
    202     DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
    203     if (!attributeNameToEventNameMap.size()) {
    204         attributeNameToEventNameMap.set(onclickAttr.localName(), eventNames().clickEvent);
    205         attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), eventNames().contextmenuEvent);
    206         attributeNameToEventNameMap.set(ondblclickAttr.localName(), eventNames().dblclickEvent);
    207         attributeNameToEventNameMap.set(onmousedownAttr.localName(), eventNames().mousedownEvent);
    208         attributeNameToEventNameMap.set(onmouseenterAttr.localName(), eventNames().mouseenterEvent);
    209         attributeNameToEventNameMap.set(onmouseleaveAttr.localName(), eventNames().mouseleaveEvent);
    210         attributeNameToEventNameMap.set(onmousemoveAttr.localName(), eventNames().mousemoveEvent);
    211         attributeNameToEventNameMap.set(onmouseoutAttr.localName(), eventNames().mouseoutEvent);
    212         attributeNameToEventNameMap.set(onmouseoverAttr.localName(), eventNames().mouseoverEvent);
    213         attributeNameToEventNameMap.set(onmouseupAttr.localName(), eventNames().mouseupEvent);
    214         attributeNameToEventNameMap.set(onmousewheelAttr.localName(), eventNames().mousewheelEvent);
    215         attributeNameToEventNameMap.set(onfocusAttr.localName(), eventNames().focusEvent);
    216         attributeNameToEventNameMap.set(onfocusinAttr.localName(), eventNames().focusinEvent);
    217         attributeNameToEventNameMap.set(onfocusoutAttr.localName(), eventNames().focusoutEvent);
    218         attributeNameToEventNameMap.set(onblurAttr.localName(), eventNames().blurEvent);
    219         attributeNameToEventNameMap.set(onkeydownAttr.localName(), eventNames().keydownEvent);
    220         attributeNameToEventNameMap.set(onkeypressAttr.localName(), eventNames().keypressEvent);
    221         attributeNameToEventNameMap.set(onkeyupAttr.localName(), eventNames().keyupEvent);
    222         attributeNameToEventNameMap.set(onscrollAttr.localName(), eventNames().scrollEvent);
    223         attributeNameToEventNameMap.set(onbeforecutAttr.localName(), eventNames().beforecutEvent);
    224         attributeNameToEventNameMap.set(oncutAttr.localName(), eventNames().cutEvent);
    225         attributeNameToEventNameMap.set(onbeforecopyAttr.localName(), eventNames().beforecopyEvent);
    226         attributeNameToEventNameMap.set(oncopyAttr.localName(), eventNames().copyEvent);
    227         attributeNameToEventNameMap.set(onbeforepasteAttr.localName(), eventNames().beforepasteEvent);
    228         attributeNameToEventNameMap.set(onpasteAttr.localName(), eventNames().pasteEvent);
    229         attributeNameToEventNameMap.set(ondragenterAttr.localName(), eventNames().dragenterEvent);
    230         attributeNameToEventNameMap.set(ondragoverAttr.localName(), eventNames().dragoverEvent);
    231         attributeNameToEventNameMap.set(ondragleaveAttr.localName(), eventNames().dragleaveEvent);
    232         attributeNameToEventNameMap.set(ondropAttr.localName(), eventNames().dropEvent);
    233         attributeNameToEventNameMap.set(ondragstartAttr.localName(), eventNames().dragstartEvent);
    234         attributeNameToEventNameMap.set(ondragAttr.localName(), eventNames().dragEvent);
    235         attributeNameToEventNameMap.set(ondragendAttr.localName(), eventNames().dragendEvent);
    236         attributeNameToEventNameMap.set(onselectstartAttr.localName(), eventNames().selectstartEvent);
    237         attributeNameToEventNameMap.set(onsubmitAttr.localName(), eventNames().submitEvent);
    238         attributeNameToEventNameMap.set(onerrorAttr.localName(), eventNames().errorEvent);
    239         attributeNameToEventNameMap.set(onwebkitanimationstartAttr.localName(), eventNames().webkitAnimationStartEvent);
    240         attributeNameToEventNameMap.set(onwebkitanimationiterationAttr.localName(), eventNames().webkitAnimationIterationEvent);
    241         attributeNameToEventNameMap.set(onwebkitanimationendAttr.localName(), eventNames().webkitAnimationEndEvent);
    242         attributeNameToEventNameMap.set(onwebkittransitionendAttr.localName(), eventNames().webkitTransitionEndEvent);
    243         attributeNameToEventNameMap.set(ontransitionendAttr.localName(), eventNames().webkitTransitionEndEvent);
    244         attributeNameToEventNameMap.set(oninputAttr.localName(), eventNames().inputEvent);
    245         attributeNameToEventNameMap.set(oninvalidAttr.localName(), eventNames().invalidEvent);
    246         attributeNameToEventNameMap.set(ontouchstartAttr.localName(), eventNames().touchstartEvent);
    247         attributeNameToEventNameMap.set(ontouchmoveAttr.localName(), eventNames().touchmoveEvent);
    248         attributeNameToEventNameMap.set(ontouchendAttr.localName(), eventNames().touchendEvent);
    249         attributeNameToEventNameMap.set(ontouchcancelAttr.localName(), eventNames().touchcancelEvent);
    250         attributeNameToEventNameMap.set(onwebkitfullscreenchangeAttr.localName(), eventNames().webkitfullscreenchangeEvent);
    251         attributeNameToEventNameMap.set(onwebkitfullscreenerrorAttr.localName(), eventNames().webkitfullscreenerrorEvent);
    252         attributeNameToEventNameMap.set(onabortAttr.localName(), eventNames().abortEvent);
    253         attributeNameToEventNameMap.set(oncanplayAttr.localName(), eventNames().canplayEvent);
    254         attributeNameToEventNameMap.set(oncanplaythroughAttr.localName(), eventNames().canplaythroughEvent);
    255         attributeNameToEventNameMap.set(onchangeAttr.localName(), eventNames().changeEvent);
    256         attributeNameToEventNameMap.set(ondurationchangeAttr.localName(), eventNames().durationchangeEvent);
    257         attributeNameToEventNameMap.set(onemptiedAttr.localName(), eventNames().emptiedEvent);
    258         attributeNameToEventNameMap.set(onendedAttr.localName(), eventNames().endedEvent);
    259         attributeNameToEventNameMap.set(onloadeddataAttr.localName(), eventNames().loadeddataEvent);
    260         attributeNameToEventNameMap.set(onloadedmetadataAttr.localName(), eventNames().loadedmetadataEvent);
    261         attributeNameToEventNameMap.set(onloadstartAttr.localName(), eventNames().loadstartEvent);
    262         attributeNameToEventNameMap.set(onpauseAttr.localName(), eventNames().pauseEvent);
    263         attributeNameToEventNameMap.set(onplayAttr.localName(), eventNames().playEvent);
    264         attributeNameToEventNameMap.set(onplayingAttr.localName(), eventNames().playingEvent);
    265         attributeNameToEventNameMap.set(onprogressAttr.localName(), eventNames().progressEvent);
    266         attributeNameToEventNameMap.set(onratechangeAttr.localName(), eventNames().ratechangeEvent);
    267         attributeNameToEventNameMap.set(onresetAttr.localName(), eventNames().resetEvent);
    268         attributeNameToEventNameMap.set(onseekedAttr.localName(), eventNames().seekedEvent);
    269         attributeNameToEventNameMap.set(onseekingAttr.localName(), eventNames().seekingEvent);
    270         attributeNameToEventNameMap.set(onselectAttr.localName(), eventNames().selectEvent);
    271         attributeNameToEventNameMap.set(onstalledAttr.localName(), eventNames().stalledEvent);
    272         attributeNameToEventNameMap.set(onsuspendAttr.localName(), eventNames().suspendEvent);
    273         attributeNameToEventNameMap.set(ontimeupdateAttr.localName(), eventNames().timeupdateEvent);
    274         attributeNameToEventNameMap.set(onvolumechangeAttr.localName(), eventNames().volumechangeEvent);
    275         attributeNameToEventNameMap.set(onwaitingAttr.localName(), eventNames().waitingEvent);
    276         attributeNameToEventNameMap.set(onloadAttr.localName(), eventNames().loadEvent);
    277     }
    278 
    279     return attributeNameToEventNameMap.get(attrName.localName());
    280 }
    281 
    282 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
    283 {
    284     if (isIdAttributeName(name) || name == classAttr || name == styleAttr)
    285         return Element::parseAttribute(name, value);
    286 
    287     if (name == dirAttr)
    288         dirAttributeChanged(value);
    289     else if (name == tabindexAttr) {
    290         int tabindex = 0;
    291         if (value.isEmpty()) {
    292             clearTabIndexExplicitlyIfNeeded();
    293             if (treeScope()->adjustedFocusedElement() == this) {
    294                 // We might want to call blur(), but it's dangerous to dispatch
    295                 // events here.
    296                 document()->setNeedsFocusedElementCheck();
    297             }
    298         } else if (parseHTMLInteger(value, tabindex)) {
    299             // Clamp tabindex to the range of 'short' to match Firefox's behavior.
    300             setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
    301         }
    302     } else {
    303         AtomicString eventName = eventNameForAttributeName(name);
    304         if (!eventName.isNull())
    305             setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
    306     }
    307 }
    308 
    309 String HTMLElement::innerHTML() const
    310 {
    311     return createMarkup(this, ChildrenOnly);
    312 }
    313 
    314 String HTMLElement::outerHTML() const
    315 {
    316     return createMarkup(this);
    317 }
    318 
    319 void HTMLElement::setInnerHTML(const String& html, ExceptionState& es)
    320 {
    321     if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, es)) {
    322         ContainerNode* container = this;
    323         if (hasLocalName(templateTag))
    324             container = toHTMLTemplateElement(this)->content();
    325         replaceChildrenWithFragment(container, fragment.release(), es);
    326     }
    327 }
    328 
    329 static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& es)
    330 {
    331     ASSERT(node && node->isTextNode());
    332     Node* next = node->nextSibling();
    333     if (!next || !next->isTextNode())
    334         return;
    335 
    336     RefPtr<Text> textNode = toText(node.get());
    337     RefPtr<Text> textNext = toText(next);
    338     textNode->appendData(textNext->data());
    339     if (textNext->parentNode()) // Might have been removed by mutation event.
    340         textNext->remove(es);
    341 }
    342 
    343 void HTMLElement::setOuterHTML(const String& html, ExceptionState& es)
    344 {
    345     Node* p = parentNode();
    346     if (!p || !p->isHTMLElement()) {
    347         es.throwDOMException(NoModificationAllowedError);
    348         return;
    349     }
    350     RefPtr<HTMLElement> parent = toHTMLElement(p);
    351     RefPtr<Node> prev = previousSibling();
    352     RefPtr<Node> next = nextSibling();
    353 
    354     RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, es);
    355     if (es.hadException())
    356         return;
    357 
    358     parent->replaceChild(fragment.release(), this, es);
    359     RefPtr<Node> node = next ? next->previousSibling() : 0;
    360     if (!es.hadException() && node && node->isTextNode())
    361         mergeWithNextTextNode(node.release(), es);
    362 
    363     if (!es.hadException() && prev && prev->isTextNode())
    364         mergeWithNextTextNode(prev.release(), es);
    365 }
    366 
    367 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& es)
    368 {
    369     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
    370     unsigned int i, length = text.length();
    371     UChar c = 0;
    372     for (unsigned int start = 0; start < length; ) {
    373 
    374         // Find next line break.
    375         for (i = start; i < length; i++) {
    376           c = text[i];
    377           if (c == '\r' || c == '\n')
    378               break;
    379         }
    380 
    381         fragment->appendChild(Text::create(document(), text.substring(start, i - start)), es);
    382         if (es.hadException())
    383             return 0;
    384 
    385         if (c == '\r' || c == '\n') {
    386             fragment->appendChild(HTMLBRElement::create(document()), es);
    387             if (es.hadException())
    388                 return 0;
    389             // Make sure \r\n doesn't result in two line breaks.
    390             if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
    391                 i++;
    392         }
    393 
    394         start = i + 1; // Character after line break.
    395     }
    396 
    397     return fragment;
    398 }
    399 
    400 void HTMLElement::setInnerText(const String& text, ExceptionState& es)
    401 {
    402     if (ieForbidsInsertHTML()) {
    403         es.throwDOMException(NoModificationAllowedError);
    404         return;
    405     }
    406     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
    407         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
    408         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
    409         hasLocalName(trTag)) {
    410         es.throwDOMException(NoModificationAllowedError);
    411         return;
    412     }
    413 
    414     // FIXME: This doesn't take whitespace collapsing into account at all.
    415 
    416     if (!text.contains('\n') && !text.contains('\r')) {
    417         if (text.isEmpty()) {
    418             removeChildren();
    419             return;
    420         }
    421         replaceChildrenWithText(this, text, es);
    422         return;
    423     }
    424 
    425     // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
    426     // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
    427     // For example, for the contents of textarea elements that are display:none?
    428     RenderObject* r = renderer();
    429     if (r && r->style()->preserveNewline()) {
    430         if (!text.contains('\r')) {
    431             replaceChildrenWithText(this, text, es);
    432             return;
    433         }
    434         String textWithConsistentLineBreaks = text;
    435         textWithConsistentLineBreaks.replace("\r\n", "\n");
    436         textWithConsistentLineBreaks.replace('\r', '\n');
    437         replaceChildrenWithText(this, textWithConsistentLineBreaks, es);
    438         return;
    439     }
    440 
    441     // Add text nodes and <br> elements.
    442     RefPtr<DocumentFragment> fragment = textToFragment(text, es);
    443     if (!es.hadException())
    444         replaceChildrenWithFragment(this, fragment.release(), es);
    445 }
    446 
    447 void HTMLElement::setOuterText(const String &text, ExceptionState& es)
    448 {
    449     if (ieForbidsInsertHTML()) {
    450         es.throwDOMException(NoModificationAllowedError);
    451         return;
    452     }
    453     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
    454         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
    455         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
    456         hasLocalName(trTag)) {
    457         es.throwDOMException(NoModificationAllowedError);
    458         return;
    459     }
    460 
    461     ContainerNode* parent = parentNode();
    462     if (!parent) {
    463         es.throwDOMException(NoModificationAllowedError);
    464         return;
    465     }
    466 
    467     RefPtr<Node> prev = previousSibling();
    468     RefPtr<Node> next = nextSibling();
    469     RefPtr<Node> newChild;
    470 
    471     // Convert text to fragment with <br> tags instead of linebreaks if needed.
    472     if (text.contains('\r') || text.contains('\n'))
    473         newChild = textToFragment(text, es);
    474     else
    475         newChild = Text::create(document(), text);
    476 
    477     if (!this || !parentNode())
    478         es.throwDOMException(HierarchyRequestError);
    479     if (es.hadException())
    480         return;
    481     parent->replaceChild(newChild.release(), this, es);
    482 
    483     RefPtr<Node> node = next ? next->previousSibling() : 0;
    484     if (!es.hadException() && node && node->isTextNode())
    485         mergeWithNextTextNode(node.release(), es);
    486 
    487     if (!es.hadException() && prev && prev->isTextNode())
    488         mergeWithNextTextNode(prev.release(), es);
    489 }
    490 
    491 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionState& es)
    492 {
    493     // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
    494     // a document fragment is created and the elements appended in the correct order. This document
    495     // fragment isn't returned anywhere.
    496     //
    497     // This is impossible for us to implement as the DOM tree does not allow for such structures,
    498     // Opera also appears to disallow such usage.
    499 
    500     if (equalIgnoringCase(where, "beforeBegin")) {
    501         if (ContainerNode* parent = this->parentNode()) {
    502             parent->insertBefore(newChild, this, es, AttachLazily);
    503             if (!es.hadException())
    504                 return newChild;
    505         }
    506         return 0;
    507     }
    508 
    509     if (equalIgnoringCase(where, "afterBegin")) {
    510         insertBefore(newChild, firstChild(), es, AttachLazily);
    511         return es.hadException() ? 0 : newChild;
    512     }
    513 
    514     if (equalIgnoringCase(where, "beforeEnd")) {
    515         appendChild(newChild, es, AttachLazily);
    516         return es.hadException() ? 0 : newChild;
    517     }
    518 
    519     if (equalIgnoringCase(where, "afterEnd")) {
    520         if (ContainerNode* parent = this->parentNode()) {
    521             parent->insertBefore(newChild, nextSibling(), es, AttachLazily);
    522             if (!es.hadException())
    523                 return newChild;
    524         }
    525         return 0;
    526     }
    527 
    528     // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
    529     es.throwDOMException(NotSupportedError);
    530     return 0;
    531 }
    532 
    533 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& es)
    534 {
    535     if (!newChild) {
    536         // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
    537         es.throwDOMException(TypeMismatchError);
    538         return 0;
    539     }
    540 
    541     Node* returnValue = insertAdjacent(where, newChild, es);
    542     return toElement(returnValue);
    543 }
    544 
    545 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
    546 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& es)
    547 {
    548     if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
    549         ContainerNode* parent = element->parentNode();
    550         if (parent && !parent->isElementNode()) {
    551             es.throwDOMException(NoModificationAllowedError);
    552             return 0;
    553         }
    554         return toElement(parent);
    555     }
    556     if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
    557         return element;
    558     es.throwDOMException(SyntaxError);
    559     return 0;
    560 }
    561 
    562 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& es)
    563 {
    564     Element* contextElement = contextElementForInsertion(where, this, es);
    565     if (!contextElement)
    566         return;
    567     RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, es);
    568     if (!fragment)
    569         return;
    570     insertAdjacent(where, fragment.get(), es);
    571 }
    572 
    573 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& es)
    574 {
    575     RefPtr<Text> textNode = document()->createTextNode(text);
    576     insertAdjacent(where, textNode.get(), es);
    577 }
    578 
    579 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
    580 {
    581     // Vertical alignment with respect to the current baseline of the text
    582     // right or left means floating images.
    583     CSSValueID floatValue = CSSValueInvalid;
    584     CSSValueID verticalAlignValue = CSSValueInvalid;
    585 
    586     if (equalIgnoringCase(alignment, "absmiddle"))
    587         verticalAlignValue = CSSValueMiddle;
    588     else if (equalIgnoringCase(alignment, "absbottom"))
    589         verticalAlignValue = CSSValueBottom;
    590     else if (equalIgnoringCase(alignment, "left")) {
    591         floatValue = CSSValueLeft;
    592         verticalAlignValue = CSSValueTop;
    593     } else if (equalIgnoringCase(alignment, "right")) {
    594         floatValue = CSSValueRight;
    595         verticalAlignValue = CSSValueTop;
    596     } else if (equalIgnoringCase(alignment, "top"))
    597         verticalAlignValue = CSSValueTop;
    598     else if (equalIgnoringCase(alignment, "middle"))
    599         verticalAlignValue = CSSValueWebkitBaselineMiddle;
    600     else if (equalIgnoringCase(alignment, "center"))
    601         verticalAlignValue = CSSValueMiddle;
    602     else if (equalIgnoringCase(alignment, "bottom"))
    603         verticalAlignValue = CSSValueBaseline;
    604     else if (equalIgnoringCase(alignment, "texttop"))
    605         verticalAlignValue = CSSValueTextTop;
    606 
    607     if (floatValue != CSSValueInvalid)
    608         addPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, floatValue);
    609 
    610     if (verticalAlignValue != CSSValueInvalid)
    611         addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
    612 }
    613 
    614 bool HTMLElement::hasCustomFocusLogic() const
    615 {
    616     return false;
    617 }
    618 
    619 bool HTMLElement::supportsSpatialNavigationFocus() const
    620 {
    621     // This function checks whether the element satisfies the extended criteria
    622     // for the element to be focusable, introduced by spatial navigation feature,
    623     // i.e. checks if click or keyboard event handler is specified.
    624     // This is the way to make it possible to navigate to (focus) elements
    625     // which web designer meant for being active (made them respond to click events).
    626 
    627     if (!document()->settings() || !document()->settings()->spatialNavigationEnabled())
    628         return false;
    629     EventTarget* target = const_cast<HTMLElement*>(this);
    630     return target->hasEventListeners(eventNames().clickEvent)
    631         || target->hasEventListeners(eventNames().keydownEvent)
    632         || target->hasEventListeners(eventNames().keypressEvent)
    633         || target->hasEventListeners(eventNames().keyupEvent);
    634 }
    635 
    636 bool HTMLElement::supportsFocus() const
    637 {
    638     // FIXME: supportsFocus() can be called when layout is not up to date.
    639     // Logic that deals with the renderer should be moved to rendererIsFocusable().
    640     // But supportsFocus must return true when the element is editable, or else
    641     // it won't be focusable. Furthermore, supportsFocus cannot just return true
    642     // always or else tabIndex() will change for all HTML elements.
    643     return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable())
    644         || supportsSpatialNavigationFocus();
    645 }
    646 
    647 String HTMLElement::contentEditable() const
    648 {
    649     const AtomicString& value = fastGetAttribute(contenteditableAttr);
    650 
    651     if (value.isNull())
    652         return "inherit";
    653     if (value.isEmpty() || equalIgnoringCase(value, "true"))
    654         return "true";
    655     if (equalIgnoringCase(value, "false"))
    656          return "false";
    657     if (equalIgnoringCase(value, "plaintext-only"))
    658         return "plaintext-only";
    659 
    660     return "inherit";
    661 }
    662 
    663 void HTMLElement::setContentEditable(const String& enabled, ExceptionState& es)
    664 {
    665     if (equalIgnoringCase(enabled, "true"))
    666         setAttribute(contenteditableAttr, "true");
    667     else if (equalIgnoringCase(enabled, "false"))
    668         setAttribute(contenteditableAttr, "false");
    669     else if (equalIgnoringCase(enabled, "plaintext-only"))
    670         setAttribute(contenteditableAttr, "plaintext-only");
    671     else if (equalIgnoringCase(enabled, "inherit"))
    672         removeAttribute(contenteditableAttr);
    673     else
    674         es.throwDOMException(SyntaxError);
    675 }
    676 
    677 bool HTMLElement::draggable() const
    678 {
    679     return equalIgnoringCase(getAttribute(draggableAttr), "true");
    680 }
    681 
    682 void HTMLElement::setDraggable(bool value)
    683 {
    684     setAttribute(draggableAttr, value ? "true" : "false");
    685 }
    686 
    687 bool HTMLElement::spellcheck() const
    688 {
    689     return isSpellCheckingEnabled();
    690 }
    691 
    692 void HTMLElement::setSpellcheck(bool enable)
    693 {
    694     setAttribute(spellcheckAttr, enable ? "true" : "false");
    695 }
    696 
    697 
    698 void HTMLElement::click()
    699 {
    700     dispatchSimulatedClick(0, SendNoEvents, DoNotShowPressedLook);
    701 }
    702 
    703 void HTMLElement::accessKeyAction(bool sendMouseEvents)
    704 {
    705     dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
    706 }
    707 
    708 String HTMLElement::title() const
    709 {
    710     return getAttribute(titleAttr);
    711 }
    712 
    713 short HTMLElement::tabIndex() const
    714 {
    715     if (supportsFocus())
    716         return Element::tabIndex();
    717     return -1;
    718 }
    719 
    720 void HTMLElement::setTabIndex(int value)
    721 {
    722     setAttribute(tabindexAttr, String::number(value));
    723 }
    724 
    725 TranslateAttributeMode HTMLElement::translateAttributeMode() const
    726 {
    727     const AtomicString& value = getAttribute(translateAttr);
    728 
    729     if (value == nullAtom)
    730         return TranslateAttributeInherit;
    731     if (equalIgnoringCase(value, "yes") || equalIgnoringCase(value, ""))
    732         return TranslateAttributeYes;
    733     if (equalIgnoringCase(value, "no"))
    734         return TranslateAttributeNo;
    735 
    736     return TranslateAttributeInherit;
    737 }
    738 
    739 bool HTMLElement::translate() const
    740 {
    741     for (const Node* n = this; n; n = n->parentNode()) {
    742         if (n->isHTMLElement()) {
    743             TranslateAttributeMode mode = static_cast<const HTMLElement*>(n)->translateAttributeMode();
    744             if (mode != TranslateAttributeInherit) {
    745                 ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
    746                 return mode == TranslateAttributeYes;
    747             }
    748         }
    749     }
    750 
    751     // Default on the root element is translate=yes.
    752     return true;
    753 }
    754 
    755 void HTMLElement::setTranslate(bool enable)
    756 {
    757     setAttribute(translateAttr, enable ? "yes" : "no");
    758 }
    759 
    760 bool HTMLElement::rendererIsNeeded(const NodeRenderingContext& context)
    761 {
    762     if (hasLocalName(noscriptTag)) {
    763         Frame* frame = document()->frame();
    764         if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
    765             return false;
    766     } else if (hasLocalName(noembedTag)) {
    767         Frame* frame = document()->frame();
    768         if (frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
    769             return false;
    770     }
    771     return Element::rendererIsNeeded(context);
    772 }
    773 
    774 RenderObject* HTMLElement::createRenderer(RenderStyle* style)
    775 {
    776     if (hasLocalName(wbrTag))
    777         return new RenderWordBreak(this);
    778     return RenderObject::createObject(this, style);
    779 }
    780 
    781 HTMLFormElement* HTMLElement::findFormAncestor() const
    782 {
    783     for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
    784         if (ancestor->hasTagName(formTag))
    785             return toHTMLFormElement(ancestor);
    786     }
    787     return 0;
    788 }
    789 
    790 HTMLFormElement* HTMLElement::virtualForm() const
    791 {
    792     return findFormAncestor();
    793 }
    794 
    795 static inline bool elementAffectsDirectionality(const Node* node)
    796 {
    797     return node->isHTMLElement() && (node->hasTagName(bdiTag) || toHTMLElement(node)->hasAttribute(dirAttr));
    798 }
    799 
    800 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
    801 {
    802     firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
    803 
    804     Node* node = firstNode->firstChild();
    805 
    806     while (node) {
    807         if (node->selfOrAncestorHasDirAutoAttribute() == flag)
    808             return;
    809 
    810         if (elementAffectsDirectionality(node)) {
    811             if (node == lastNode)
    812                 return;
    813             node = NodeTraversal::nextSkippingChildren(node, firstNode);
    814             continue;
    815         }
    816         node->setSelfOrAncestorHasDirAutoAttribute(flag);
    817         if (node == lastNode)
    818             return;
    819         node = NodeTraversal::next(node, firstNode);
    820     }
    821 }
    822 
    823 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
    824 {
    825     Element::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
    826     adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
    827 }
    828 
    829 bool HTMLElement::hasDirectionAuto() const
    830 {
    831     const AtomicString& direction = fastGetAttribute(dirAttr);
    832     return (hasTagName(bdiTag) && direction == nullAtom) || equalIgnoringCase(direction, "auto");
    833 }
    834 
    835 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
    836 {
    837     if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
    838         isAuto = false;
    839         return LTR;
    840     }
    841 
    842     isAuto = true;
    843     return directionality();
    844 }
    845 
    846 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
    847 {
    848     if (isHTMLTextFormControlElement(this)) {
    849         HTMLTextFormControlElement* textElement = toHTMLTextFormControlElement(const_cast<HTMLElement*>(this));
    850         bool hasStrongDirectionality;
    851         Unicode::Direction textDirection = textElement->value().defaultWritingDirection(&hasStrongDirectionality);
    852         if (strongDirectionalityTextNode)
    853             *strongDirectionalityTextNode = hasStrongDirectionality ? textElement : 0;
    854         return (textDirection == Unicode::LeftToRight) ? LTR : RTL;
    855     }
    856 
    857     Node* node = firstChild();
    858     while (node) {
    859         // Skip bdi, script, style and text form controls.
    860         if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
    861             || (node->isElementNode() && toElement(node)->isTextFormControl())) {
    862             node = NodeTraversal::nextSkippingChildren(node, this);
    863             continue;
    864         }
    865 
    866         // Skip elements with valid dir attribute
    867         if (node->isElementNode()) {
    868             AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
    869             if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
    870                 node = NodeTraversal::nextSkippingChildren(node, this);
    871                 continue;
    872             }
    873         }
    874 
    875         if (node->isTextNode()) {
    876             bool hasStrongDirectionality;
    877             WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
    878             if (hasStrongDirectionality) {
    879                 if (strongDirectionalityTextNode)
    880                     *strongDirectionalityTextNode = node;
    881                 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
    882             }
    883         }
    884         node = NodeTraversal::next(node, this);
    885     }
    886     if (strongDirectionalityTextNode)
    887         *strongDirectionalityTextNode = 0;
    888     return LTR;
    889 }
    890 
    891 void HTMLElement::dirAttributeChanged(const AtomicString& value)
    892 {
    893     Element* parent = parentElement();
    894 
    895     if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
    896         toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
    897 
    898     if (equalIgnoringCase(value, "auto"))
    899         calculateAndAdjustDirectionality();
    900 }
    901 
    902 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
    903 {
    904     ASSERT(selfOrAncestorHasDirAutoAttribute());
    905     Node* strongDirectionalityTextNode;
    906     TextDirection textDirection = directionality(&strongDirectionalityTextNode);
    907     setHasDirAutoFlagRecursively(child, false);
    908     if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
    909         Element* elementToAdjust = this;
    910         for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
    911             if (elementAffectsDirectionality(elementToAdjust)) {
    912                 elementToAdjust->setNeedsStyleRecalc();
    913                 return;
    914             }
    915         }
    916     }
    917 }
    918 
    919 void HTMLElement::calculateAndAdjustDirectionality()
    920 {
    921     Node* strongDirectionalityTextNode;
    922     TextDirection textDirection = directionality(&strongDirectionalityTextNode);
    923     setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
    924     if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
    925         setNeedsStyleRecalc();
    926 }
    927 
    928 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
    929 {
    930     if ((!document() || document()->renderer()) && childCountDelta < 0) {
    931         Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
    932         for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(node)) {
    933             if (elementAffectsDirectionality(node))
    934                 continue;
    935 
    936             setHasDirAutoFlagRecursively(node, false);
    937         }
    938     }
    939 
    940     if (!selfOrAncestorHasDirAutoAttribute())
    941         return;
    942 
    943     Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
    944     while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
    945         oldMarkedNode = NodeTraversal::nextSkippingChildren(oldMarkedNode, this);
    946     if (oldMarkedNode)
    947         setHasDirAutoFlagRecursively(oldMarkedNode, false);
    948 
    949     for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
    950         if (elementAffectsDirectionality(elementToAdjust)) {
    951             toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
    952             return;
    953         }
    954     }
    955 }
    956 
    957 void HTMLElement::addHTMLLengthToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
    958 {
    959     // FIXME: This function should not spin up the CSS parser, but should instead just figure out the correct
    960     // length unit and make the appropriate parsed value.
    961 
    962     // strip attribute garbage..
    963     StringImpl* v = value.impl();
    964     if (v) {
    965         unsigned int l = 0;
    966 
    967         while (l < v->length() && (*v)[l] <= ' ')
    968             l++;
    969 
    970         for (; l < v->length(); l++) {
    971             UChar cc = (*v)[l];
    972             if (cc > '9')
    973                 break;
    974             if (cc < '0') {
    975                 if (cc == '%' || cc == '*')
    976                     l++;
    977                 if (cc != '.')
    978                     break;
    979             }
    980         }
    981 
    982         if (l != v->length()) {
    983             addPropertyToPresentationAttributeStyle(style, propertyID, v->substring(0, l));
    984             return;
    985         }
    986     }
    987 
    988     addPropertyToPresentationAttributeStyle(style, propertyID, value);
    989 }
    990 
    991 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
    992 {
    993     // Per spec, only look at the first 128 digits of the string.
    994     const size_t maxColorLength = 128;
    995     // We'll pad the buffer with two extra 0s later, so reserve two more than the max.
    996     Vector<char, maxColorLength+2> digitBuffer;
    997 
    998     size_t i = 0;
    999     // Skip a leading #.
   1000     if (colorString[0] == '#')
   1001         i = 1;
   1002 
   1003     // Grab the first 128 characters, replacing non-hex characters with 0.
   1004     // Non-BMP characters are replaced with "00" due to them appearing as two "characters" in the String.
   1005     for (; i < colorString.length() && digitBuffer.size() < maxColorLength; i++) {
   1006         if (!isASCIIHexDigit(colorString[i]))
   1007             digitBuffer.append('0');
   1008         else
   1009             digitBuffer.append(colorString[i]);
   1010     }
   1011 
   1012     if (!digitBuffer.size())
   1013         return Color::black;
   1014 
   1015     // Pad the buffer out to at least the next multiple of three in size.
   1016     digitBuffer.append('0');
   1017     digitBuffer.append('0');
   1018 
   1019     if (digitBuffer.size() < 6)
   1020         return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
   1021 
   1022     // Split the digits into three components, then search the last 8 digits of each component.
   1023     ASSERT(digitBuffer.size() >= 6);
   1024     size_t componentLength = digitBuffer.size() / 3;
   1025     size_t componentSearchWindowLength = min<size_t>(componentLength, 8);
   1026     size_t redIndex = componentLength - componentSearchWindowLength;
   1027     size_t greenIndex = componentLength * 2 - componentSearchWindowLength;
   1028     size_t blueIndex = componentLength * 3 - componentSearchWindowLength;
   1029     // Skip digits until one of them is non-zero, or we've only got two digits left in the component.
   1030     while (digitBuffer[redIndex] == '0' && digitBuffer[greenIndex] == '0' && digitBuffer[blueIndex] == '0' && (componentLength - redIndex) > 2) {
   1031         redIndex++;
   1032         greenIndex++;
   1033         blueIndex++;
   1034     }
   1035     ASSERT(redIndex + 1 < componentLength);
   1036     ASSERT(greenIndex >= componentLength);
   1037     ASSERT(greenIndex + 1 < componentLength * 2);
   1038     ASSERT(blueIndex >= componentLength * 2);
   1039     ASSERT_WITH_SECURITY_IMPLICATION(blueIndex + 1 < digitBuffer.size());
   1040 
   1041     int redValue = toASCIIHexValue(digitBuffer[redIndex], digitBuffer[redIndex + 1]);
   1042     int greenValue = toASCIIHexValue(digitBuffer[greenIndex], digitBuffer[greenIndex + 1]);
   1043     int blueValue = toASCIIHexValue(digitBuffer[blueIndex], digitBuffer[blueIndex + 1]);
   1044     return makeRGB(redValue, greenValue, blueValue);
   1045 }
   1046 
   1047 // Color parsing that matches HTML's "rules for parsing a legacy color value"
   1048 void HTMLElement::addHTMLColorToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& attributeValue)
   1049 {
   1050     // An empty string doesn't apply a color. (One containing only whitespace does, which is why this check occurs before stripping.)
   1051     if (attributeValue.isEmpty())
   1052         return;
   1053 
   1054     String colorString = attributeValue.stripWhiteSpace();
   1055 
   1056     // "transparent" doesn't apply a color either.
   1057     if (equalIgnoringCase(colorString, "transparent"))
   1058         return;
   1059 
   1060     // If the string is a named CSS color or a 3/6-digit hex color, use that.
   1061     StyleColor parsedColor(colorString);
   1062     if (!parsedColor.isValid())
   1063         parsedColor = parseColorStringWithCrazyLegacyRules(colorString);
   1064 
   1065     style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
   1066 }
   1067 
   1068 void HTMLElement::defaultEventHandler(Event* event)
   1069 {
   1070     if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) {
   1071         handleKeypressEvent(toKeyboardEvent(event));
   1072         if (event->defaultHandled())
   1073             return;
   1074     }
   1075 
   1076     Element::defaultEventHandler(event);
   1077 }
   1078 
   1079 void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
   1080 {
   1081     if (!document()->settings() || !document()->settings()->spatialNavigationEnabled() || !supportsFocus())
   1082         return;
   1083     // if the element is a text form control (like <input type=text> or <textarea>)
   1084     // or has contentEditable attribute on, we should enter a space or newline
   1085     // even in spatial navigation mode instead of handling it as a "click" action.
   1086     if (isTextFormControl() || isContentEditable())
   1087         return;
   1088     int charCode = event->charCode();
   1089     if (charCode == '\r' || charCode == ' ') {
   1090         dispatchSimulatedClick(event);
   1091         event->setDefaultHandled();
   1092     }
   1093 }
   1094 
   1095 } // namespace WebCore
   1096 
   1097 #ifndef NDEBUG
   1098 
   1099 // For use in the debugger
   1100 void dumpInnerHTML(WebCore::HTMLElement*);
   1101 
   1102 void dumpInnerHTML(WebCore::HTMLElement* element)
   1103 {
   1104     printf("%s\n", element->innerHTML().ascii().data());
   1105 }
   1106 #endif
   1107