Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@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/ScriptEventListener.h"
34 #include "core/css/CSSMarkup.h"
35 #include "core/css/CSSValuePool.h"
36 #include "core/css/StylePropertySet.h"
37 #include "core/dom/DocumentFragment.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/dom/NodeTraversal.h"
40 #include "core/dom/Text.h"
41 #include "core/editing/markup.h"
42 #include "core/events/EventListener.h"
43 #include "core/events/KeyboardEvent.h"
44 #include "core/frame/Settings.h"
45 #include "core/html/HTMLBRElement.h"
46 #include "core/html/HTMLFormElement.h"
47 #include "core/html/HTMLInputElement.h"
48 #include "core/html/HTMLTemplateElement.h"
49 #include "core/html/HTMLTextFormControlElement.h"
50 #include "core/html/parser/HTMLParserIdioms.h"
51 #include "core/rendering/RenderObject.h"
52 #include "platform/text/BidiResolver.h"
53 #include "platform/text/BidiTextRun.h"
54 #include "platform/text/TextRunIterator.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 PassRefPtrWillBeRawPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document& document)
67 {
68     return adoptRefWillBeRefCountedGarbageCollected(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()) {
77         if (!tagQName().hasPrefix())
78             return tagQName().localNameUpper();
79         return Element::nodeName().upper();
80     }
81     return Element::nodeName();
82 }
83
84 bool HTMLElement::ieForbidsInsertHTML() const
85 {
86     // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
87     // and createContextualFragment on these tags.  We have no tests to
88     // verify this however, so this list could be totally wrong.
89     // This list was moved from the previous endTagRequirement() implementation.
90     // This is also called from editing and assumed to be the list of tags
91     // for which no end tag should be serialized. It's unclear if the list for
92     // IE compat and the list for serialization sanity are the same.
93     if (hasLocalName(areaTag)
94         || hasLocalName(baseTag)
95         || hasLocalName(basefontTag)
96         || hasLocalName(brTag)
97         || hasLocalName(colTag)
98         || hasLocalName(embedTag)
99         || hasLocalName(frameTag)
100         || hasLocalName(hrTag)
101         || hasLocalName(imageTag)
102         || hasLocalName(imgTag)
103         || hasLocalName(inputTag)
104         || hasLocalName(linkTag)
105         || hasLocalName(metaTag)
106         || hasLocalName(paramTag)
107         || hasLocalName(sourceTag)
108         || hasLocalName(wbrTag))
109         return true;
110     return false;
111 }
112
113 static inline CSSValueID unicodeBidiAttributeForDirAuto(HTMLElement* element)
114 {
115     if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
116         return CSSValueWebkitPlaintext;
117     // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
118     // See https://bugs.webkit.org/show_bug.cgi?id=73164.
119     return CSSValueWebkitIsolate;
120 }
121
122 unsigned HTMLElement::parseBorderWidthAttribute(const AtomicString& value) const
123 {
124     unsigned borderWidth = 0;
125     if (value.isEmpty() || !parseHTMLNonNegativeInteger(value, borderWidth))
126         return hasLocalName(tableTag) ? 1 : borderWidth;
127     return borderWidth;
128 }
129
130 void HTMLElement::applyBorderAttributeToStyle(const AtomicString& value, MutableStylePropertySet* style)
131 {
132     addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(value), CSSPrimitiveValue::CSS_PX);
133     addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
134 }
135
136 void HTMLElement::mapLanguageAttributeToLocale(const AtomicString& value, MutableStylePropertySet* style)
137 {
138     if (!value.isEmpty()) {
139         // Have to quote so the locale id is treated as a string instead of as a CSS keyword.
140         addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, quoteCSSString(value));
141     } else {
142         // The empty string means the language is explicitly unknown.
143         addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
144     }
145 }
146
147 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
148 {
149     if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
150         return true;
151     return Element::isPresentationAttribute(name);
152 }
153
154 static inline bool isValidDirAttribute(const AtomicString& value)
155 {
156     return equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "ltr") || equalIgnoringCase(value, "rtl");
157 }
158
159 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
160 {
161     if (name == alignAttr) {
162         if (equalIgnoringCase(value, "middle"))
163             addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
164         else
165             addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, value);
166     } else if (name == contenteditableAttr) {
167         if (value.isEmpty() || equalIgnoringCase(value, "true")) {
168             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
169             addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
170             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
171         } else if (equalIgnoringCase(value, "plaintext-only")) {
172             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
173             addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
174             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
175         } else if (equalIgnoringCase(value, "false"))
176             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
177     } else if (name == hiddenAttr) {
178         addPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
179     } else if (name == draggableAttr) {
180         if (equalIgnoringCase(value, "true")) {
181             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
182             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
183         } else if (equalIgnoringCase(value, "false"))
184             addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
185     } else if (name == dirAttr) {
186         if (equalIgnoringCase(value, "auto"))
187             addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
188         else {
189             if (isValidDirAttribute(value))
190                 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
191             else
192                 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, "ltr");
193             if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
194                 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
195         }
196     } else if (name.matches(XMLNames::langAttr))
197         mapLanguageAttributeToLocale(value, style);
198     else if (name == langAttr) {
199         // xml:lang has a higher priority than lang.
200         if (!fastHasAttribute(XMLNames::langAttr))
201             mapLanguageAttributeToLocale(value, style);
202     } else
203         Element::collectStyleForPresentationAttribute(name, value, style);
204 }
205
206 const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName)
207 {
208     if (!attrName.namespaceURI().isNull())
209         return nullAtom;
210
211     if (!attrName.localName().startsWith("on", false))
212         return nullAtom;
213
214     typedef HashMap<AtomicString, AtomicString> StringToStringMap;
215     DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
216     if (!attributeNameToEventNameMap.size()) {
217         attributeNameToEventNameMap.set(onabortAttr.localName(), EventTypeNames::abort);
218         attributeNameToEventNameMap.set(onanimationendAttr.localName(), EventTypeNames::animationend);
219         attributeNameToEventNameMap.set(onanimationiterationAttr.localName(), EventTypeNames::animationiteration);
220         attributeNameToEventNameMap.set(onanimationstartAttr.localName(), EventTypeNames::animationstart);
221         attributeNameToEventNameMap.set(onautocompleteAttr.localName(), EventTypeNames::autocomplete);
222         attributeNameToEventNameMap.set(onautocompleteerrorAttr.localName(), EventTypeNames::autocompleteerror);
223         attributeNameToEventNameMap.set(onbeforecopyAttr.localName(), EventTypeNames::beforecopy);
224         attributeNameToEventNameMap.set(onbeforecutAttr.localName(), EventTypeNames::beforecut);
225         attributeNameToEventNameMap.set(onbeforepasteAttr.localName(), EventTypeNames::beforepaste);
226         attributeNameToEventNameMap.set(onblurAttr.localName(), EventTypeNames::blur);
227         attributeNameToEventNameMap.set(oncancelAttr.localName(), EventTypeNames::cancel);
228         attributeNameToEventNameMap.set(oncanplayAttr.localName(), EventTypeNames::canplay);
229         attributeNameToEventNameMap.set(oncanplaythroughAttr.localName(), EventTypeNames::canplaythrough);
230         attributeNameToEventNameMap.set(onchangeAttr.localName(), EventTypeNames::change);
231         attributeNameToEventNameMap.set(onclickAttr.localName(), EventTypeNames::click);
232         attributeNameToEventNameMap.set(oncloseAttr.localName(), EventTypeNames::close);
233         attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), EventTypeNames::contextmenu);
234         attributeNameToEventNameMap.set(oncopyAttr.localName(), EventTypeNames::copy);
235         attributeNameToEventNameMap.set(oncuechangeAttr.localName(), EventTypeNames::cuechange);
236         attributeNameToEventNameMap.set(oncutAttr.localName(), EventTypeNames::cut);
237         attributeNameToEventNameMap.set(ondblclickAttr.localName(), EventTypeNames::dblclick);
238         attributeNameToEventNameMap.set(ondragAttr.localName(), EventTypeNames::drag);
239         attributeNameToEventNameMap.set(ondragendAttr.localName(), EventTypeNames::dragend);
240         attributeNameToEventNameMap.set(ondragenterAttr.localName(), EventTypeNames::dragenter);
241         attributeNameToEventNameMap.set(ondragleaveAttr.localName(), EventTypeNames::dragleave);
242         attributeNameToEventNameMap.set(ondragoverAttr.localName(), EventTypeNames::dragover);
243         attributeNameToEventNameMap.set(ondragstartAttr.localName(), EventTypeNames::dragstart);
244         attributeNameToEventNameMap.set(ondropAttr.localName(), EventTypeNames::drop);
245         attributeNameToEventNameMap.set(ondurationchangeAttr.localName(), EventTypeNames::durationchange);
246         attributeNameToEventNameMap.set(onemptiedAttr.localName(), EventTypeNames::emptied);
247         attributeNameToEventNameMap.set(onendedAttr.localName(), EventTypeNames::ended);
248         attributeNameToEventNameMap.set(onerrorAttr.localName(), EventTypeNames::error);
249         attributeNameToEventNameMap.set(onfocusAttr.localName(), EventTypeNames::focus);
250         attributeNameToEventNameMap.set(onfocusinAttr.localName(), EventTypeNames::focusin);
251         attributeNameToEventNameMap.set(onfocusoutAttr.localName(), EventTypeNames::focusout);
252         attributeNameToEventNameMap.set(oninputAttr.localName(), EventTypeNames::input);
253         attributeNameToEventNameMap.set(oninvalidAttr.localName(), EventTypeNames::invalid);
254         attributeNameToEventNameMap.set(onkeydownAttr.localName(), EventTypeNames::keydown);
255         attributeNameToEventNameMap.set(onkeypressAttr.localName(), EventTypeNames::keypress);
256         attributeNameToEventNameMap.set(onkeyupAttr.localName(), EventTypeNames::keyup);
257         attributeNameToEventNameMap.set(onloadAttr.localName(), EventTypeNames::load);
258         attributeNameToEventNameMap.set(onloadeddataAttr.localName(), EventTypeNames::loadeddata);
259         attributeNameToEventNameMap.set(onloadedmetadataAttr.localName(), EventTypeNames::loadedmetadata);
260         attributeNameToEventNameMap.set(onloadstartAttr.localName(), EventTypeNames::loadstart);
261         attributeNameToEventNameMap.set(onmousedownAttr.localName(), EventTypeNames::mousedown);
262         attributeNameToEventNameMap.set(onmouseenterAttr.localName(), EventTypeNames::mouseenter);
263         attributeNameToEventNameMap.set(onmouseleaveAttr.localName(), EventTypeNames::mouseleave);
264         attributeNameToEventNameMap.set(onmousemoveAttr.localName(), EventTypeNames::mousemove);
265         attributeNameToEventNameMap.set(onmouseoutAttr.localName(), EventTypeNames::mouseout);
266         attributeNameToEventNameMap.set(onmouseoverAttr.localName(), EventTypeNames::mouseover);
267         attributeNameToEventNameMap.set(onmouseupAttr.localName(), EventTypeNames::mouseup);
268         attributeNameToEventNameMap.set(onmousewheelAttr.localName(), EventTypeNames::mousewheel);
269         attributeNameToEventNameMap.set(onpasteAttr.localName(), EventTypeNames::paste);
270         attributeNameToEventNameMap.set(onpauseAttr.localName(), EventTypeNames::pause);
271         attributeNameToEventNameMap.set(onplayAttr.localName(), EventTypeNames::play);
272         attributeNameToEventNameMap.set(onplayingAttr.localName(), EventTypeNames::playing);
273         attributeNameToEventNameMap.set(onprogressAttr.localName(), EventTypeNames::progress);
274         attributeNameToEventNameMap.set(onratechangeAttr.localName(), EventTypeNames::ratechange);
275         attributeNameToEventNameMap.set(onresetAttr.localName(), EventTypeNames::reset);
276         attributeNameToEventNameMap.set(onresizeAttr.localName(), EventTypeNames::resize);
277         attributeNameToEventNameMap.set(onscrollAttr.localName(), EventTypeNames::scroll);
278         attributeNameToEventNameMap.set(onseekedAttr.localName(), EventTypeNames::seeked);
279         attributeNameToEventNameMap.set(onseekingAttr.localName(), EventTypeNames::seeking);
280         attributeNameToEventNameMap.set(onselectAttr.localName(), EventTypeNames::select);
281         attributeNameToEventNameMap.set(onselectstartAttr.localName(), EventTypeNames::selectstart);
282         attributeNameToEventNameMap.set(onshowAttr.localName(), EventTypeNames::show);
283         attributeNameToEventNameMap.set(onstalledAttr.localName(), EventTypeNames::stalled);
284         attributeNameToEventNameMap.set(onsubmitAttr.localName(), EventTypeNames::submit);
285         attributeNameToEventNameMap.set(onsuspendAttr.localName(), EventTypeNames::suspend);
286         attributeNameToEventNameMap.set(ontimeupdateAttr.localName(), EventTypeNames::timeupdate);
287         attributeNameToEventNameMap.set(ontoggleAttr.localName(), EventTypeNames::toggle);
288         attributeNameToEventNameMap.set(ontouchcancelAttr.localName(), EventTypeNames::touchcancel);
289         attributeNameToEventNameMap.set(ontouchendAttr.localName(), EventTypeNames::touchend);
290         attributeNameToEventNameMap.set(ontouchmoveAttr.localName(), EventTypeNames::touchmove);
291         attributeNameToEventNameMap.set(ontouchstartAttr.localName(), EventTypeNames::touchstart);
292         attributeNameToEventNameMap.set(ontransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
293         attributeNameToEventNameMap.set(onvolumechangeAttr.localName(), EventTypeNames::volumechange);
294         attributeNameToEventNameMap.set(onwaitingAttr.localName(), EventTypeNames::waiting);
295         attributeNameToEventNameMap.set(onwebkitanimationendAttr.localName(), EventTypeNames::webkitAnimationEnd);
296         attributeNameToEventNameMap.set(onwebkitanimationiterationAttr.localName(), EventTypeNames::webkitAnimationIteration);
297         attributeNameToEventNameMap.set(onwebkitanimationstartAttr.localName(), EventTypeNames::webkitAnimationStart);
298         attributeNameToEventNameMap.set(onwebkitfullscreenchangeAttr.localName(), EventTypeNames::webkitfullscreenchange);
299         attributeNameToEventNameMap.set(onwebkitfullscreenerrorAttr.localName(), EventTypeNames::webkitfullscreenerror);
300         attributeNameToEventNameMap.set(onwebkittransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
301         attributeNameToEventNameMap.set(onwheelAttr.localName(), EventTypeNames::wheel);
302     }
303
304     return attributeNameToEventNameMap.get(attrName.localName());
305 }
306
307 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
308 {
309     if (name == tabindexAttr)
310         return Element::parseAttribute(name, value);
311
312     if (name == dirAttr) {
313         dirAttributeChanged(value);
314     } else {
315         const AtomicString& eventName = eventNameForAttributeName(name);
316         if (!eventName.isNull())
317             setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
318     }
319 }
320
321 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& exceptionState)
322 {
323     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
324     unsigned i, length = text.length();
325     UChar c = 0;
326     for (unsigned start = 0; start < length; ) {
327
328         // Find next line break.
329         for (i = start; i < length; i++) {
330           c = text[i];
331           if (c == '\r' || c == '\n')
332               break;
333         }
334
335         fragment->appendChild(Text::create(document(), text.substring(start, i - start)), exceptionState);
336         if (exceptionState.hadException())
337             return nullptr;
338
339         if (c == '\r' || c == '\n') {
340             fragment->appendChild(HTMLBRElement::create(document()), exceptionState);
341             if (exceptionState.hadException())
342                 return nullptr;
343             // Make sure \r\n doesn't result in two line breaks.
344             if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
345                 i++;
346         }
347
348         start = i + 1; // Character after line break.
349     }
350
351     return fragment;
352 }
353
354 void HTMLElement::setInnerText(const String& text, ExceptionState& exceptionState)
355 {
356     if (ieForbidsInsertHTML()) {
357         exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
358         return;
359     }
360     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
361         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
362         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
363         hasLocalName(trTag)) {
364         exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
365         return;
366     }
367
368     // FIXME: This doesn't take whitespace collapsing into account at all.
369
370     if (!text.contains('\n') && !text.contains('\r')) {
371         if (text.isEmpty()) {
372             removeChildren();
373             return;
374         }
375         replaceChildrenWithText(this, text, exceptionState);
376         return;
377     }
378
379     // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
380     // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
381     // For example, for the contents of textarea elements that are display:none?
382     RenderObject* r = renderer();
383     if (r && r->style()->preserveNewline()) {
384         if (!text.contains('\r')) {
385             replaceChildrenWithText(this, text, exceptionState);
386             return;
387         }
388         String textWithConsistentLineBreaks = text;
389         textWithConsistentLineBreaks.replace("\r\n", "\n");
390         textWithConsistentLineBreaks.replace('\r', '\n');
391         replaceChildrenWithText(this, textWithConsistentLineBreaks, exceptionState);
392         return;
393     }
394
395     // Add text nodes and <br> elements.
396     RefPtr<DocumentFragment> fragment = textToFragment(text, exceptionState);
397     if (!exceptionState.hadException())
398         replaceChildrenWithFragment(this, fragment.release(), exceptionState);
399 }
400
401 void HTMLElement::setOuterText(const String &text, ExceptionState& exceptionState)
402 {
403     if (ieForbidsInsertHTML()) {
404         exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
405         return;
406     }
407     if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
408         hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
409         hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
410         hasLocalName(trTag)) {
411         exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
412         return;
413     }
414
415     ContainerNode* parent = parentNode();
416     if (!parent) {
417         exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
418         return;
419     }
420
421     RefPtr<Node> prev = previousSibling();
422     RefPtr<Node> next = nextSibling();
423     RefPtr<Node> newChild;
424
425     // Convert text to fragment with <br> tags instead of linebreaks if needed.
426     if (text.contains('\r') || text.contains('\n'))
427         newChild = textToFragment(text, exceptionState);
428     else
429         newChild = Text::create(document(), text);
430
431     // textToFragment might cause mutation events.
432     if (!this || !parentNode())
433         exceptionState.throwDOMException(HierarchyRequestError, "The element has no parent.");
434
435     if (exceptionState.hadException())
436         return;
437
438     parent->replaceChild(newChild.release(), this, exceptionState);
439
440     RefPtr<Node> node = next ? next->previousSibling() : 0;
441     if (!exceptionState.hadException() && node && node->isTextNode())
442         mergeWithNextTextNode(node.release(), exceptionState);
443
444     if (!exceptionState.hadException() && prev && prev->isTextNode())
445         mergeWithNextTextNode(prev.release(), exceptionState);
446 }
447
448 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
449 {
450     // Vertical alignment with respect to the current baseline of the text
451     // right or left means floating images.
452     CSSValueID floatValue = CSSValueInvalid;
453     CSSValueID verticalAlignValue = CSSValueInvalid;
454
455     if (equalIgnoringCase(alignment, "absmiddle"))
456         verticalAlignValue = CSSValueMiddle;
457     else if (equalIgnoringCase(alignment, "absbottom"))
458         verticalAlignValue = CSSValueBottom;
459     else if (equalIgnoringCase(alignment, "left")) {
460         floatValue = CSSValueLeft;
461         verticalAlignValue = CSSValueTop;
462     } else if (equalIgnoringCase(alignment, "right")) {
463         floatValue = CSSValueRight;
464         verticalAlignValue = CSSValueTop;
465     } else if (equalIgnoringCase(alignment, "top"))
466         verticalAlignValue = CSSValueTop;
467     else if (equalIgnoringCase(alignment, "middle"))
468         verticalAlignValue = CSSValueWebkitBaselineMiddle;
469     else if (equalIgnoringCase(alignment, "center"))
470         verticalAlignValue = CSSValueMiddle;
471     else if (equalIgnoringCase(alignment, "bottom"))
472         verticalAlignValue = CSSValueBaseline;
473     else if (equalIgnoringCase(alignment, "texttop"))
474         verticalAlignValue = CSSValueTextTop;
475
476     if (floatValue != CSSValueInvalid)
477         addPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, floatValue);
478
479     if (verticalAlignValue != CSSValueInvalid)
480         addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
481 }
482
483 bool HTMLElement::hasCustomFocusLogic() const
484 {
485     return false;
486 }
487
488 String HTMLElement::contentEditable() const
489 {
490     const AtomicString& value = fastGetAttribute(contenteditableAttr);
491
492     if (value.isNull())
493         return "inherit";
494     if (value.isEmpty() || equalIgnoringCase(value, "true"))
495         return "true";
496     if (equalIgnoringCase(value, "false"))
497          return "false";
498     if (equalIgnoringCase(value, "plaintext-only"))
499         return "plaintext-only";
500
501     return "inherit";
502 }
503
504 void HTMLElement::setContentEditable(const String& enabled, ExceptionState& exceptionState)
505 {
506     if (equalIgnoringCase(enabled, "true"))
507         setAttribute(contenteditableAttr, "true");
508     else if (equalIgnoringCase(enabled, "false"))
509         setAttribute(contenteditableAttr, "false");
510     else if (equalIgnoringCase(enabled, "plaintext-only"))
511         setAttribute(contenteditableAttr, "plaintext-only");
512     else if (equalIgnoringCase(enabled, "inherit"))
513         removeAttribute(contenteditableAttr);
514     else
515         exceptionState.throwDOMException(SyntaxError, "The value provided ('" + enabled + "') is not one of 'true', 'false', 'plaintext-only', or 'inherit'.");
516 }
517
518 bool HTMLElement::draggable() const
519 {
520     return equalIgnoringCase(getAttribute(draggableAttr), "true");
521 }
522
523 void HTMLElement::setDraggable(bool value)
524 {
525     setAttribute(draggableAttr, value ? "true" : "false");
526 }
527
528 bool HTMLElement::spellcheck() const
529 {
530     return isSpellCheckingEnabled();
531 }
532
533 void HTMLElement::setSpellcheck(bool enable)
534 {
535     setAttribute(spellcheckAttr, enable ? "true" : "false");
536 }
537
538
539 void HTMLElement::click()
540 {
541     dispatchSimulatedClick(0, SendNoEvents);
542 }
543
544 void HTMLElement::accessKeyAction(bool sendMouseEvents)
545 {
546     dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
547 }
548
549 String HTMLElement::title() const
550 {
551     return fastGetAttribute(titleAttr);
552 }
553
554 short HTMLElement::tabIndex() const
555 {
556     if (supportsFocus())
557         return Element::tabIndex();
558     return -1;
559 }
560
561 TranslateAttributeMode HTMLElement::translateAttributeMode() const
562 {
563     const AtomicString& value = getAttribute(translateAttr);
564
565     if (value == nullAtom)
566         return TranslateAttributeInherit;
567     if (equalIgnoringCase(value, "yes") || equalIgnoringCase(value, ""))
568         return TranslateAttributeYes;
569     if (equalIgnoringCase(value, "no"))
570         return TranslateAttributeNo;
571
572     return TranslateAttributeInherit;
573 }
574
575 bool HTMLElement::translate() const
576 {
577     for (const HTMLElement* element = this; element; element = Traversal<HTMLElement>::firstAncestor(*element)) {
578         TranslateAttributeMode mode = element->translateAttributeMode();
579         if (mode != TranslateAttributeInherit) {
580             ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
581             return mode == TranslateAttributeYes;
582         }
583     }
584
585     // Default on the root element is translate=yes.
586     return true;
587 }
588
589 void HTMLElement::setTranslate(bool enable)
590 {
591     setAttribute(translateAttr, enable ? "yes" : "no");
592 }
593
594 // Returns the conforming 'dir' value associated with the state the attribute is in (in its canonical case), if any,
595 // or the empty string if the attribute is in a state that has no associated keyword value or if the attribute is
596 // not in a defined state (e.g. the attribute is missing and there is no missing value default).
597 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#limited-to-only-known-values
598 static inline const AtomicString& toValidDirValue(const AtomicString& value)
599 {
600     DEFINE_STATIC_LOCAL(const AtomicString, ltrValue, ("ltr", AtomicString::ConstructFromLiteral));
601     DEFINE_STATIC_LOCAL(const AtomicString, rtlValue, ("rtl", AtomicString::ConstructFromLiteral));
602     DEFINE_STATIC_LOCAL(const AtomicString, autoValue, ("auto", AtomicString::ConstructFromLiteral));
603
604     if (equalIgnoringCase(value, ltrValue))
605         return ltrValue;
606     if (equalIgnoringCase(value, rtlValue))
607         return rtlValue;
608     if (equalIgnoringCase(value, autoValue))
609         return autoValue;
610     return nullAtom;
611 }
612
613 const AtomicString& HTMLElement::dir()
614 {
615     return toValidDirValue(fastGetAttribute(dirAttr));
616 }
617
618 void HTMLElement::setDir(const AtomicString& value)
619 {
620     setAttribute(dirAttr, value);
621 }
622
623 HTMLFormElement* HTMLElement::findFormAncestor() const
624 {
625     return Traversal<HTMLFormElement>::firstAncestor(*this);
626 }
627
628 static inline bool elementAffectsDirectionality(const Node* node)
629 {
630     return node->isHTMLElement() && (isHTMLBDIElement(*node) || toHTMLElement(node)->hasAttribute(dirAttr));
631 }
632
633 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
634 {
635     firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
636
637     Node* node = firstNode->firstChild();
638
639     while (node) {
640         if (node->selfOrAncestorHasDirAutoAttribute() == flag)
641             return;
642
643         if (elementAffectsDirectionality(node)) {
644             if (node == lastNode)
645                 return;
646             node = NodeTraversal::nextSkippingChildren(*node, firstNode);
647             continue;
648         }
649         node->setSelfOrAncestorHasDirAutoAttribute(flag);
650         if (node == lastNode)
651             return;
652         node = NodeTraversal::next(*node, firstNode);
653     }
654 }
655
656 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
657 {
658     Element::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
659     adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
660 }
661
662 bool HTMLElement::hasDirectionAuto() const
663 {
664     const AtomicString& direction = fastGetAttribute(dirAttr);
665     return (isHTMLBDIElement(*this) && direction == nullAtom) || equalIgnoringCase(direction, "auto");
666 }
667
668 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
669 {
670     if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
671         isAuto = false;
672         return LTR;
673     }
674
675     isAuto = true;
676     return directionality();
677 }
678
679 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
680 {
681     if (isHTMLInputElement(*this)) {
682         HTMLInputElement* inputElement = toHTMLInputElement(const_cast<HTMLElement*>(this));
683         bool hasStrongDirectionality;
684         TextDirection textDirection = determineDirectionality(inputElement->value(), hasStrongDirectionality);
685         if (strongDirectionalityTextNode)
686             *strongDirectionalityTextNode = hasStrongDirectionality ? inputElement : 0;
687         return textDirection;
688     }
689
690     Node* node = firstChild();
691     while (node) {
692         // Skip bdi, script, style and text form controls.
693         if (equalIgnoringCase(node->nodeName(), "bdi") || isHTMLScriptElement(*node) || isHTMLStyleElement(*node)
694             || (node->isElementNode() && toElement(node)->isTextFormControl())) {
695             node = NodeTraversal::nextSkippingChildren(*node, this);
696             continue;
697         }
698
699         // Skip elements with valid dir attribute
700         if (node->isElementNode()) {
701             AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
702             if (isValidDirAttribute(dirAttributeValue)) {
703                 node = NodeTraversal::nextSkippingChildren(*node, this);
704                 continue;
705             }
706         }
707
708         if (node->isTextNode()) {
709             bool hasStrongDirectionality;
710             TextDirection textDirection = determineDirectionality(node->textContent(true), hasStrongDirectionality);
711             if (hasStrongDirectionality) {
712                 if (strongDirectionalityTextNode)
713                     *strongDirectionalityTextNode = node;
714                 return textDirection;
715             }
716         }
717         node = NodeTraversal::next(*node, this);
718     }
719     if (strongDirectionalityTextNode)
720         *strongDirectionalityTextNode = 0;
721     return LTR;
722 }
723
724 void HTMLElement::dirAttributeChanged(const AtomicString& value)
725 {
726     Element* parent = parentElement();
727
728     if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
729         toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
730
731     if (equalIgnoringCase(value, "auto"))
732         calculateAndAdjustDirectionality();
733 }
734
735 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
736 {
737     ASSERT(selfOrAncestorHasDirAutoAttribute());
738     Node* strongDirectionalityTextNode;
739     TextDirection textDirection = directionality(&strongDirectionalityTextNode);
740     setHasDirAutoFlagRecursively(child, false);
741     if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
742         Element* elementToAdjust = this;
743         for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
744             if (elementAffectsDirectionality(elementToAdjust)) {
745                 elementToAdjust->setNeedsStyleRecalc(SubtreeStyleChange);
746                 return;
747             }
748         }
749     }
750 }
751
752 void HTMLElement::calculateAndAdjustDirectionality()
753 {
754     Node* strongDirectionalityTextNode;
755     TextDirection textDirection = directionality(&strongDirectionalityTextNode);
756     setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
757     if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
758         setNeedsStyleRecalc(SubtreeStyleChange);
759 }
760
761 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
762 {
763     if (document().renderer() && childCountDelta < 0) {
764         Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
765         for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(*node)) {
766             if (elementAffectsDirectionality(node))
767                 continue;
768
769             setHasDirAutoFlagRecursively(node, false);
770         }
771     }
772
773     if (!selfOrAncestorHasDirAutoAttribute())
774         return;
775
776     Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
777     while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
778         oldMarkedNode = NodeTraversal::nextSkippingChildren(*oldMarkedNode, this);
779     if (oldMarkedNode)
780         setHasDirAutoFlagRecursively(oldMarkedNode, false);
781
782     for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
783         if (elementAffectsDirectionality(elementToAdjust)) {
784             toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
785             return;
786         }
787     }
788 }
789
790 void HTMLElement::addHTMLLengthToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
791 {
792     // FIXME: This function should not spin up the CSS parser, but should instead just figure out the correct
793     // length unit and make the appropriate parsed value.
794
795     // strip attribute garbage..
796     StringImpl* v = value.impl();
797     if (v) {
798         unsigned length = 0;
799
800         while (length < v->length() && (*v)[length] <= ' ')
801             length++;
802
803         for (; length < v->length(); length++) {
804             UChar cc = (*v)[length];
805             if (cc > '9')
806                 break;
807             if (cc < '0') {
808                 if (cc == '%' || cc == '*')
809                     length++;
810                 if (cc != '.')
811                     break;
812             }
813         }
814
815         if (length != v->length()) {
816             addPropertyToPresentationAttributeStyle(style, propertyID, v->substring(0, length));
817             return;
818         }
819     }
820
821     addPropertyToPresentationAttributeStyle(style, propertyID, value);
822 }
823
824 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
825 {
826     // Per spec, only look at the first 128 digits of the string.
827     const size_t maxColorLength = 128;
828     // We'll pad the buffer with two extra 0s later, so reserve two more than the max.
829     Vector<char, maxColorLength+2> digitBuffer;
830
831     size_t i = 0;
832     // Skip a leading #.
833     if (colorString[0] == '#')
834         i = 1;
835
836     // Grab the first 128 characters, replacing non-hex characters with 0.
837     // Non-BMP characters are replaced with "00" due to them appearing as two "characters" in the String.
838     for (; i < colorString.length() && digitBuffer.size() < maxColorLength; i++) {
839         if (!isASCIIHexDigit(colorString[i]))
840             digitBuffer.append('0');
841         else
842             digitBuffer.append(colorString[i]);
843     }
844
845     if (!digitBuffer.size())
846         return Color::black;
847
848     // Pad the buffer out to at least the next multiple of three in size.
849     digitBuffer.append('0');
850     digitBuffer.append('0');
851
852     if (digitBuffer.size() < 6)
853         return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
854
855     // Split the digits into three components, then search the last 8 digits of each component.
856     ASSERT(digitBuffer.size() >= 6);
857     size_t componentLength = digitBuffer.size() / 3;
858     size_t componentSearchWindowLength = min<size_t>(componentLength, 8);
859     size_t redIndex = componentLength - componentSearchWindowLength;
860     size_t greenIndex = componentLength * 2 - componentSearchWindowLength;
861     size_t blueIndex = componentLength * 3 - componentSearchWindowLength;
862     // Skip digits until one of them is non-zero, or we've only got two digits left in the component.
863     while (digitBuffer[redIndex] == '0' && digitBuffer[greenIndex] == '0' && digitBuffer[blueIndex] == '0' && (componentLength - redIndex) > 2) {
864         redIndex++;
865         greenIndex++;
866         blueIndex++;
867     }
868     ASSERT(redIndex + 1 < componentLength);
869     ASSERT(greenIndex >= componentLength);
870     ASSERT(greenIndex + 1 < componentLength * 2);
871     ASSERT(blueIndex >= componentLength * 2);
872     ASSERT_WITH_SECURITY_IMPLICATION(blueIndex + 1 < digitBuffer.size());
873
874     int redValue = toASCIIHexValue(digitBuffer[redIndex], digitBuffer[redIndex + 1]);
875     int greenValue = toASCIIHexValue(digitBuffer[greenIndex], digitBuffer[greenIndex + 1]);
876     int blueValue = toASCIIHexValue(digitBuffer[blueIndex], digitBuffer[blueIndex + 1]);
877     return makeRGB(redValue, greenValue, blueValue);
878 }
879
880 // Color parsing that matches HTML's "rules for parsing a legacy color value"
881 void HTMLElement::addHTMLColorToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& attributeValue)
882 {
883     // An empty string doesn't apply a color. (One containing only whitespace does, which is why this check occurs before stripping.)
884     if (attributeValue.isEmpty())
885         return;
886
887     String colorString = attributeValue.stripWhiteSpace();
888
889     // "transparent" doesn't apply a color either.
890     if (equalIgnoringCase(colorString, "transparent"))
891         return;
892
893     // If the string is a named CSS color or a 3/6-digit hex color, use that.
894     Color parsedColor;
895     if (!parsedColor.setFromString(colorString))
896         parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
897
898     style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
899 }
900
901 bool HTMLElement::isInteractiveContent() const
902 {
903     return false;
904 }
905
906 void HTMLElement::defaultEventHandler(Event* event)
907 {
908     if (event->type() == EventTypeNames::keypress && event->isKeyboardEvent()) {
909         handleKeypressEvent(toKeyboardEvent(event));
910         if (event->defaultHandled())
911             return;
912     }
913
914     Element::defaultEventHandler(event);
915 }
916
917 bool HTMLElement::matchesReadOnlyPseudoClass() const
918 {
919     return !matchesReadWritePseudoClass();
920 }
921
922 bool HTMLElement::matchesReadWritePseudoClass() const
923 {
924     if (fastHasAttribute(contenteditableAttr)) {
925         const AtomicString& value = fastGetAttribute(contenteditableAttr);
926
927         if (value.isEmpty() || equalIgnoringCase(value, "true") || equalIgnoringCase(value, "plaintext-only"))
928             return true;
929         if (equalIgnoringCase(value, "false"))
930             return false;
931         // All other values should be treated as "inherit".
932     }
933
934     return parentElement() && parentElement()->rendererIsEditable();
935 }
936
937 void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
938 {
939     if (!document().settings() || !document().settings()->spatialNavigationEnabled() || !supportsFocus())
940         return;
941     // if the element is a text form control (like <input type=text> or <textarea>)
942     // or has contentEditable attribute on, we should enter a space or newline
943     // even in spatial navigation mode instead of handling it as a "click" action.
944     if (isTextFormControl() || isContentEditable())
945         return;
946     int charCode = event->charCode();
947     if (charCode == '\r' || charCode == ' ') {
948         dispatchSimulatedClick(event);
949         event->setDefaultHandled();
950     }
951 }
952
953 } // namespace WebCore
954
955 #ifndef NDEBUG
956
957 // For use in the debugger
958 void dumpInnerHTML(WebCore::HTMLElement*);
959
960 void dumpInnerHTML(WebCore::HTMLElement* element)
961 {
962     printf("%s\n", element->innerHTML().ascii().data());
963 }
964 #endif