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