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.
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.
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.
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.
26 #include "core/html/HTMLElement.h"
28 #include "CSSPropertyNames.h"
29 #include "CSSValueKeywords.h"
30 #include "HTMLNames.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"
60 using namespace HTMLNames;
66 PassRefPtrWillBeRawPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document& document)
68 return adoptRefWillBeRefCountedGarbageCollected(new HTMLElement(tagName, document));
71 String HTMLElement::nodeName() const
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();
81 return Element::nodeName();
84 bool HTMLElement::ieForbidsInsertHTML() const
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))
113 static inline CSSValueID unicodeBidiAttributeForDirAuto(HTMLElement* element)
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;
122 unsigned HTMLElement::parseBorderWidthAttribute(const AtomicString& value) const
124 unsigned borderWidth = 0;
125 if (value.isEmpty() || !parseHTMLNonNegativeInteger(value, borderWidth))
126 return hasLocalName(tableTag) ? 1 : borderWidth;
130 void HTMLElement::applyBorderAttributeToStyle(const AtomicString& value, MutableStylePropertySet* style)
132 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(value), CSSPrimitiveValue::CSS_PX);
133 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
136 void HTMLElement::mapLanguageAttributeToLocale(const AtomicString& value, MutableStylePropertySet* style)
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));
142 // The empty string means the language is explicitly unknown.
143 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
147 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
149 if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
151 return Element::isPresentationAttribute(name);
154 static inline bool isValidDirAttribute(const AtomicString& value)
156 return equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "ltr") || equalIgnoringCase(value, "rtl");
159 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
161 if (name == alignAttr) {
162 if (equalIgnoringCase(value, "middle"))
163 addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
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));
189 if (isValidDirAttribute(value))
190 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
192 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, "ltr");
193 if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
194 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
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);
203 Element::collectStyleForPresentationAttribute(name, value, style);
206 const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName)
208 if (!attrName.namespaceURI().isNull())
211 if (!attrName.localName().startsWith("on", false))
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);
304 return attributeNameToEventNameMap.get(attrName.localName());
307 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
309 if (name == tabindexAttr)
310 return Element::parseAttribute(name, value);
312 if (name == dirAttr) {
313 dirAttributeChanged(value);
315 const AtomicString& eventName = eventNameForAttributeName(name);
316 if (!eventName.isNull())
317 setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
321 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& exceptionState)
323 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
324 unsigned i, length = text.length();
326 for (unsigned start = 0; start < length; ) {
328 // Find next line break.
329 for (i = start; i < length; i++) {
331 if (c == '\r' || c == '\n')
335 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), exceptionState);
336 if (exceptionState.hadException())
339 if (c == '\r' || c == '\n') {
340 fragment->appendChild(HTMLBRElement::create(document()), exceptionState);
341 if (exceptionState.hadException())
343 // Make sure \r\n doesn't result in two line breaks.
344 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
348 start = i + 1; // Character after line break.
354 void HTMLElement::setInnerText(const String& text, ExceptionState& exceptionState)
356 if (ieForbidsInsertHTML()) {
357 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
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.");
368 // FIXME: This doesn't take whitespace collapsing into account at all.
370 if (!text.contains('\n') && !text.contains('\r')) {
371 if (text.isEmpty()) {
375 replaceChildrenWithText(this, text, exceptionState);
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);
388 String textWithConsistentLineBreaks = text;
389 textWithConsistentLineBreaks.replace("\r\n", "\n");
390 textWithConsistentLineBreaks.replace('\r', '\n');
391 replaceChildrenWithText(this, textWithConsistentLineBreaks, exceptionState);
395 // Add text nodes and <br> elements.
396 RefPtr<DocumentFragment> fragment = textToFragment(text, exceptionState);
397 if (!exceptionState.hadException())
398 replaceChildrenWithFragment(this, fragment.release(), exceptionState);
401 void HTMLElement::setOuterText(const String &text, ExceptionState& exceptionState)
403 if (ieForbidsInsertHTML()) {
404 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
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.");
415 ContainerNode* parent = parentNode();
417 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
421 RefPtr<Node> prev = previousSibling();
422 RefPtr<Node> next = nextSibling();
423 RefPtr<Node> newChild;
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);
429 newChild = Text::create(document(), text);
431 // textToFragment might cause mutation events.
432 if (!this || !parentNode())
433 exceptionState.throwDOMException(HierarchyRequestError, "The element has no parent.");
435 if (exceptionState.hadException())
438 parent->replaceChild(newChild.release(), this, exceptionState);
440 RefPtr<Node> node = next ? next->previousSibling() : 0;
441 if (!exceptionState.hadException() && node && node->isTextNode())
442 mergeWithNextTextNode(node.release(), exceptionState);
444 if (!exceptionState.hadException() && prev && prev->isTextNode())
445 mergeWithNextTextNode(prev.release(), exceptionState);
448 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
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;
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;
476 if (floatValue != CSSValueInvalid)
477 addPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, floatValue);
479 if (verticalAlignValue != CSSValueInvalid)
480 addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
483 bool HTMLElement::hasCustomFocusLogic() const
488 String HTMLElement::contentEditable() const
490 const AtomicString& value = fastGetAttribute(contenteditableAttr);
494 if (value.isEmpty() || equalIgnoringCase(value, "true"))
496 if (equalIgnoringCase(value, "false"))
498 if (equalIgnoringCase(value, "plaintext-only"))
499 return "plaintext-only";
504 void HTMLElement::setContentEditable(const String& enabled, ExceptionState& exceptionState)
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);
515 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + enabled + "') is not one of 'true', 'false', 'plaintext-only', or 'inherit'.");
518 bool HTMLElement::draggable() const
520 return equalIgnoringCase(getAttribute(draggableAttr), "true");
523 void HTMLElement::setDraggable(bool value)
525 setAttribute(draggableAttr, value ? "true" : "false");
528 bool HTMLElement::spellcheck() const
530 return isSpellCheckingEnabled();
533 void HTMLElement::setSpellcheck(bool enable)
535 setAttribute(spellcheckAttr, enable ? "true" : "false");
539 void HTMLElement::click()
541 dispatchSimulatedClick(0, SendNoEvents);
544 void HTMLElement::accessKeyAction(bool sendMouseEvents)
546 dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
549 String HTMLElement::title() const
551 return fastGetAttribute(titleAttr);
554 short HTMLElement::tabIndex() const
557 return Element::tabIndex();
561 TranslateAttributeMode HTMLElement::translateAttributeMode() const
563 const AtomicString& value = getAttribute(translateAttr);
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;
572 return TranslateAttributeInherit;
575 bool HTMLElement::translate() const
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;
585 // Default on the root element is translate=yes.
589 void HTMLElement::setTranslate(bool enable)
591 setAttribute(translateAttr, enable ? "yes" : "no");
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)
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));
604 if (equalIgnoringCase(value, ltrValue))
606 if (equalIgnoringCase(value, rtlValue))
608 if (equalIgnoringCase(value, autoValue))
613 const AtomicString& HTMLElement::dir()
615 return toValidDirValue(fastGetAttribute(dirAttr));
618 void HTMLElement::setDir(const AtomicString& value)
620 setAttribute(dirAttr, value);
623 HTMLFormElement* HTMLElement::findFormAncestor() const
625 return Traversal<HTMLFormElement>::firstAncestor(*this);
628 static inline bool elementAffectsDirectionality(const Node* node)
630 return node->isHTMLElement() && (isHTMLBDIElement(*node) || toHTMLElement(node)->hasAttribute(dirAttr));
633 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
635 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
637 Node* node = firstNode->firstChild();
640 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
643 if (elementAffectsDirectionality(node)) {
644 if (node == lastNode)
646 node = NodeTraversal::nextSkippingChildren(*node, firstNode);
649 node->setSelfOrAncestorHasDirAutoAttribute(flag);
650 if (node == lastNode)
652 node = NodeTraversal::next(*node, firstNode);
656 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
658 Element::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
659 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
662 bool HTMLElement::hasDirectionAuto() const
664 const AtomicString& direction = fastGetAttribute(dirAttr);
665 return (isHTMLBDIElement(*this) && direction == nullAtom) || equalIgnoringCase(direction, "auto");
668 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
670 if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
676 return directionality();
679 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
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;
690 Node* node = firstChild();
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);
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);
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;
717 node = NodeTraversal::next(*node, this);
719 if (strongDirectionalityTextNode)
720 *strongDirectionalityTextNode = 0;
724 void HTMLElement::dirAttributeChanged(const AtomicString& value)
726 Element* parent = parentElement();
728 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
729 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
731 if (equalIgnoringCase(value, "auto"))
732 calculateAndAdjustDirectionality();
735 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
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);
752 void HTMLElement::calculateAndAdjustDirectionality()
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);
761 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
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))
769 setHasDirAutoFlagRecursively(node, false);
773 if (!selfOrAncestorHasDirAutoAttribute())
776 Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
777 while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
778 oldMarkedNode = NodeTraversal::nextSkippingChildren(*oldMarkedNode, this);
780 setHasDirAutoFlagRecursively(oldMarkedNode, false);
782 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
783 if (elementAffectsDirectionality(elementToAdjust)) {
784 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
790 void HTMLElement::addHTMLLengthToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
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.
795 // strip attribute garbage..
796 StringImpl* v = value.impl();
800 while (length < v->length() && (*v)[length] <= ' ')
803 for (; length < v->length(); length++) {
804 UChar cc = (*v)[length];
808 if (cc == '%' || cc == '*')
815 if (length != v->length()) {
816 addPropertyToPresentationAttributeStyle(style, propertyID, v->substring(0, length));
821 addPropertyToPresentationAttributeStyle(style, propertyID, value);
824 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
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;
833 if (colorString[0] == '#')
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');
842 digitBuffer.append(colorString[i]);
845 if (!digitBuffer.size())
848 // Pad the buffer out to at least the next multiple of three in size.
849 digitBuffer.append('0');
850 digitBuffer.append('0');
852 if (digitBuffer.size() < 6)
853 return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
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) {
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());
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);
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)
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())
887 String colorString = attributeValue.stripWhiteSpace();
889 // "transparent" doesn't apply a color either.
890 if (equalIgnoringCase(colorString, "transparent"))
893 // If the string is a named CSS color or a 3/6-digit hex color, use that.
895 if (!parsedColor.setFromString(colorString))
896 parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
898 style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
901 bool HTMLElement::isInteractiveContent() const
906 void HTMLElement::defaultEventHandler(Event* event)
908 if (event->type() == EventTypeNames::keypress && event->isKeyboardEvent()) {
909 handleKeypressEvent(toKeyboardEvent(event));
910 if (event->defaultHandled())
914 Element::defaultEventHandler(event);
917 bool HTMLElement::matchesReadOnlyPseudoClass() const
919 return !matchesReadWritePseudoClass();
922 bool HTMLElement::matchesReadWritePseudoClass() const
924 if (fastHasAttribute(contenteditableAttr)) {
925 const AtomicString& value = fastGetAttribute(contenteditableAttr);
927 if (value.isEmpty() || equalIgnoringCase(value, "true") || equalIgnoringCase(value, "plaintext-only"))
929 if (equalIgnoringCase(value, "false"))
931 // All other values should be treated as "inherit".
934 return parentElement() && parentElement()->rendererIsEditable();
937 void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
939 if (!document().settings() || !document().settings()->spatialNavigationEnabled() || !supportsFocus())
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())
946 int charCode = event->charCode();
947 if (charCode == '\r' || charCode == ' ') {
948 dispatchSimulatedClick(event);
949 event->setDefaultHandled();
953 } // namespace WebCore
957 // For use in the debugger
958 void dumpInnerHTML(WebCore::HTMLElement*);
960 void dumpInnerHTML(WebCore::HTMLElement* element)
962 printf("%s\n", element->innerHTML().ascii().data());