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 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
16 *
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
21 *
22 */
23
24 #include "config.h"
25 #include "HTMLElement.h"
26
27 #include "CSSPropertyNames.h"
28 #include "CSSValueKeywords.h"
29 #include "DocumentFragment.h"
30 #include "Event.h"
31 #include "EventListener.h"
32 #include "EventNames.h"
33 #include "ExceptionCode.h"
34 #include "Frame.h"
35 #include "HTMLBRElement.h"
36 #include "HTMLCollection.h"
37 #include "HTMLDocument.h"
38 #include "HTMLElementFactory.h"
39 #include "HTMLFormElement.h"
40 #include "HTMLNames.h"
41 #include "HTMLTokenizer.h"
42 #include "MappedAttribute.h"
43 #include "RenderWordBreak.h"
44 #include "ScriptEventListener.h"
45 #include "Settings.h"
46 #include "Text.h"
47 #include "TextIterator.h"
48 #include "XMLTokenizer.h"
49 #include "markup.h"
50 #include <wtf/StdLibExtras.h>
51
52 namespace WebCore {
53
54 using namespace HTMLNames;
55
56 using std::min;
57 using std::max;
58
HTMLElement(const QualifiedName & tagName,Document * doc)59 HTMLElement::HTMLElement(const QualifiedName& tagName, Document *doc)
60 : StyledElement(tagName, doc)
61 {
62 }
63
~HTMLElement()64 HTMLElement::~HTMLElement()
65 {
66 }
67
nodeName() const68 String HTMLElement::nodeName() const
69 {
70 // FIXME: Would be nice to have an atomicstring lookup based off uppercase chars that does not have to copy
71 // the string on a hit in the hash.
72 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
73 if (document()->isHTMLDocument() && !tagQName().hasPrefix())
74 return tagQName().localName().string().upper();
75 return Element::nodeName();
76 }
77
endTagRequirement() const78 HTMLTagStatus HTMLElement::endTagRequirement() const
79 {
80 if (hasLocalName(wbrTag))
81 return TagStatusForbidden;
82 if (hasLocalName(dtTag) || hasLocalName(ddTag) || hasLocalName(rpTag) || hasLocalName(rtTag))
83 return TagStatusOptional;
84
85 // Same values as <span>. This way custom tag name elements will behave like inline spans.
86 return TagStatusRequired;
87 }
88
tagPriority() const89 int HTMLElement::tagPriority() const
90 {
91 if (hasLocalName(wbrTag))
92 return 0;
93 if (hasLocalName(addressTag) || hasLocalName(ddTag) || hasLocalName(dtTag) || hasLocalName(noscriptTag) || hasLocalName(rpTag) || hasLocalName(rtTag))
94 return 3;
95 if (hasLocalName(centerTag) || hasLocalName(nobrTag) || hasLocalName(rubyTag))
96 return 5;
97 if (hasLocalName(noembedTag) || hasLocalName(noframesTag))
98 return 10;
99
100 // Same values as <span>. This way custom tag name elements will behave like inline spans.
101 return 1;
102 }
103
mapToEntry(const QualifiedName & attrName,MappedAttributeEntry & result) const104 bool HTMLElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
105 {
106 if (attrName == alignAttr ||
107 attrName == contenteditableAttr) {
108 result = eUniversal;
109 return false;
110 }
111 if (attrName == dirAttr) {
112 result = hasLocalName(bdoTag) ? eBDO : eUniversal;
113 return false;
114 }
115
116 return StyledElement::mapToEntry(attrName, result);
117 }
118
parseMappedAttribute(MappedAttribute * attr)119 void HTMLElement::parseMappedAttribute(MappedAttribute *attr)
120 {
121 if (attr->name() == idAttr || attr->name() == classAttr || attr->name() == styleAttr)
122 return StyledElement::parseMappedAttribute(attr);
123
124 String indexstring;
125 if (attr->name() == alignAttr) {
126 if (equalIgnoringCase(attr->value(), "middle"))
127 addCSSProperty(attr, CSSPropertyTextAlign, "center");
128 else
129 addCSSProperty(attr, CSSPropertyTextAlign, attr->value());
130 } else if (attr->name() == contenteditableAttr) {
131 setContentEditable(attr);
132 } else if (attr->name() == tabindexAttr) {
133 indexstring = getAttribute(tabindexAttr);
134 if (indexstring.length()) {
135 bool parsedOK;
136 int tabindex = indexstring.toIntStrict(&parsedOK);
137 if (parsedOK)
138 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
139 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
140 }
141 } else if (attr->name() == langAttr) {
142 // FIXME: Implement
143 } else if (attr->name() == dirAttr) {
144 addCSSProperty(attr, CSSPropertyDirection, attr->value());
145 addCSSProperty(attr, CSSPropertyUnicodeBidi, hasLocalName(bdoTag) ? CSSValueBidiOverride : CSSValueEmbed);
146 } else if (attr->name() == draggableAttr) {
147 const AtomicString& value = attr->value();
148 if (equalIgnoringCase(value, "true")) {
149 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueElement);
150 addCSSProperty(attr, CSSPropertyWebkitUserSelect, CSSValueNone);
151 } else if (equalIgnoringCase(value, "false"))
152 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueNone);
153 }
154 // standard events
155 else if (attr->name() == onclickAttr) {
156 setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attr));
157 } else if (attr->name() == oncontextmenuAttr) {
158 setAttributeEventListener(eventNames().contextmenuEvent, createAttributeEventListener(this, attr));
159 } else if (attr->name() == ondblclickAttr) {
160 setAttributeEventListener(eventNames().dblclickEvent, createAttributeEventListener(this, attr));
161 } else if (attr->name() == onmousedownAttr) {
162 setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, attr));
163 } else if (attr->name() == onmousemoveAttr) {
164 setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, attr));
165 } else if (attr->name() == onmouseoutAttr) {
166 setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, attr));
167 } else if (attr->name() == onmouseoverAttr) {
168 setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, attr));
169 } else if (attr->name() == onmouseupAttr) {
170 setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, attr));
171 } else if (attr->name() == onmousewheelAttr) {
172 setAttributeEventListener(eventNames().mousewheelEvent, createAttributeEventListener(this, attr));
173 } else if (attr->name() == onfocusAttr) {
174 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
175 } else if (attr->name() == onblurAttr) {
176 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
177 } else if (attr->name() == onkeydownAttr) {
178 setAttributeEventListener(eventNames().keydownEvent, createAttributeEventListener(this, attr));
179 } else if (attr->name() == onkeypressAttr) {
180 setAttributeEventListener(eventNames().keypressEvent, createAttributeEventListener(this, attr));
181 } else if (attr->name() == onkeyupAttr) {
182 setAttributeEventListener(eventNames().keyupEvent, createAttributeEventListener(this, attr));
183 } else if (attr->name() == onscrollAttr) {
184 setAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(this, attr));
185 } else if (attr->name() == onbeforecutAttr) {
186 setAttributeEventListener(eventNames().beforecutEvent, createAttributeEventListener(this, attr));
187 } else if (attr->name() == oncutAttr) {
188 setAttributeEventListener(eventNames().cutEvent, createAttributeEventListener(this, attr));
189 } else if (attr->name() == onbeforecopyAttr) {
190 setAttributeEventListener(eventNames().beforecopyEvent, createAttributeEventListener(this, attr));
191 } else if (attr->name() == oncopyAttr) {
192 setAttributeEventListener(eventNames().copyEvent, createAttributeEventListener(this, attr));
193 } else if (attr->name() == onbeforepasteAttr) {
194 setAttributeEventListener(eventNames().beforepasteEvent, createAttributeEventListener(this, attr));
195 } else if (attr->name() == onpasteAttr) {
196 setAttributeEventListener(eventNames().pasteEvent, createAttributeEventListener(this, attr));
197 } else if (attr->name() == ondragenterAttr) {
198 setAttributeEventListener(eventNames().dragenterEvent, createAttributeEventListener(this, attr));
199 } else if (attr->name() == ondragoverAttr) {
200 setAttributeEventListener(eventNames().dragoverEvent, createAttributeEventListener(this, attr));
201 } else if (attr->name() == ondragleaveAttr) {
202 setAttributeEventListener(eventNames().dragleaveEvent, createAttributeEventListener(this, attr));
203 } else if (attr->name() == ondropAttr) {
204 setAttributeEventListener(eventNames().dropEvent, createAttributeEventListener(this, attr));
205 } else if (attr->name() == ondragstartAttr) {
206 setAttributeEventListener(eventNames().dragstartEvent, createAttributeEventListener(this, attr));
207 } else if (attr->name() == ondragAttr) {
208 setAttributeEventListener(eventNames().dragEvent, createAttributeEventListener(this, attr));
209 } else if (attr->name() == ondragendAttr) {
210 setAttributeEventListener(eventNames().dragendEvent, createAttributeEventListener(this, attr));
211 } else if (attr->name() == onselectstartAttr) {
212 setAttributeEventListener(eventNames().selectstartEvent, createAttributeEventListener(this, attr));
213 } else if (attr->name() == onsubmitAttr) {
214 setAttributeEventListener(eventNames().submitEvent, createAttributeEventListener(this, attr));
215 } else if (attr->name() == onerrorAttr) {
216 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attr));
217 } else if (attr->name() == onwebkitanimationstartAttr) {
218 setAttributeEventListener(eventNames().webkitAnimationStartEvent, createAttributeEventListener(this, attr));
219 } else if (attr->name() == onwebkitanimationiterationAttr) {
220 setAttributeEventListener(eventNames().webkitAnimationIterationEvent, createAttributeEventListener(this, attr));
221 } else if (attr->name() == onwebkitanimationendAttr) {
222 setAttributeEventListener(eventNames().webkitAnimationEndEvent, createAttributeEventListener(this, attr));
223 } else if (attr->name() == onwebkittransitionendAttr) {
224 setAttributeEventListener(eventNames().webkitTransitionEndEvent, createAttributeEventListener(this, attr));
225 #if ENABLE(TOUCH_EVENTS) // Android
226 } else if (attr->name() == ontouchstartAttr) {
227 setAttributeEventListener(eventNames().touchstartEvent, createAttributeEventListener(this, attr));
228 } else if (attr->name() == ontouchendAttr) {
229 setAttributeEventListener(eventNames().touchendEvent, createAttributeEventListener(this, attr));
230 } else if (attr->name() == ontouchmoveAttr) {
231 setAttributeEventListener(eventNames().touchmoveEvent, createAttributeEventListener(this, attr));
232 } else if (attr->name() == ontouchcancelAttr) {
233 setAttributeEventListener(eventNames().touchcancelEvent, createAttributeEventListener(this, attr));
234 #endif
235 } else if (attr->name() == oninputAttr) {
236 setAttributeEventListener(eventNames().inputEvent, createAttributeEventListener(this, attr));
237 }
238 }
239
innerHTML() const240 String HTMLElement::innerHTML() const
241 {
242 return createMarkup(this, ChildrenOnly);
243 }
244
outerHTML() const245 String HTMLElement::outerHTML() const
246 {
247 return createMarkup(this);
248 }
249
createContextualFragment(const String & html)250 PassRefPtr<DocumentFragment> HTMLElement::createContextualFragment(const String &html)
251 {
252 // the following is in accordance with the definition as used by IE
253 if (endTagRequirement() == TagStatusForbidden)
254 return 0;
255
256 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
257 hasLocalName(headTag) || hasLocalName(styleTag) || hasLocalName(titleTag))
258 return 0;
259
260 RefPtr<DocumentFragment> fragment = new DocumentFragment(document());
261
262 if (document()->isHTMLDocument())
263 parseHTMLDocumentFragment(html, fragment.get());
264 else {
265 if (!parseXMLDocumentFragment(html, fragment.get(), this))
266 // FIXME: We should propagate a syntax error exception out here.
267 return 0;
268 }
269
270 // Exceptions are ignored because none ought to happen here.
271 int ignoredExceptionCode;
272
273 // we need to pop <html> and <body> elements and remove <head> to
274 // accommodate folks passing complete HTML documents to make the
275 // child of an element.
276
277 RefPtr<Node> nextNode;
278 for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
279 nextNode = node->nextSibling();
280 if (node->hasTagName(htmlTag) || node->hasTagName(bodyTag)) {
281 Node *firstChild = node->firstChild();
282 if (firstChild)
283 nextNode = firstChild;
284 RefPtr<Node> nextChild;
285 for (RefPtr<Node> child = firstChild; child; child = nextChild) {
286 nextChild = child->nextSibling();
287 node->removeChild(child.get(), ignoredExceptionCode);
288 ASSERT(!ignoredExceptionCode);
289 fragment->insertBefore(child, node.get(), ignoredExceptionCode);
290 ASSERT(!ignoredExceptionCode);
291 }
292 fragment->removeChild(node.get(), ignoredExceptionCode);
293 ASSERT(!ignoredExceptionCode);
294 } else if (node->hasTagName(headTag)) {
295 fragment->removeChild(node.get(), ignoredExceptionCode);
296 ASSERT(!ignoredExceptionCode);
297 }
298 }
299
300 return fragment.release();
301 }
302
hasOneChild(ContainerNode * node)303 static inline bool hasOneChild(ContainerNode* node)
304 {
305 Node* firstChild = node->firstChild();
306 return firstChild && !firstChild->nextSibling();
307 }
308
hasOneTextChild(ContainerNode * node)309 static inline bool hasOneTextChild(ContainerNode* node)
310 {
311 return hasOneChild(node) && node->firstChild()->isTextNode();
312 }
313
replaceChildrenWithFragment(HTMLElement * element,PassRefPtr<DocumentFragment> fragment,ExceptionCode & ec)314 static void replaceChildrenWithFragment(HTMLElement* element, PassRefPtr<DocumentFragment> fragment, ExceptionCode& ec)
315 {
316 if (!fragment->firstChild()) {
317 element->removeChildren();
318 return;
319 }
320
321 if (hasOneTextChild(element) && hasOneTextChild(fragment.get())) {
322 static_cast<Text*>(element->firstChild())->setData(static_cast<Text*>(fragment->firstChild())->string(), ec);
323 return;
324 }
325
326 if (hasOneChild(element)) {
327 element->replaceChild(fragment, element->firstChild(), ec);
328 return;
329 }
330
331 element->removeChildren();
332 element->appendChild(fragment, ec);
333 }
334
replaceChildrenWithText(HTMLElement * element,const String & text,ExceptionCode & ec)335 static void replaceChildrenWithText(HTMLElement* element, const String& text, ExceptionCode& ec)
336 {
337 if (hasOneTextChild(element)) {
338 static_cast<Text*>(element->firstChild())->setData(text, ec);
339 return;
340 }
341
342 RefPtr<Text> textNode = new Text(element->document(), text);
343
344 if (hasOneChild(element)) {
345 element->replaceChild(textNode.release(), element->firstChild(), ec);
346 return;
347 }
348
349 element->removeChildren();
350 element->appendChild(textNode.release(), ec);
351 }
352
setInnerHTML(const String & html,ExceptionCode & ec)353 void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec)
354 {
355 RefPtr<DocumentFragment> fragment = createContextualFragment(html);
356 if (!fragment) {
357 ec = NO_MODIFICATION_ALLOWED_ERR;
358 return;
359 }
360
361 replaceChildrenWithFragment(this, fragment.release(), ec);
362 }
363
setOuterHTML(const String & html,ExceptionCode & ec)364 void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
365 {
366 Node* p = parent();
367 if (!p || !p->isHTMLElement()) {
368 ec = NO_MODIFICATION_ALLOWED_ERR;
369 return;
370 }
371
372 HTMLElement* parent = static_cast<HTMLElement*>(p);
373 RefPtr<DocumentFragment> fragment = parent->createContextualFragment(html);
374 if (!fragment) {
375 ec = NO_MODIFICATION_ALLOWED_ERR;
376 return;
377 }
378
379 // FIXME: Why doesn't this have code to merge neighboring text nodes the way setOuterText does?
380
381 parent->replaceChild(fragment.release(), this, ec);
382 }
383
setInnerText(const String & text,ExceptionCode & ec)384 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
385 {
386 // follow the IE specs about when this is allowed
387 if (endTagRequirement() == TagStatusForbidden) {
388 ec = NO_MODIFICATION_ALLOWED_ERR;
389 return;
390 }
391 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
392 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
393 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
394 hasLocalName(trTag)) {
395 ec = NO_MODIFICATION_ALLOWED_ERR;
396 return;
397 }
398
399 // FIXME: This doesn't take whitespace collapsing into account at all.
400
401 if (!text.contains('\n') && !text.contains('\r')) {
402 if (text.isEmpty()) {
403 removeChildren();
404 return;
405 }
406 replaceChildrenWithText(this, text, ec);
407 return;
408 }
409
410 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
411 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
412 // For example, for the contents of textarea elements that are display:none?
413 RenderObject* r = renderer();
414 if (r && r->style()->preserveNewline()) {
415 if (!text.contains('\r')) {
416 replaceChildrenWithText(this, text, ec);
417 return;
418 }
419 String textWithConsistentLineBreaks = text;
420 textWithConsistentLineBreaks.replace("\r\n", "\n");
421 textWithConsistentLineBreaks.replace('\r', '\n');
422 replaceChildrenWithText(this, textWithConsistentLineBreaks, ec);
423 return;
424 }
425
426 // Add text nodes and <br> elements.
427 ec = 0;
428 RefPtr<DocumentFragment> fragment = new DocumentFragment(document());
429 int lineStart = 0;
430 UChar prev = 0;
431 int length = text.length();
432 for (int i = 0; i < length; ++i) {
433 UChar c = text[i];
434 if (c == '\n' || c == '\r') {
435 if (i > lineStart) {
436 fragment->appendChild(new Text(document(), text.substring(lineStart, i - lineStart)), ec);
437 if (ec)
438 return;
439 }
440 if (!(c == '\n' && i != 0 && prev == '\r')) {
441 fragment->appendChild(new HTMLBRElement(brTag, document()), ec);
442 if (ec)
443 return;
444 }
445 lineStart = i + 1;
446 }
447 prev = c;
448 }
449 if (length > lineStart)
450 fragment->appendChild(new Text(document(), text.substring(lineStart, length - lineStart)), ec);
451 replaceChildrenWithFragment(this, fragment.release(), ec);
452 }
453
setOuterText(const String & text,ExceptionCode & ec)454 void HTMLElement::setOuterText(const String &text, ExceptionCode& ec)
455 {
456 // follow the IE specs about when this is allowed
457 if (endTagRequirement() == TagStatusForbidden) {
458 ec = NO_MODIFICATION_ALLOWED_ERR;
459 return;
460 }
461 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
462 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
463 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
464 hasLocalName(trTag)) {
465 ec = NO_MODIFICATION_ALLOWED_ERR;
466 return;
467 }
468
469 Node* parent = parentNode();
470 if (!parent) {
471 ec = NO_MODIFICATION_ALLOWED_ERR;
472 return;
473 }
474
475 // FIXME: This creates a new text node even when the text is empty.
476 // FIXME: This creates a single text node even when the text has CR and LF
477 // characters in it. Instead it should create <br> elements.
478 RefPtr<Text> t = new Text(document(), text);
479 ec = 0;
480 parent->replaceChild(t, this, ec);
481 if (ec)
482 return;
483
484 // is previous node a text node? if so, merge into it
485 Node* prev = t->previousSibling();
486 if (prev && prev->isTextNode()) {
487 Text* textPrev = static_cast<Text*>(prev);
488 textPrev->appendData(t->data(), ec);
489 if (ec)
490 return;
491 t->remove(ec);
492 if (ec)
493 return;
494 t = textPrev;
495 }
496
497 // is next node a text node? if so, merge it in
498 Node* next = t->nextSibling();
499 if (next && next->isTextNode()) {
500 Text* textNext = static_cast<Text*>(next);
501 t->appendData(textNext->data(), ec);
502 if (ec)
503 return;
504 textNext->remove(ec);
505 if (ec)
506 return;
507 }
508 }
509
insertAdjacent(const String & where,Node * newChild,ExceptionCode & ec)510 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionCode& ec)
511 {
512 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
513 // a document fragment is created and the elements appended in the correct order. This document
514 // fragment isn't returned anywhere.
515 //
516 // This is impossible for us to implement as the DOM tree does not allow for such structures,
517 // Opera also appears to disallow such usage.
518
519 if (equalIgnoringCase(where, "beforeBegin")) {
520 if (Node* p = parent())
521 return p->insertBefore(newChild, this, ec) ? newChild : 0;
522 return 0;
523 }
524
525 if (equalIgnoringCase(where, "afterBegin"))
526 return insertBefore(newChild, firstChild(), ec) ? newChild : 0;
527
528 if (equalIgnoringCase(where, "beforeEnd"))
529 return appendChild(newChild, ec) ? newChild : 0;
530
531 if (equalIgnoringCase(where, "afterEnd")) {
532 if (Node* p = parent())
533 return p->insertBefore(newChild, nextSibling(), ec) ? newChild : 0;
534 return 0;
535 }
536
537 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative
538 ec = NOT_SUPPORTED_ERR;
539 return 0;
540 }
541
insertAdjacentElement(const String & where,Element * newChild,ExceptionCode & ec)542 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
543 {
544 if (!newChild) {
545 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative
546 ec = TYPE_MISMATCH_ERR;
547 return 0;
548 }
549
550 Node* returnValue = insertAdjacent(where, newChild, ec);
551 ASSERT(!returnValue || returnValue->isElementNode());
552 return static_cast<Element*>(returnValue);
553 }
554
insertAdjacentHTML(const String & where,const String & html,ExceptionCode & ec)555 void HTMLElement::insertAdjacentHTML(const String& where, const String& html, ExceptionCode& ec)
556 {
557 RefPtr<DocumentFragment> fragment = document()->createDocumentFragment();
558 if (document()->isHTMLDocument())
559 parseHTMLDocumentFragment(html, fragment.get());
560 else {
561 if (!parseXMLDocumentFragment(html, fragment.get(), this))
562 // FIXME: We should propagate a syntax error exception out here.
563 return;
564 }
565
566 insertAdjacent(where, fragment.get(), ec);
567 }
568
insertAdjacentText(const String & where,const String & text,ExceptionCode & ec)569 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
570 {
571 RefPtr<Text> textNode = document()->createTextNode(text);
572 insertAdjacent(where, textNode.get(), ec);
573 }
574
addHTMLAlignment(MappedAttribute * attr)575 void HTMLElement::addHTMLAlignment(MappedAttribute* attr)
576 {
577 addHTMLAlignmentToStyledElement(this, attr);
578 }
579
addHTMLAlignmentToStyledElement(StyledElement * element,MappedAttribute * attr)580 void HTMLElement::addHTMLAlignmentToStyledElement(StyledElement* element, MappedAttribute* attr)
581 {
582 // vertical alignment with respect to the current baseline of the text
583 // right or left means floating images
584 int floatValue = CSSValueInvalid;
585 int verticalAlignValue = CSSValueInvalid;
586
587 const AtomicString& alignment = attr->value();
588 if (equalIgnoringCase(alignment, "absmiddle"))
589 verticalAlignValue = CSSValueMiddle;
590 else if (equalIgnoringCase(alignment, "absbottom"))
591 verticalAlignValue = CSSValueBottom;
592 else if (equalIgnoringCase(alignment, "left")) {
593 floatValue = CSSValueLeft;
594 verticalAlignValue = CSSValueTop;
595 } else if (equalIgnoringCase(alignment, "right")) {
596 floatValue = CSSValueRight;
597 verticalAlignValue = CSSValueTop;
598 } else if (equalIgnoringCase(alignment, "top"))
599 verticalAlignValue = CSSValueTop;
600 else if (equalIgnoringCase(alignment, "middle"))
601 verticalAlignValue = CSSValueWebkitBaselineMiddle;
602 else if (equalIgnoringCase(alignment, "center"))
603 verticalAlignValue = CSSValueMiddle;
604 else if (equalIgnoringCase(alignment, "bottom"))
605 verticalAlignValue = CSSValueBaseline;
606 else if (equalIgnoringCase(alignment, "texttop"))
607 verticalAlignValue = CSSValueTextTop;
608
609 if (floatValue != CSSValueInvalid)
610 element->addCSSProperty(attr, CSSPropertyFloat, floatValue);
611
612 if (verticalAlignValue != CSSValueInvalid)
613 element->addCSSProperty(attr, CSSPropertyVerticalAlign, verticalAlignValue);
614 }
615
isFocusable() const616 bool HTMLElement::isFocusable() const
617 {
618 return Element::isFocusable() || (isContentEditable() && parent() && !parent()->isContentEditable());
619 }
620
isContentEditable() const621 bool HTMLElement::isContentEditable() const
622 {
623 if (document()->frame() && document()->frame()->isContentEditable())
624 return true;
625
626 // FIXME: this is a terrible thing to do here:
627 // https://bugs.webkit.org/show_bug.cgi?id=21834
628 document()->updateStyleIfNeeded();
629
630 if (!renderer()) {
631 if (parentNode())
632 return parentNode()->isContentEditable();
633 else
634 return false;
635 }
636
637 return renderer()->style()->userModify() == READ_WRITE || renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY;
638 }
639
isContentRichlyEditable() const640 bool HTMLElement::isContentRichlyEditable() const
641 {
642 if (document()->frame() && document()->frame()->isContentEditable())
643 return true;
644
645 document()->updateStyleIfNeeded();
646
647 if (!renderer()) {
648 if (parentNode())
649 return parentNode()->isContentEditable();
650 else
651 return false;
652 }
653
654 return renderer()->style()->userModify() == READ_WRITE;
655 }
656
contentEditable() const657 String HTMLElement::contentEditable() const
658 {
659 document()->updateStyleIfNeeded();
660
661 if (!renderer())
662 return "false";
663
664 switch (renderer()->style()->userModify()) {
665 case READ_WRITE:
666 return "true";
667 case READ_ONLY:
668 return "false";
669 case READ_WRITE_PLAINTEXT_ONLY:
670 return "plaintext-only";
671 default:
672 return "inherit";
673 }
674 }
675
setContentEditable(MappedAttribute * attr)676 void HTMLElement::setContentEditable(MappedAttribute* attr)
677 {
678 const AtomicString& enabled = attr->value();
679 if (enabled.isEmpty() || equalIgnoringCase(enabled, "true")) {
680 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWrite);
681 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
682 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
683 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
684 } else if (equalIgnoringCase(enabled, "false")) {
685 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadOnly);
686 attr->decl()->removeProperty(CSSPropertyWordWrap, false);
687 attr->decl()->removeProperty(CSSPropertyWebkitNbspMode, false);
688 attr->decl()->removeProperty(CSSPropertyWebkitLineBreak, false);
689 } else if (equalIgnoringCase(enabled, "inherit")) {
690 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueInherit);
691 attr->decl()->removeProperty(CSSPropertyWordWrap, false);
692 attr->decl()->removeProperty(CSSPropertyWebkitNbspMode, false);
693 attr->decl()->removeProperty(CSSPropertyWebkitLineBreak, false);
694 } else if (equalIgnoringCase(enabled, "plaintext-only")) {
695 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
696 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
697 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
698 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
699 }
700 }
701
setContentEditable(const String & enabled)702 void HTMLElement::setContentEditable(const String &enabled)
703 {
704 if (enabled == "inherit") {
705 ExceptionCode ec;
706 removeAttribute(contenteditableAttr, ec);
707 }
708 else
709 setAttribute(contenteditableAttr, enabled.isEmpty() ? "true" : enabled);
710 }
711
draggable() const712 bool HTMLElement::draggable() const
713 {
714 return equalIgnoringCase(getAttribute(draggableAttr), "true");
715 }
716
setDraggable(bool value)717 void HTMLElement::setDraggable(bool value)
718 {
719 setAttribute(draggableAttr, value ? "true" : "false");
720 }
721
click()722 void HTMLElement::click()
723 {
724 dispatchSimulatedClick(0, false, false);
725 }
726
727 // accessKeyAction is used by the accessibility support code
728 // to send events to elements that our JavaScript caller does
729 // does not. The elements JS is interested in have subclasses
730 // that override this method to direct the click appropriately.
731 // Here in the base class, then, we only send the click if
732 // the caller wants it to go to any HTMLElement, and we say
733 // to send the mouse events in addition to the click.
accessKeyAction(bool sendToAnyElement)734 void HTMLElement::accessKeyAction(bool sendToAnyElement)
735 {
736 if (sendToAnyElement)
737 dispatchSimulatedClick(0, true);
738 }
739
id() const740 String HTMLElement::id() const
741 {
742 return getAttribute(idAttr);
743 }
744
setId(const String & value)745 void HTMLElement::setId(const String& value)
746 {
747 setAttribute(idAttr, value);
748 }
749
title() const750 String HTMLElement::title() const
751 {
752 return getAttribute(titleAttr);
753 }
754
setTitle(const String & value)755 void HTMLElement::setTitle(const String& value)
756 {
757 setAttribute(titleAttr, value);
758 }
759
lang() const760 String HTMLElement::lang() const
761 {
762 return getAttribute(langAttr);
763 }
764
setLang(const String & value)765 void HTMLElement::setLang(const String& value)
766 {
767 setAttribute(langAttr, value);
768 }
769
dir() const770 String HTMLElement::dir() const
771 {
772 return getAttribute(dirAttr);
773 }
774
setDir(const String & value)775 void HTMLElement::setDir(const String &value)
776 {
777 setAttribute(dirAttr, value);
778 }
779
className() const780 String HTMLElement::className() const
781 {
782 return getAttribute(classAttr);
783 }
784
setClassName(const String & value)785 void HTMLElement::setClassName(const String &value)
786 {
787 setAttribute(classAttr, value);
788 }
789
tabIndex() const790 short HTMLElement::tabIndex() const
791 {
792 if (supportsFocus())
793 return Element::tabIndex();
794 return -1;
795 }
796
setTabIndex(int value)797 void HTMLElement::setTabIndex(int value)
798 {
799 setAttribute(tabindexAttr, String::number(value));
800 }
801
children()802 PassRefPtr<HTMLCollection> HTMLElement::children()
803 {
804 return HTMLCollection::create(this, NodeChildren);
805 }
806
807 // DOM Section 1.1.1
childAllowed(Node * newChild)808 bool HTMLElement::childAllowed(Node *newChild)
809 {
810 if (!Element::childAllowed(newChild))
811 return false;
812
813 // For XML documents, we are non-validating and do not check against a DTD, even for HTML elements.
814 if (!document()->isHTMLDocument())
815 return true;
816
817 // Future-proof for XML content inside HTML documents (we may allow this some day).
818 if (newChild->isElementNode() && !newChild->isHTMLElement())
819 return true;
820
821 // Elements with forbidden tag status can never have children
822 if (endTagRequirement() == TagStatusForbidden)
823 return false;
824
825 // Comment nodes are always allowed.
826 if (newChild->isCommentNode())
827 return true;
828
829 // Now call checkDTD.
830 return checkDTD(newChild);
831 }
832
833 // DTD Stuff
834 // This unfortunate function is only needed when checking against the DTD. Other languages (like SVG) won't need this.
isRecognizedTagName(const QualifiedName & tagName)835 bool HTMLElement::isRecognizedTagName(const QualifiedName& tagName)
836 {
837 DEFINE_STATIC_LOCAL(HashSet<AtomicStringImpl*>, tagList, ());
838 if (tagList.isEmpty()) {
839 size_t tagCount = 0;
840 WebCore::QualifiedName** tags = HTMLNames::getHTMLTags(&tagCount);
841 for (size_t i = 0; i < tagCount; i++)
842 tagList.add(tags[i]->localName().impl());
843 }
844 return tagList.contains(tagName.localName().impl());
845 }
846
847 // The terms inline and block are used here loosely. Don't make the mistake of assuming all inlines or all blocks
848 // need to be in these two lists.
inlineTagList()849 static HashSet<AtomicStringImpl*>* inlineTagList()
850 {
851 DEFINE_STATIC_LOCAL(HashSet<AtomicStringImpl*>, tagList, ());
852 if (tagList.isEmpty()) {
853 tagList.add(ttTag.localName().impl());
854 tagList.add(iTag.localName().impl());
855 tagList.add(bTag.localName().impl());
856 tagList.add(uTag.localName().impl());
857 tagList.add(sTag.localName().impl());
858 tagList.add(strikeTag.localName().impl());
859 tagList.add(bigTag.localName().impl());
860 tagList.add(smallTag.localName().impl());
861 tagList.add(emTag.localName().impl());
862 tagList.add(strongTag.localName().impl());
863 tagList.add(dfnTag.localName().impl());
864 tagList.add(codeTag.localName().impl());
865 tagList.add(sampTag.localName().impl());
866 tagList.add(kbdTag.localName().impl());
867 tagList.add(varTag.localName().impl());
868 tagList.add(citeTag.localName().impl());
869 tagList.add(abbrTag.localName().impl());
870 tagList.add(acronymTag.localName().impl());
871 tagList.add(aTag.localName().impl());
872 tagList.add(canvasTag.localName().impl());
873 tagList.add(imgTag.localName().impl());
874 tagList.add(appletTag.localName().impl());
875 tagList.add(objectTag.localName().impl());
876 tagList.add(embedTag.localName().impl());
877 tagList.add(fontTag.localName().impl());
878 tagList.add(basefontTag.localName().impl());
879 tagList.add(brTag.localName().impl());
880 tagList.add(scriptTag.localName().impl());
881 tagList.add(styleTag.localName().impl());
882 tagList.add(linkTag.localName().impl());
883 tagList.add(mapTag.localName().impl());
884 tagList.add(qTag.localName().impl());
885 tagList.add(subTag.localName().impl());
886 tagList.add(supTag.localName().impl());
887 tagList.add(spanTag.localName().impl());
888 tagList.add(bdoTag.localName().impl());
889 tagList.add(iframeTag.localName().impl());
890 tagList.add(inputTag.localName().impl());
891 tagList.add(keygenTag.localName().impl());
892 tagList.add(selectTag.localName().impl());
893 tagList.add(datagridTag.localName().impl());
894 tagList.add(textareaTag.localName().impl());
895 tagList.add(labelTag.localName().impl());
896 tagList.add(buttonTag.localName().impl());
897 tagList.add(insTag.localName().impl());
898 tagList.add(delTag.localName().impl());
899 tagList.add(nobrTag.localName().impl());
900 tagList.add(wbrTag.localName().impl());
901 #if ENABLE(VIDEO)
902 tagList.add(audioTag.localName().impl());
903 tagList.add(videoTag.localName().impl());
904 #endif
905 tagList.add(rpTag.localName().impl());
906 tagList.add(rtTag.localName().impl());
907 tagList.add(rubyTag.localName().impl());
908 }
909 return &tagList;
910 }
911
blockTagList()912 static HashSet<AtomicStringImpl*>* blockTagList()
913 {
914 DEFINE_STATIC_LOCAL(HashSet<AtomicStringImpl*>, tagList, ());
915 if (tagList.isEmpty()) {
916 tagList.add(addressTag.localName().impl());
917 tagList.add(blockquoteTag.localName().impl());
918 tagList.add(centerTag.localName().impl());
919 tagList.add(ddTag.localName().impl());
920 tagList.add(dirTag.localName().impl());
921 tagList.add(divTag.localName().impl());
922 tagList.add(dlTag.localName().impl());
923 tagList.add(dtTag.localName().impl());
924 tagList.add(fieldsetTag.localName().impl());
925 tagList.add(formTag.localName().impl());
926 tagList.add(h1Tag.localName().impl());
927 tagList.add(h2Tag.localName().impl());
928 tagList.add(h3Tag.localName().impl());
929 tagList.add(h4Tag.localName().impl());
930 tagList.add(h5Tag.localName().impl());
931 tagList.add(h6Tag.localName().impl());
932 tagList.add(hrTag.localName().impl());
933 tagList.add(isindexTag.localName().impl());
934 tagList.add(layerTag.localName().impl());
935 tagList.add(liTag.localName().impl());
936 tagList.add(listingTag.localName().impl());
937 tagList.add(marqueeTag.localName().impl());
938 tagList.add(menuTag.localName().impl());
939 tagList.add(noembedTag.localName().impl());
940 tagList.add(noframesTag.localName().impl());
941 tagList.add(nolayerTag.localName().impl());
942 tagList.add(noscriptTag.localName().impl());
943 tagList.add(olTag.localName().impl());
944 tagList.add(pTag.localName().impl());
945 tagList.add(plaintextTag.localName().impl());
946 tagList.add(preTag.localName().impl());
947 tagList.add(tableTag.localName().impl());
948 tagList.add(ulTag.localName().impl());
949 tagList.add(xmpTag.localName().impl());
950 }
951 return &tagList;
952 }
953
inEitherTagList(const Node * newChild)954 bool HTMLElement::inEitherTagList(const Node* newChild)
955 {
956 if (newChild->isTextNode())
957 return true;
958
959 if (newChild->isHTMLElement()) {
960 const HTMLElement* child = static_cast<const HTMLElement*>(newChild);
961 if (inlineTagList()->contains(child->tagQName().localName().impl())) {
962 #if PLATFORM(MAC)
963 if (child->tagQName().localName() == styleTag) {
964 // Leopard Mail doesn't expect <style> to be in the body of the document, so don't allow it in that case.
965 // See <rdar://problem/6621310>
966 Settings* settings = newChild->document() ? newChild->document()->settings() : 0;
967 if (settings && settings->needsLeopardMailQuirks())
968 return false;
969 }
970 #endif
971 return true;
972 }
973 if (blockTagList()->contains(child->tagQName().localName().impl()))
974 return true;
975 return !isRecognizedTagName(child->tagQName()); // Accept custom html tags
976 }
977
978 return false;
979 }
980
inInlineTagList(const Node * newChild)981 bool HTMLElement::inInlineTagList(const Node* newChild)
982 {
983 if (newChild->isTextNode())
984 return true;
985
986 if (newChild->isHTMLElement()) {
987 const HTMLElement* child = static_cast<const HTMLElement*>(newChild);
988 if (inlineTagList()->contains(child->tagQName().localName().impl()))
989 return true;
990 return !isRecognizedTagName(child->tagQName()); // Accept custom html tags
991 }
992
993 return false;
994 }
995
inBlockTagList(const Node * newChild)996 bool HTMLElement::inBlockTagList(const Node* newChild)
997 {
998 if (newChild->isTextNode())
999 return true;
1000
1001 if (newChild->isHTMLElement()) {
1002 const HTMLElement* child = static_cast<const HTMLElement*>(newChild);
1003 return (blockTagList()->contains(child->tagQName().localName().impl()));
1004 }
1005
1006 return false;
1007 }
1008
checkDTD(const Node * newChild)1009 bool HTMLElement::checkDTD(const Node* newChild)
1010 {
1011 if (hasLocalName(addressTag) && newChild->hasTagName(pTag))
1012 return true;
1013 return inEitherTagList(newChild);
1014 }
1015
rendererIsNeeded(RenderStyle * style)1016 bool HTMLElement::rendererIsNeeded(RenderStyle *style)
1017 {
1018 #if !ENABLE(XHTMLMP)
1019 if (hasLocalName(noscriptTag)) {
1020 Settings* settings = document()->settings();
1021 if (settings && settings->isJavaScriptEnabled())
1022 return false;
1023 }
1024 #endif
1025 return StyledElement::rendererIsNeeded(style);
1026 }
1027
createRenderer(RenderArena * arena,RenderStyle * style)1028 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
1029 {
1030 if (hasLocalName(wbrTag))
1031 return new (arena) RenderWordBreak(this);
1032 return RenderObject::createObject(this, style);
1033 }
1034
findFormAncestor() const1035 HTMLFormElement* HTMLElement::findFormAncestor() const
1036 {
1037 for (Node* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode())
1038 if (ancestor->hasTagName(formTag))
1039 return static_cast<HTMLFormElement*>(ancestor);
1040 return 0;
1041 }
1042
virtualForm() const1043 HTMLFormElement* HTMLElement::virtualForm() const
1044 {
1045 return findFormAncestor();
1046 }
1047
1048 } // namespace WebCore
1049
1050 #ifndef NDEBUG
1051
1052 // For use in the debugger
1053 void dumpInnerHTML(WebCore::HTMLElement*);
1054
dumpInnerHTML(WebCore::HTMLElement * element)1055 void dumpInnerHTML(WebCore::HTMLElement* element)
1056 {
1057 printf("%s\n", element->innerHTML().ascii().data());
1058 }
1059 #endif
1060