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