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 "HTMLElement.h"
28 #include "Attribute.h"
29 #include "CSSParser.h"
30 #include "CSSPropertyNames.h"
31 #include "CSSValueKeywords.h"
32 #include "CSSValuePool.h"
33 #include "ChildListMutationScope.h"
34 #include "DocumentFragment.h"
36 #include "EventListener.h"
37 #include "EventNames.h"
38 #include "ExceptionCode.h"
40 #include "HTMLBRElement.h"
41 #include "HTMLCollection.h"
42 #include "HTMLDocument.h"
43 #include "HTMLElementFactory.h"
44 #include "HTMLFormElement.h"
45 #include "HTMLNames.h"
46 #include "HTMLParserIdioms.h"
47 #include "HTMLTextFormControlElement.h"
48 #include "RenderWordBreak.h"
49 #include "ScriptEventListener.h"
52 #include "TextIterator.h"
55 #include <wtf/StdLibExtras.h>
56 #include <wtf/text/CString.h>
59 #include "HTMLPropertiesCollection.h"
60 #include "MicroDataItemValue.h"
65 using namespace HTMLNames;
71 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
73 return adoptRef(new HTMLElement(tagName, document));
76 String HTMLElement::nodeName() const
78 // FIXME: Would be nice to have an atomicstring lookup based off uppercase
79 // chars that does not have to copy the string on a hit in the hash.
80 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
81 if (document()->isHTMLDocument() && !tagQName().hasPrefix())
82 return tagQName().localNameUpper();
83 return Element::nodeName();
86 bool HTMLElement::ieForbidsInsertHTML() const
88 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
89 // and createContextualFragment on these tags. We have no tests to
90 // verify this however, so this list could be totally wrong.
91 // This list was moved from the previous endTagRequirement() implementation.
92 // This is also called from editing and assumed to be the list of tags
93 // for which no end tag should be serialized. It's unclear if the list for
94 // IE compat and the list for serialization sanity are the same.
95 if (hasLocalName(areaTag)
96 || hasLocalName(baseTag)
97 || hasLocalName(basefontTag)
98 || hasLocalName(brTag)
99 || hasLocalName(colTag)
100 || hasLocalName(embedTag)
101 || hasLocalName(frameTag)
102 || hasLocalName(hrTag)
103 || hasLocalName(imageTag)
104 || hasLocalName(imgTag)
105 || hasLocalName(inputTag)
106 || hasLocalName(isindexTag)
107 || hasLocalName(linkTag)
108 || hasLocalName(metaTag)
109 || hasLocalName(paramTag)
110 || hasLocalName(sourceTag)
111 || hasLocalName(wbrTag))
113 // FIXME: I'm not sure why dashboard mode would want to change the
114 // serialization of <canvas>, that seems like a bad idea.
115 #if ENABLE(DASHBOARD_SUPPORT)
116 if (hasLocalName(canvasTag)) {
117 Settings* settings = document()->settings();
118 if (settings && settings->usesDashboardBackwardCompatibilityMode())
125 static inline int unicodeBidiAttributeForDirAuto(HTMLElement* element)
127 if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
128 return CSSValueWebkitPlaintext;
129 // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
130 // See https://bugs.webkit.org/show_bug.cgi?id=73164.
131 return CSSValueWebkitIsolate;
134 static unsigned parseBorderWidthAttribute(const Attribute& attribute)
136 ASSERT(attribute.name() == borderAttr);
137 unsigned borderWidth = 0;
138 if (!attribute.isEmpty())
139 parseHTMLNonNegativeInteger(attribute.value(), borderWidth);
143 void HTMLElement::applyBorderAttributeToStyle(const Attribute& attribute, StylePropertySet* style)
145 addPropertyToAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(attribute), CSSPrimitiveValue::CSS_PX);
146 addPropertyToAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
149 void HTMLElement::mapLanguageAttributeToLocale(const Attribute& attribute, StylePropertySet* style)
151 ASSERT((attribute.name() == langAttr || attribute.name().matches(XMLNames::langAttr)));
152 if (!attribute.isEmpty()) {
153 // Have to quote so the locale id is treated as a string instead of as a CSS keyword.
154 addPropertyToAttributeStyle(style, CSSPropertyWebkitLocale, quoteCSSString(attribute.value()));
156 // The empty string means the language is explicitly unknown.
157 addPropertyToAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
161 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
163 if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
165 return StyledElement::isPresentationAttribute(name);
168 void HTMLElement::collectStyleForAttribute(const Attribute& attribute, StylePropertySet* style)
170 if (attribute.name() == alignAttr) {
171 if (equalIgnoringCase(attribute.value(), "middle"))
172 addPropertyToAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
174 addPropertyToAttributeStyle(style, CSSPropertyTextAlign, attribute.value());
175 } else if (attribute.name() == contenteditableAttr) {
176 if (attribute.isEmpty() || equalIgnoringCase(attribute.value(), "true")) {
177 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
178 addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
179 addPropertyToAttributeStyle(style, CSSPropertyWebkitNbspMode, CSSValueSpace);
180 addPropertyToAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
181 } else if (equalIgnoringCase(attribute.value(), "plaintext-only")) {
182 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
183 addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
184 addPropertyToAttributeStyle(style, CSSPropertyWebkitNbspMode, CSSValueSpace);
185 addPropertyToAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
186 } else if (equalIgnoringCase(attribute.value(), "false"))
187 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
188 } else if (attribute.name() == hiddenAttr) {
189 addPropertyToAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
190 } else if (attribute.name() == draggableAttr) {
191 if (equalIgnoringCase(attribute.value(), "true")) {
192 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
193 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
194 } else if (equalIgnoringCase(attribute.value(), "false"))
195 addPropertyToAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
196 } else if (attribute.name() == dirAttr) {
197 if (equalIgnoringCase(attribute.value(), "auto"))
198 addPropertyToAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
200 addPropertyToAttributeStyle(style, CSSPropertyDirection, attribute.value());
201 if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
202 addPropertyToAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
204 } else if (attribute.name().matches(XMLNames::langAttr)) {
205 mapLanguageAttributeToLocale(attribute, style);
206 } else if (attribute.name() == langAttr) {
207 // xml:lang has a higher priority than lang.
208 if (!fastHasAttribute(XMLNames::langAttr))
209 mapLanguageAttributeToLocale(attribute, style);
211 StyledElement::collectStyleForAttribute(attribute, style);
214 void HTMLElement::parseAttribute(const Attribute& attribute)
216 if (isIdAttributeName(attribute.name()) || attribute.name() == classAttr || attribute.name() == styleAttr)
217 return StyledElement::parseAttribute(attribute);
219 if (attribute.name() == dirAttr)
220 dirAttributeChanged(attribute);
221 else if (attribute.name() == tabindexAttr) {
223 if (attribute.isEmpty())
224 clearTabIndexExplicitly();
225 else if (parseHTMLInteger(attribute.value(), tabindex)) {
226 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
227 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
229 #if ENABLE(MICRODATA)
230 } else if (attribute.name() == itempropAttr) {
231 setItemProp(attribute.value());
232 } else if (attribute.name() == itemrefAttr) {
233 setItemRef(attribute.value());
234 } else if (attribute.name() == itemtypeAttr) {
235 setItemType(attribute.value());
239 else if (attribute.name() == onclickAttr) {
240 setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attribute));
241 } else if (attribute.name() == oncontextmenuAttr) {
242 setAttributeEventListener(eventNames().contextmenuEvent, createAttributeEventListener(this, attribute));
243 } else if (attribute.name() == ondblclickAttr) {
244 setAttributeEventListener(eventNames().dblclickEvent, createAttributeEventListener(this, attribute));
245 } else if (attribute.name() == onmousedownAttr) {
246 setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, attribute));
247 } else if (attribute.name() == onmousemoveAttr) {
248 setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, attribute));
249 } else if (attribute.name() == onmouseoutAttr) {
250 setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, attribute));
251 } else if (attribute.name() == onmouseoverAttr) {
252 setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, attribute));
253 } else if (attribute.name() == onmouseupAttr) {
254 setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, attribute));
255 } else if (attribute.name() == onmousewheelAttr) {
256 setAttributeEventListener(eventNames().mousewheelEvent, createAttributeEventListener(this, attribute));
257 } else if (attribute.name() == onfocusAttr) {
258 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attribute));
259 } else if (attribute.name() == onfocusinAttr) {
260 setAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(this, attribute));
261 } else if (attribute.name() == onfocusoutAttr) {
262 setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, attribute));
263 } else if (attribute.name() == onblurAttr) {
264 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attribute));
265 } else if (attribute.name() == onkeydownAttr) {
266 setAttributeEventListener(eventNames().keydownEvent, createAttributeEventListener(this, attribute));
267 } else if (attribute.name() == onkeypressAttr) {
268 setAttributeEventListener(eventNames().keypressEvent, createAttributeEventListener(this, attribute));
269 } else if (attribute.name() == onkeyupAttr) {
270 setAttributeEventListener(eventNames().keyupEvent, createAttributeEventListener(this, attribute));
271 } else if (attribute.name() == onscrollAttr) {
272 setAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(this, attribute));
273 } else if (attribute.name() == onbeforecutAttr) {
274 setAttributeEventListener(eventNames().beforecutEvent, createAttributeEventListener(this, attribute));
275 } else if (attribute.name() == oncutAttr) {
276 setAttributeEventListener(eventNames().cutEvent, createAttributeEventListener(this, attribute));
277 } else if (attribute.name() == onbeforecopyAttr) {
278 setAttributeEventListener(eventNames().beforecopyEvent, createAttributeEventListener(this, attribute));
279 } else if (attribute.name() == oncopyAttr) {
280 setAttributeEventListener(eventNames().copyEvent, createAttributeEventListener(this, attribute));
281 } else if (attribute.name() == onbeforepasteAttr) {
282 setAttributeEventListener(eventNames().beforepasteEvent, createAttributeEventListener(this, attribute));
283 } else if (attribute.name() == onpasteAttr) {
284 setAttributeEventListener(eventNames().pasteEvent, createAttributeEventListener(this, attribute));
285 } else if (attribute.name() == ondragenterAttr) {
286 setAttributeEventListener(eventNames().dragenterEvent, createAttributeEventListener(this, attribute));
287 } else if (attribute.name() == ondragoverAttr) {
288 setAttributeEventListener(eventNames().dragoverEvent, createAttributeEventListener(this, attribute));
289 } else if (attribute.name() == ondragleaveAttr) {
290 setAttributeEventListener(eventNames().dragleaveEvent, createAttributeEventListener(this, attribute));
291 } else if (attribute.name() == ondropAttr) {
292 setAttributeEventListener(eventNames().dropEvent, createAttributeEventListener(this, attribute));
293 } else if (attribute.name() == ondragstartAttr) {
294 setAttributeEventListener(eventNames().dragstartEvent, createAttributeEventListener(this, attribute));
295 } else if (attribute.name() == ondragAttr) {
296 setAttributeEventListener(eventNames().dragEvent, createAttributeEventListener(this, attribute));
297 } else if (attribute.name() == ondragendAttr) {
298 setAttributeEventListener(eventNames().dragendEvent, createAttributeEventListener(this, attribute));
299 } else if (attribute.name() == onselectstartAttr) {
300 setAttributeEventListener(eventNames().selectstartEvent, createAttributeEventListener(this, attribute));
301 } else if (attribute.name() == onsubmitAttr) {
302 setAttributeEventListener(eventNames().submitEvent, createAttributeEventListener(this, attribute));
303 } else if (attribute.name() == onerrorAttr) {
304 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attribute));
305 } else if (attribute.name() == onwebkitanimationstartAttr) {
306 setAttributeEventListener(eventNames().webkitAnimationStartEvent, createAttributeEventListener(this, attribute));
307 } else if (attribute.name() == onwebkitanimationiterationAttr) {
308 setAttributeEventListener(eventNames().webkitAnimationIterationEvent, createAttributeEventListener(this, attribute));
309 } else if (attribute.name() == onwebkitanimationendAttr) {
310 setAttributeEventListener(eventNames().webkitAnimationEndEvent, createAttributeEventListener(this, attribute));
311 } else if (attribute.name() == onwebkittransitionendAttr) {
312 setAttributeEventListener(eventNames().webkitTransitionEndEvent, createAttributeEventListener(this, attribute));
313 } else if (attribute.name() == oninputAttr) {
314 setAttributeEventListener(eventNames().inputEvent, createAttributeEventListener(this, attribute));
315 } else if (attribute.name() == oninvalidAttr) {
316 setAttributeEventListener(eventNames().invalidEvent, createAttributeEventListener(this, attribute));
317 } else if (attribute.name() == ontouchstartAttr) {
318 setAttributeEventListener(eventNames().touchstartEvent, createAttributeEventListener(this, attribute));
319 } else if (attribute.name() == ontouchmoveAttr) {
320 setAttributeEventListener(eventNames().touchmoveEvent, createAttributeEventListener(this, attribute));
321 } else if (attribute.name() == ontouchendAttr) {
322 setAttributeEventListener(eventNames().touchendEvent, createAttributeEventListener(this, attribute));
323 } else if (attribute.name() == ontouchcancelAttr) {
324 setAttributeEventListener(eventNames().touchcancelEvent, createAttributeEventListener(this, attribute));
325 #if ENABLE(FULLSCREEN_API)
326 } else if (attribute.name() == onwebkitfullscreenchangeAttr) {
327 setAttributeEventListener(eventNames().webkitfullscreenchangeEvent, createAttributeEventListener(this, attribute));
328 } else if (attribute.name() == onwebkitfullscreenerrorAttr) {
329 setAttributeEventListener(eventNames().webkitfullscreenerrorEvent, createAttributeEventListener(this, attribute));
334 String HTMLElement::innerHTML() const
336 return createMarkup(this, ChildrenOnly);
339 String HTMLElement::outerHTML() const
341 return createMarkup(this);
344 void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec)
346 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, ec))
347 replaceChildrenWithFragment(this, fragment.release(), ec);
350 static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionCode& ec)
352 ASSERT(node && node->isTextNode());
353 Node* next = node->nextSibling();
354 if (!next || !next->isTextNode())
357 RefPtr<Text> textNode = toText(node.get());
358 RefPtr<Text> textNext = toText(next);
359 textNode->appendData(textNext->data(), ec);
362 if (textNext->parentNode()) // Might have been removed by mutation event.
363 textNext->remove(ec);
366 void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
368 Node* p = parentNode();
369 if (!p || !p->isHTMLElement()) {
370 ec = NO_MODIFICATION_ALLOWED_ERR;
373 RefPtr<HTMLElement> parent = toHTMLElement(p);
374 RefPtr<Node> prev = previousSibling();
375 RefPtr<Node> next = nextSibling();
377 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, ec);
381 parent->replaceChild(fragment.release(), this, ec);
382 RefPtr<Node> node = next ? next->previousSibling() : 0;
383 if (!ec && node && node->isTextNode())
384 mergeWithNextTextNode(node.release(), ec);
386 if (!ec && prev && prev->isTextNode())
387 mergeWithNextTextNode(prev.release(), ec);
390 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionCode& ec)
392 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
393 unsigned int i, length = text.length();
395 for (unsigned int start = 0; start < length; ) {
397 // Find next line break.
398 for (i = start; i < length; i++) {
400 if (c == '\r' || c == '\n')
404 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), ec);
408 if (c == '\r' || c == '\n') {
409 fragment->appendChild(HTMLBRElement::create(document()), ec);
412 // Make sure \r\n doesn't result in two line breaks.
413 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
417 start = i + 1; // Character after line break.
423 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
425 if (ieForbidsInsertHTML()) {
426 ec = NO_MODIFICATION_ALLOWED_ERR;
429 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
430 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
431 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
432 hasLocalName(trTag)) {
433 ec = NO_MODIFICATION_ALLOWED_ERR;
437 // FIXME: This doesn't take whitespace collapsing into account at all.
439 if (!text.contains('\n') && !text.contains('\r')) {
440 if (text.isEmpty()) {
444 replaceChildrenWithText(this, text, ec);
448 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
449 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
450 // For example, for the contents of textarea elements that are display:none?
451 RenderObject* r = renderer();
452 if (r && r->style()->preserveNewline()) {
453 if (!text.contains('\r')) {
454 replaceChildrenWithText(this, text, ec);
457 String textWithConsistentLineBreaks = text;
458 textWithConsistentLineBreaks.replace("\r\n", "\n");
459 textWithConsistentLineBreaks.replace('\r', '\n');
460 replaceChildrenWithText(this, textWithConsistentLineBreaks, ec);
464 // Add text nodes and <br> elements.
466 RefPtr<DocumentFragment> fragment = textToFragment(text, ec);
468 replaceChildrenWithFragment(this, fragment.release(), ec);
471 void HTMLElement::setOuterText(const String &text, ExceptionCode& ec)
473 if (ieForbidsInsertHTML()) {
474 ec = NO_MODIFICATION_ALLOWED_ERR;
477 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
478 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
479 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
480 hasLocalName(trTag)) {
481 ec = NO_MODIFICATION_ALLOWED_ERR;
485 ContainerNode* parent = parentNode();
487 ec = NO_MODIFICATION_ALLOWED_ERR;
491 RefPtr<Node> prev = previousSibling();
492 RefPtr<Node> next = nextSibling();
493 RefPtr<Node> newChild;
496 // Convert text to fragment with <br> tags instead of linebreaks if needed.
497 if (text.contains('\r') || text.contains('\n'))
498 newChild = textToFragment(text, ec);
500 newChild = Text::create(document(), text);
502 if (!this || !parentNode())
503 ec = HIERARCHY_REQUEST_ERR;
506 parent->replaceChild(newChild.release(), this, ec);
508 RefPtr<Node> node = next ? next->previousSibling() : 0;
509 if (!ec && node && node->isTextNode())
510 mergeWithNextTextNode(node.release(), ec);
512 if (!ec && prev && prev->isTextNode())
513 mergeWithNextTextNode(prev.release(), ec);
516 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionCode& ec)
518 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
519 // a document fragment is created and the elements appended in the correct order. This document
520 // fragment isn't returned anywhere.
522 // This is impossible for us to implement as the DOM tree does not allow for such structures,
523 // Opera also appears to disallow such usage.
525 if (equalIgnoringCase(where, "beforeBegin")) {
526 ContainerNode* parent = this->parentNode();
527 return (parent && parent->insertBefore(newChild, this, ec)) ? newChild : 0;
530 if (equalIgnoringCase(where, "afterBegin"))
531 return insertBefore(newChild, firstChild(), ec) ? newChild : 0;
533 if (equalIgnoringCase(where, "beforeEnd"))
534 return appendChild(newChild, ec) ? newChild : 0;
536 if (equalIgnoringCase(where, "afterEnd")) {
537 ContainerNode* parent = this->parentNode();
538 return (parent && parent->insertBefore(newChild, nextSibling(), ec)) ? newChild : 0;
541 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
542 ec = NOT_SUPPORTED_ERR;
546 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
549 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
550 ec = TYPE_MISMATCH_ERR;
554 Node* returnValue = insertAdjacent(where, newChild, ec);
555 ASSERT(!returnValue || returnValue->isElementNode());
556 return static_cast<Element*>(returnValue);
559 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
560 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionCode& ec)
562 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
563 ContainerNode* parent = element->parentNode();
564 if (parent && !parent->isElementNode()) {
565 ec = NO_MODIFICATION_ALLOWED_ERR;
568 ASSERT(!parent || parent->isElementNode());
569 return static_cast<Element*>(parent);
571 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
577 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec)
579 Element* contextElement = contextElementForInsertion(where, this, ec);
582 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, ec);
585 insertAdjacent(where, fragment.get(), ec);
588 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
590 RefPtr<Text> textNode = document()->createTextNode(text);
591 insertAdjacent(where, textNode.get(), ec);
594 void HTMLElement::applyAlignmentAttributeToStyle(const Attribute& attribute, StylePropertySet* style)
596 // Vertical alignment with respect to the current baseline of the text
597 // right or left means floating images.
598 int floatValue = CSSValueInvalid;
599 int verticalAlignValue = CSSValueInvalid;
601 const AtomicString& alignment = attribute.value();
602 if (equalIgnoringCase(alignment, "absmiddle"))
603 verticalAlignValue = CSSValueMiddle;
604 else if (equalIgnoringCase(alignment, "absbottom"))
605 verticalAlignValue = CSSValueBottom;
606 else if (equalIgnoringCase(alignment, "left")) {
607 floatValue = CSSValueLeft;
608 verticalAlignValue = CSSValueTop;
609 } else if (equalIgnoringCase(alignment, "right")) {
610 floatValue = CSSValueRight;
611 verticalAlignValue = CSSValueTop;
612 } else if (equalIgnoringCase(alignment, "top"))
613 verticalAlignValue = CSSValueTop;
614 else if (equalIgnoringCase(alignment, "middle"))
615 verticalAlignValue = CSSValueWebkitBaselineMiddle;
616 else if (equalIgnoringCase(alignment, "center"))
617 verticalAlignValue = CSSValueMiddle;
618 else if (equalIgnoringCase(alignment, "bottom"))
619 verticalAlignValue = CSSValueBaseline;
620 else if (equalIgnoringCase(alignment, "texttop"))
621 verticalAlignValue = CSSValueTextTop;
623 if (floatValue != CSSValueInvalid)
624 addPropertyToAttributeStyle(style, CSSPropertyFloat, floatValue);
626 if (verticalAlignValue != CSSValueInvalid)
627 addPropertyToAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
630 bool HTMLElement::supportsFocus() const
632 return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable());
635 String HTMLElement::contentEditable() const
637 const AtomicString& value = fastGetAttribute(contenteditableAttr);
641 if (value.isEmpty() || equalIgnoringCase(value, "true"))
643 if (equalIgnoringCase(value, "false"))
645 if (equalIgnoringCase(value, "plaintext-only"))
646 return "plaintext-only";
651 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
653 if (equalIgnoringCase(enabled, "true"))
654 setAttribute(contenteditableAttr, "true");
655 else if (equalIgnoringCase(enabled, "false"))
656 setAttribute(contenteditableAttr, "false");
657 else if (equalIgnoringCase(enabled, "plaintext-only"))
658 setAttribute(contenteditableAttr, "plaintext-only");
659 else if (equalIgnoringCase(enabled, "inherit"))
660 removeAttribute(contenteditableAttr);
665 bool HTMLElement::draggable() const
667 return equalIgnoringCase(getAttribute(draggableAttr), "true");
670 void HTMLElement::setDraggable(bool value)
672 setAttribute(draggableAttr, value ? "true" : "false");
675 bool HTMLElement::spellcheck() const
677 return isSpellCheckingEnabled();
680 void HTMLElement::setSpellcheck(bool enable)
682 setAttribute(spellcheckAttr, enable ? "true" : "false");
686 void HTMLElement::click()
688 dispatchSimulatedClick(0, false, false);
691 void HTMLElement::accessKeyAction(bool sendMouseEvents)
693 dispatchSimulatedClick(0, sendMouseEvents);
696 String HTMLElement::title() const
698 return getAttribute(titleAttr);
701 short HTMLElement::tabIndex() const
704 return Element::tabIndex();
708 void HTMLElement::setTabIndex(int value)
710 setAttribute(tabindexAttr, String::number(value));
713 TranslateAttributeMode HTMLElement::translateAttributeMode() const
715 const AtomicString& value = getAttribute(translateAttr);
717 if (value == nullAtom)
718 return TranslateAttributeInherit;
719 if (equalIgnoringCase(value, "yes") || equalIgnoringCase(value, ""))
720 return TranslateAttributeYes;
721 if (equalIgnoringCase(value, "no"))
722 return TranslateAttributeNo;
724 return TranslateAttributeInherit;
727 bool HTMLElement::translate() const
729 for (const Node* n = this; n; n = n->parentNode()) {
730 if (n->isHTMLElement()) {
731 TranslateAttributeMode mode = static_cast<const HTMLElement*>(n)->translateAttributeMode();
732 if (mode != TranslateAttributeInherit) {
733 ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
734 return mode == TranslateAttributeYes;
739 // Default on the root element is translate=yes.
743 void HTMLElement::setTranslate(bool enable)
745 setAttribute(translateAttr, enable ? "yes" : "no");
749 PassRefPtr<HTMLCollection> HTMLElement::children()
751 return ensureCachedHTMLCollection(NodeChildren);
754 bool HTMLElement::rendererIsNeeded(const NodeRenderingContext& context)
756 if (hasLocalName(noscriptTag)) {
757 Frame* frame = document()->frame();
758 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
760 } else if (hasLocalName(noembedTag)) {
761 Frame* frame = document()->frame();
762 if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
765 return StyledElement::rendererIsNeeded(context);
768 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
770 if (hasLocalName(wbrTag))
771 return new (arena) RenderWordBreak(this);
772 return RenderObject::createObject(this, style);
775 HTMLFormElement* HTMLElement::findFormAncestor() const
777 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
778 if (ancestor->hasTagName(formTag))
779 return static_cast<HTMLFormElement*>(ancestor);
784 HTMLFormElement* HTMLElement::virtualForm() const
786 return findFormAncestor();
789 static inline bool elementAffectsDirectionality(const Node* node)
791 return node->isHTMLElement() && (node->hasTagName(bdiTag) || toHTMLElement(node)->hasAttribute(dirAttr));
794 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
796 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
798 Node* node = firstNode->firstChild();
801 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
804 if (elementAffectsDirectionality(node)) {
805 if (node == lastNode)
807 node = node->traverseNextSibling(firstNode);
810 node->setSelfOrAncestorHasDirAutoAttribute(flag);
811 if (node == lastNode)
813 node = node->traverseNextNode(firstNode);
817 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
819 StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
820 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
823 bool HTMLElement::hasDirectionAuto() const
825 const AtomicString& direction = fastGetAttribute(dirAttr);
826 return (hasTagName(bdiTag) && direction == nullAtom) || equalIgnoringCase(direction, "auto");
829 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
831 if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
837 return directionality();
840 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
842 if (HTMLTextFormControlElement* textElement = toTextFormControl(const_cast<HTMLElement*>(this))) {
843 bool hasStrongDirectionality;
844 Unicode::Direction textDirection = textElement->value().defaultWritingDirection(&hasStrongDirectionality);
845 if (strongDirectionalityTextNode)
846 *strongDirectionalityTextNode = hasStrongDirectionality ? textElement : 0;
847 return (textDirection == Unicode::LeftToRight) ? LTR : RTL;
850 Node* node = firstChild();
852 // Skip bdi, script, style and text form controls.
853 if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
854 || (node->isElementNode() && toElement(node)->isTextFormControl())) {
855 node = node->traverseNextSibling(this);
859 // Skip elements with valid dir attribute
860 if (node->isElementNode()) {
861 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
862 if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
863 node = node->traverseNextSibling(this);
868 if (node->isTextNode()) {
869 bool hasStrongDirectionality;
870 WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
871 if (hasStrongDirectionality) {
872 if (strongDirectionalityTextNode)
873 *strongDirectionalityTextNode = node;
874 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
877 node = node->traverseNextNode(this);
879 if (strongDirectionalityTextNode)
880 *strongDirectionalityTextNode = 0;
884 void HTMLElement::dirAttributeChanged(const Attribute& attribute)
886 Element* parent = parentElement();
888 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
889 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
891 if (equalIgnoringCase(attribute.value(), "auto"))
892 calculateAndAdjustDirectionality();
895 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
897 ASSERT(selfOrAncestorHasDirAutoAttribute());
898 Node* strongDirectionalityTextNode;
899 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
900 setHasDirAutoFlagRecursively(child, false);
901 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
902 Element* elementToAdjust = this;
903 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
904 if (elementAffectsDirectionality(elementToAdjust)) {
905 elementToAdjust->setNeedsStyleRecalc();
912 void HTMLElement::calculateAndAdjustDirectionality()
914 Node* strongDirectionalityTextNode;
915 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
916 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
917 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
918 setNeedsStyleRecalc();
921 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
923 if ((!document() || document()->renderer()) && childCountDelta < 0) {
924 Node* node = beforeChange ? beforeChange->traverseNextSibling() : 0;
925 for (int counter = 0; node && counter < childCountDelta; counter++, node = node->traverseNextSibling()) {
926 if (elementAffectsDirectionality(node))
929 setHasDirAutoFlagRecursively(node, false);
933 if (!selfOrAncestorHasDirAutoAttribute())
936 Node* oldMarkedNode = beforeChange ? beforeChange->traverseNextSibling() : 0;
937 while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
938 oldMarkedNode = oldMarkedNode->traverseNextSibling(this);
940 setHasDirAutoFlagRecursively(oldMarkedNode, false);
942 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
943 if (elementAffectsDirectionality(elementToAdjust)) {
944 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
950 bool HTMLElement::isURLAttribute(const Attribute& attribute) const
952 #if ENABLE(MICRODATA)
953 return attribute.name() == itemidAttr;
955 UNUSED_PARAM(attribute);
960 #if ENABLE(MICRODATA)
961 void HTMLElement::setItemValue(const String& value, ExceptionCode& ec)
963 if (!hasAttribute(itempropAttr) || hasAttribute(itemscopeAttr)) {
964 ec = INVALID_ACCESS_ERR;
968 setItemValueText(value, ec);
971 PassRefPtr<MicroDataItemValue> HTMLElement::itemValue() const
973 if (!hasAttribute(itempropAttr))
976 if (hasAttribute(itemscopeAttr))
977 return MicroDataItemValue::createFromNode(const_cast<HTMLElement* const>(this));
979 return MicroDataItemValue::createFromString(itemValueText());
982 String HTMLElement::itemValueText() const
984 return textContent(true);
987 void HTMLElement::setItemValueText(const String& value, ExceptionCode& ec)
989 setTextContent(value, ec);
992 PassRefPtr<HTMLPropertiesCollection> HTMLElement::properties()
994 return static_cast<HTMLPropertiesCollection*>(ensureCachedHTMLCollection(ItemProperties).get());
998 void HTMLElement::addHTMLLengthToStyle(StylePropertySet* style, CSSPropertyID propertyID, const String& value)
1000 // FIXME: This function should not spin up the CSS parser, but should instead just figure out the correct
1001 // length unit and make the appropriate parsed value.
1003 // strip attribute garbage..
1004 StringImpl* v = value.impl();
1008 while (l < v->length() && (*v)[l] <= ' ')
1011 for (; l < v->length(); l++) {
1016 if (cc == '%' || cc == '*')
1023 if (l != v->length()) {
1024 addPropertyToAttributeStyle(style, propertyID, v->substring(0, l));
1029 addPropertyToAttributeStyle(style, propertyID, value);
1032 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
1034 // Per spec, only look at the first 128 digits of the string.
1035 const size_t maxColorLength = 128;
1036 // We'll pad the buffer with two extra 0s later, so reserve two more than the max.
1037 Vector<char, maxColorLength+2> digitBuffer;
1040 // Skip a leading #.
1041 if (colorString[0] == '#')
1044 // Grab the first 128 characters, replacing non-hex characters with 0.
1045 // Non-BMP characters are replaced with "00" due to them appearing as two "characters" in the String.
1046 for (; i < colorString.length() && digitBuffer.size() < maxColorLength; i++) {
1047 if (!isASCIIHexDigit(colorString[i]))
1048 digitBuffer.append('0');
1050 digitBuffer.append(colorString[i]);
1053 if (!digitBuffer.size())
1054 return Color::black;
1056 // Pad the buffer out to at least the next multiple of three in size.
1057 digitBuffer.append('0');
1058 digitBuffer.append('0');
1060 if (digitBuffer.size() < 6)
1061 return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
1063 // Split the digits into three components, then search the last 8 digits of each component.
1064 ASSERT(digitBuffer.size() >= 6);
1065 size_t componentLength = digitBuffer.size() / 3;
1066 size_t componentSearchWindowLength = min<size_t>(componentLength, 8);
1067 size_t redIndex = componentLength - componentSearchWindowLength;
1068 size_t greenIndex = componentLength * 2 - componentSearchWindowLength;
1069 size_t blueIndex = componentLength * 3 - componentSearchWindowLength;
1070 // Skip digits until one of them is non-zero, or we've only got two digits left in the component.
1071 while (digitBuffer[redIndex] == '0' && digitBuffer[greenIndex] == '0' && digitBuffer[blueIndex] == '0' && (componentLength - redIndex) > 2) {
1076 ASSERT(redIndex + 1 < componentLength);
1077 ASSERT(greenIndex >= componentLength);
1078 ASSERT(greenIndex + 1 < componentLength * 2);
1079 ASSERT(blueIndex >= componentLength * 2);
1080 ASSERT(blueIndex + 1 < digitBuffer.size());
1082 int redValue = toASCIIHexValue(digitBuffer[redIndex], digitBuffer[redIndex + 1]);
1083 int greenValue = toASCIIHexValue(digitBuffer[greenIndex], digitBuffer[greenIndex + 1]);
1084 int blueValue = toASCIIHexValue(digitBuffer[blueIndex], digitBuffer[blueIndex + 1]);
1085 return makeRGB(redValue, greenValue, blueValue);
1088 // Color parsing that matches HTML's "rules for parsing a legacy color value"
1089 void HTMLElement::addHTMLColorToStyle(StylePropertySet* style, CSSPropertyID propertyID, const String& attributeValue)
1091 // An empty string doesn't apply a color. (One containing only whitespace does, which is why this check occurs before stripping.)
1092 if (attributeValue.isEmpty())
1095 String colorString = attributeValue.stripWhiteSpace();
1097 // "transparent" doesn't apply a color either.
1098 if (equalIgnoringCase(colorString, "transparent"))
1101 // If the string is a named CSS color or a 3/6-digit hex color, use that.
1102 Color parsedColor(colorString);
1103 if (!parsedColor.isValid())
1104 parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
1106 style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
1109 } // namespace WebCore
1113 // For use in the debugger
1114 void dumpInnerHTML(WebCore::HTMLElement*);
1116 void dumpInnerHTML(WebCore::HTMLElement* element)
1118 printf("%s\n", element->innerHTML().ascii().data());