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 "Attribute.h"
28 #include "CSSPropertyNames.h"
29 #include "CSSValueKeywords.h"
30 #include "DocumentFragment.h"
31 #include "Event.h"
32 #include "EventListener.h"
33 #include "EventNames.h"
34 #include "ExceptionCode.h"
35 #include "Frame.h"
36 #include "HTMLBRElement.h"
37 #include "HTMLCollection.h"
38 #include "HTMLDocument.h"
39 #include "HTMLElementFactory.h"
40 #include "HTMLFormElement.h"
41 #include "HTMLNames.h"
42 #include "HTMLParserIdioms.h"
43 #include "RenderWordBreak.h"
44 #include "ScriptEventListener.h"
45 #include "Settings.h"
46 #include "Text.h"
47 #include "TextIterator.h"
48 #include "markup.h"
49 #include <wtf/StdLibExtras.h>
50 #include <wtf/text/CString.h>
51
52 namespace WebCore {
53
54 using namespace HTMLNames;
55
56 using std::min;
57 using std::max;
58
create(const QualifiedName & tagName,Document * document)59 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
60 {
61 return adoptRef(new HTMLElement(tagName, document));
62 }
63
nodeName() const64 String HTMLElement::nodeName() const
65 {
66 // FIXME: Would be nice to have an atomicstring lookup based off uppercase
67 // chars that does not have to copy the string on a hit in the hash.
68 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
69 if (document()->isHTMLDocument() && !tagQName().hasPrefix())
70 return tagQName().localNameUpper();
71 return Element::nodeName();
72 }
73
ieForbidsInsertHTML() const74 bool HTMLElement::ieForbidsInsertHTML() const
75 {
76 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
77 // and createContextualFragment on these tags. We have no tests to
78 // verify this however, so this list could be totally wrong.
79 // This list was moved from the previous endTagRequirement() implementation.
80 // This is also called from editing and assumed to be the list of tags
81 // for which no end tag should be serialized. It's unclear if the list for
82 // IE compat and the list for serialization sanity are the same.
83 if (hasLocalName(areaTag)
84 || hasLocalName(baseTag)
85 || hasLocalName(basefontTag)
86 || hasLocalName(brTag)
87 || hasLocalName(colTag)
88 || hasLocalName(embedTag)
89 || hasLocalName(frameTag)
90 || hasLocalName(hrTag)
91 || hasLocalName(imageTag)
92 || hasLocalName(imgTag)
93 || hasLocalName(inputTag)
94 || hasLocalName(isindexTag)
95 || hasLocalName(linkTag)
96 || hasLocalName(metaTag)
97 || hasLocalName(paramTag)
98 || hasLocalName(sourceTag)
99 || hasLocalName(wbrTag))
100 return true;
101 // FIXME: I'm not sure why dashboard mode would want to change the
102 // serialization of <canvas>, that seems like a bad idea.
103 #if ENABLE(DASHBOARD_SUPPORT)
104 if (hasLocalName(canvasTag)) {
105 Settings* settings = document()->settings();
106 if (settings && settings->usesDashboardBackwardCompatibilityMode())
107 return true;
108 }
109 #endif
110 return false;
111 }
112
mapToEntry(const QualifiedName & attrName,MappedAttributeEntry & result) const113 bool HTMLElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
114 {
115 if (attrName == alignAttr
116 || attrName == contenteditableAttr
117 || attrName == hiddenAttr) {
118 result = eUniversal;
119 return false;
120 }
121 if (attrName == dirAttr) {
122 result = hasLocalName(bdoTag) ? eBDO : eUniversal;
123 return true;
124 }
125
126 return StyledElement::mapToEntry(attrName, result);
127 }
128
parseMappedAttribute(Attribute * attr)129 void HTMLElement::parseMappedAttribute(Attribute* attr)
130 {
131 if (isIdAttributeName(attr->name()) || attr->name() == classAttr || attr->name() == styleAttr)
132 return StyledElement::parseMappedAttribute(attr);
133
134 String indexstring;
135 if (attr->name() == alignAttr) {
136 if (equalIgnoringCase(attr->value(), "middle"))
137 addCSSProperty(attr, CSSPropertyTextAlign, "center");
138 else
139 addCSSProperty(attr, CSSPropertyTextAlign, attr->value());
140 } else if (attr->name() == contenteditableAttr) {
141 setContentEditable(attr);
142 } else if (attr->name() == hiddenAttr) {
143 addCSSProperty(attr, CSSPropertyDisplay, CSSValueNone);
144 } else if (attr->name() == tabindexAttr) {
145 indexstring = getAttribute(tabindexAttr);
146 int tabindex = 0;
147 if (!indexstring.length()) {
148 clearTabIndexExplicitly();
149 } else if (parseHTMLInteger(indexstring, tabindex)) {
150 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
151 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
152 }
153 } else if (attr->name() == langAttr) {
154 // FIXME: Implement
155 } else if (attr->name() == dirAttr) {
156 if (!equalIgnoringCase(attr->value(), "auto"))
157 addCSSProperty(attr, CSSPropertyDirection, attr->value());
158 dirAttributeChanged(attr);
159 addCSSProperty(attr, CSSPropertyUnicodeBidi, hasLocalName(bdoTag) ? CSSValueBidiOverride : CSSValueEmbed);
160 } else if (attr->name() == draggableAttr) {
161 const AtomicString& value = attr->value();
162 if (equalIgnoringCase(value, "true")) {
163 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueElement);
164 addCSSProperty(attr, CSSPropertyWebkitUserSelect, CSSValueNone);
165 } else if (equalIgnoringCase(value, "false"))
166 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueNone);
167 }
168 // standard events
169 else if (attr->name() == onclickAttr) {
170 setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attr));
171 } else if (attr->name() == oncontextmenuAttr) {
172 setAttributeEventListener(eventNames().contextmenuEvent, createAttributeEventListener(this, attr));
173 } else if (attr->name() == ondblclickAttr) {
174 setAttributeEventListener(eventNames().dblclickEvent, createAttributeEventListener(this, attr));
175 } else if (attr->name() == onmousedownAttr) {
176 setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, attr));
177 } else if (attr->name() == onmousemoveAttr) {
178 setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, attr));
179 } else if (attr->name() == onmouseoutAttr) {
180 setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, attr));
181 } else if (attr->name() == onmouseoverAttr) {
182 setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, attr));
183 } else if (attr->name() == onmouseupAttr) {
184 setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, attr));
185 } else if (attr->name() == onmousewheelAttr) {
186 setAttributeEventListener(eventNames().mousewheelEvent, createAttributeEventListener(this, attr));
187 } else if (attr->name() == onfocusAttr) {
188 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
189 } else if (attr->name() == onfocusinAttr) {
190 setAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(this, attr));
191 } else if (attr->name() == onfocusoutAttr) {
192 setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, attr));
193 } else if (attr->name() == onblurAttr) {
194 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
195 } else if (attr->name() == onkeydownAttr) {
196 setAttributeEventListener(eventNames().keydownEvent, createAttributeEventListener(this, attr));
197 } else if (attr->name() == onkeypressAttr) {
198 setAttributeEventListener(eventNames().keypressEvent, createAttributeEventListener(this, attr));
199 } else if (attr->name() == onkeyupAttr) {
200 setAttributeEventListener(eventNames().keyupEvent, createAttributeEventListener(this, attr));
201 } else if (attr->name() == onscrollAttr) {
202 setAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(this, attr));
203 } else if (attr->name() == onbeforecutAttr) {
204 setAttributeEventListener(eventNames().beforecutEvent, createAttributeEventListener(this, attr));
205 } else if (attr->name() == oncutAttr) {
206 setAttributeEventListener(eventNames().cutEvent, createAttributeEventListener(this, attr));
207 } else if (attr->name() == onbeforecopyAttr) {
208 setAttributeEventListener(eventNames().beforecopyEvent, createAttributeEventListener(this, attr));
209 } else if (attr->name() == oncopyAttr) {
210 setAttributeEventListener(eventNames().copyEvent, createAttributeEventListener(this, attr));
211 } else if (attr->name() == onbeforepasteAttr) {
212 setAttributeEventListener(eventNames().beforepasteEvent, createAttributeEventListener(this, attr));
213 } else if (attr->name() == onpasteAttr) {
214 setAttributeEventListener(eventNames().pasteEvent, createAttributeEventListener(this, attr));
215 } else if (attr->name() == ondragenterAttr) {
216 setAttributeEventListener(eventNames().dragenterEvent, createAttributeEventListener(this, attr));
217 } else if (attr->name() == ondragoverAttr) {
218 setAttributeEventListener(eventNames().dragoverEvent, createAttributeEventListener(this, attr));
219 } else if (attr->name() == ondragleaveAttr) {
220 setAttributeEventListener(eventNames().dragleaveEvent, createAttributeEventListener(this, attr));
221 } else if (attr->name() == ondropAttr) {
222 setAttributeEventListener(eventNames().dropEvent, createAttributeEventListener(this, attr));
223 } else if (attr->name() == ondragstartAttr) {
224 setAttributeEventListener(eventNames().dragstartEvent, createAttributeEventListener(this, attr));
225 } else if (attr->name() == ondragAttr) {
226 setAttributeEventListener(eventNames().dragEvent, createAttributeEventListener(this, attr));
227 } else if (attr->name() == ondragendAttr) {
228 setAttributeEventListener(eventNames().dragendEvent, createAttributeEventListener(this, attr));
229 } else if (attr->name() == onselectstartAttr) {
230 setAttributeEventListener(eventNames().selectstartEvent, createAttributeEventListener(this, attr));
231 } else if (attr->name() == onsubmitAttr) {
232 setAttributeEventListener(eventNames().submitEvent, createAttributeEventListener(this, attr));
233 } else if (attr->name() == onerrorAttr) {
234 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attr));
235 } else if (attr->name() == onwebkitanimationstartAttr) {
236 setAttributeEventListener(eventNames().webkitAnimationStartEvent, createAttributeEventListener(this, attr));
237 } else if (attr->name() == onwebkitanimationiterationAttr) {
238 setAttributeEventListener(eventNames().webkitAnimationIterationEvent, createAttributeEventListener(this, attr));
239 } else if (attr->name() == onwebkitanimationendAttr) {
240 setAttributeEventListener(eventNames().webkitAnimationEndEvent, createAttributeEventListener(this, attr));
241 } else if (attr->name() == onwebkittransitionendAttr) {
242 setAttributeEventListener(eventNames().webkitTransitionEndEvent, createAttributeEventListener(this, attr));
243 } else if (attr->name() == oninputAttr) {
244 setAttributeEventListener(eventNames().inputEvent, createAttributeEventListener(this, attr));
245 } else if (attr->name() == oninvalidAttr) {
246 setAttributeEventListener(eventNames().invalidEvent, createAttributeEventListener(this, attr));
247 } else if (attr->name() == ontouchstartAttr) {
248 setAttributeEventListener(eventNames().touchstartEvent, createAttributeEventListener(this, attr));
249 } else if (attr->name() == ontouchmoveAttr) {
250 setAttributeEventListener(eventNames().touchmoveEvent, createAttributeEventListener(this, attr));
251 } else if (attr->name() == ontouchendAttr) {
252 setAttributeEventListener(eventNames().touchendEvent, createAttributeEventListener(this, attr));
253 } else if (attr->name() == ontouchcancelAttr) {
254 setAttributeEventListener(eventNames().touchcancelEvent, createAttributeEventListener(this, attr));
255 #if ENABLE(FULLSCREEN_API)
256 } else if (attr->name() == onwebkitfullscreenchangeAttr) {
257 setAttributeEventListener(eventNames().webkitfullscreenchangeEvent, createAttributeEventListener(this, attr));
258 #endif
259 }
260 }
261
innerHTML() const262 String HTMLElement::innerHTML() const
263 {
264 return createMarkup(this, ChildrenOnly);
265 }
266
outerHTML() const267 String HTMLElement::outerHTML() const
268 {
269 return createMarkup(this);
270 }
271
272 // FIXME: This logic should move into Range::createContextualFragment
deprecatedCreateContextualFragment(const String & markup,FragmentScriptingPermission scriptingPermission)273 PassRefPtr<DocumentFragment> HTMLElement::deprecatedCreateContextualFragment(const String& markup, FragmentScriptingPermission scriptingPermission)
274 {
275 // The following is in accordance with the definition as used by IE.
276 if (ieForbidsInsertHTML())
277 return 0;
278
279 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag)
280 || hasLocalName(headTag) || hasLocalName(styleTag) || hasLocalName(titleTag))
281 return 0;
282
283 return Element::deprecatedCreateContextualFragment(markup, scriptingPermission);
284 }
285
hasOneChild(ContainerNode * node)286 static inline bool hasOneChild(ContainerNode* node)
287 {
288 Node* firstChild = node->firstChild();
289 return firstChild && !firstChild->nextSibling();
290 }
291
hasOneTextChild(ContainerNode * node)292 static inline bool hasOneTextChild(ContainerNode* node)
293 {
294 return hasOneChild(node) && node->firstChild()->isTextNode();
295 }
296
replaceChildrenWithFragment(HTMLElement * element,PassRefPtr<DocumentFragment> fragment,ExceptionCode & ec)297 static void replaceChildrenWithFragment(HTMLElement* element, PassRefPtr<DocumentFragment> fragment, ExceptionCode& ec)
298 {
299 if (!fragment->firstChild()) {
300 element->removeChildren();
301 return;
302 }
303
304 if (hasOneTextChild(element) && hasOneTextChild(fragment.get())) {
305 static_cast<Text*>(element->firstChild())->setData(static_cast<Text*>(fragment->firstChild())->data(), ec);
306 return;
307 }
308
309 if (hasOneChild(element)) {
310 element->replaceChild(fragment, element->firstChild(), ec);
311 return;
312 }
313
314 element->removeChildren();
315 element->appendChild(fragment, ec);
316 }
317
replaceChildrenWithText(HTMLElement * element,const String & text,ExceptionCode & ec)318 static void replaceChildrenWithText(HTMLElement* element, const String& text, ExceptionCode& ec)
319 {
320 if (hasOneTextChild(element)) {
321 static_cast<Text*>(element->firstChild())->setData(text, ec);
322 return;
323 }
324
325 RefPtr<Text> textNode = Text::create(element->document(), text);
326
327 if (hasOneChild(element)) {
328 element->replaceChild(textNode.release(), element->firstChild(), ec);
329 return;
330 }
331
332 element->removeChildren();
333 element->appendChild(textNode.release(), ec);
334 }
335
336 // We may want to move a version of this function into DocumentFragment.h/cpp
createFragmentFromSource(const String & markup,Element * contextElement,ExceptionCode & ec)337 static PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
338 {
339 Document* document = contextElement->document();
340 RefPtr<DocumentFragment> fragment;
341
342 fragment = DocumentFragment::create(document);
343 if (document->isHTMLDocument()) {
344 fragment->parseHTML(markup, contextElement);
345 return fragment;
346 }
347
348 bool wasValid = fragment->parseXML(markup, contextElement);
349 if (!wasValid) {
350 ec = INVALID_STATE_ERR;
351 return 0;
352 }
353 return fragment;
354 }
355
setInnerHTML(const String & html,ExceptionCode & ec)356 void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec)
357 {
358 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, this, ec);
359 if (fragment)
360 replaceChildrenWithFragment(this, fragment.release(), ec);
361 }
362
mergeWithNextTextNode(PassRefPtr<Node> node,ExceptionCode & ec)363 static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionCode& ec)
364 {
365 ASSERT(node && node->isTextNode());
366 Node* next = node->nextSibling();
367 if (!next || !next->isTextNode())
368 return;
369
370 RefPtr<Text> textNode = static_cast<Text*>(node.get());
371 RefPtr<Text> textNext = static_cast<Text*>(next);
372 textNode->appendData(textNext->data(), ec);
373 if (ec)
374 return;
375 if (textNext->parentNode()) // Might have been removed by mutation event.
376 textNext->remove(ec);
377 }
378
setOuterHTML(const String & html,ExceptionCode & ec)379 void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
380 {
381 Node* p = parentNode();
382 if (!p || !p->isHTMLElement()) {
383 ec = NO_MODIFICATION_ALLOWED_ERR;
384 return;
385 }
386 RefPtr<HTMLElement> parent = static_cast<HTMLElement*>(p);
387 RefPtr<Node> prev = previousSibling();
388 RefPtr<Node> next = nextSibling();
389
390 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, parent.get(), ec);
391 if (ec)
392 return;
393
394 parent->replaceChild(fragment.release(), this, ec);
395 RefPtr<Node> node = next ? next->previousSibling() : 0;
396 if (!ec && node && node->isTextNode())
397 mergeWithNextTextNode(node.release(), ec);
398
399 if (!ec && prev && prev->isTextNode())
400 mergeWithNextTextNode(prev.release(), ec);
401 }
402
textToFragment(const String & text,ExceptionCode & ec)403 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionCode& ec)
404 {
405 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
406 unsigned int i, length = text.length();
407 UChar c = 0;
408 for (unsigned int start = 0; start < length; ) {
409
410 // Find next line break.
411 for (i = start; i < length; i++) {
412 c = text[i];
413 if (c == '\r' || c == '\n')
414 break;
415 }
416
417 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), ec);
418 if (ec)
419 return 0;
420
421 if (c == '\r' || c == '\n') {
422 fragment->appendChild(HTMLBRElement::create(document()), ec);
423 if (ec)
424 return 0;
425 // Make sure \r\n doesn't result in two line breaks.
426 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
427 i++;
428 }
429
430 start = i + 1; // Character after line break.
431 }
432
433 return fragment;
434 }
435
setInnerText(const String & text,ExceptionCode & ec)436 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
437 {
438 if (ieForbidsInsertHTML()) {
439 ec = NO_MODIFICATION_ALLOWED_ERR;
440 return;
441 }
442 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
443 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
444 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
445 hasLocalName(trTag)) {
446 ec = NO_MODIFICATION_ALLOWED_ERR;
447 return;
448 }
449
450 // FIXME: This doesn't take whitespace collapsing into account at all.
451
452 if (!text.contains('\n') && !text.contains('\r')) {
453 if (text.isEmpty()) {
454 removeChildren();
455 return;
456 }
457 replaceChildrenWithText(this, text, ec);
458 return;
459 }
460
461 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
462 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
463 // For example, for the contents of textarea elements that are display:none?
464 RenderObject* r = renderer();
465 if (r && r->style()->preserveNewline()) {
466 if (!text.contains('\r')) {
467 replaceChildrenWithText(this, text, ec);
468 return;
469 }
470 String textWithConsistentLineBreaks = text;
471 textWithConsistentLineBreaks.replace("\r\n", "\n");
472 textWithConsistentLineBreaks.replace('\r', '\n');
473 replaceChildrenWithText(this, textWithConsistentLineBreaks, ec);
474 return;
475 }
476
477 // Add text nodes and <br> elements.
478 ec = 0;
479 RefPtr<DocumentFragment> fragment = textToFragment(text, ec);
480 if (!ec)
481 replaceChildrenWithFragment(this, fragment.release(), ec);
482 }
483
setOuterText(const String & text,ExceptionCode & ec)484 void HTMLElement::setOuterText(const String &text, ExceptionCode& ec)
485 {
486 if (ieForbidsInsertHTML()) {
487 ec = NO_MODIFICATION_ALLOWED_ERR;
488 return;
489 }
490 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
491 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
492 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
493 hasLocalName(trTag)) {
494 ec = NO_MODIFICATION_ALLOWED_ERR;
495 return;
496 }
497
498 ContainerNode* parent = parentNode();
499 if (!parent) {
500 ec = NO_MODIFICATION_ALLOWED_ERR;
501 return;
502 }
503
504 RefPtr<Node> prev = previousSibling();
505 RefPtr<Node> next = nextSibling();
506 RefPtr<Node> newChild;
507 ec = 0;
508
509 // Convert text to fragment with <br> tags instead of linebreaks if needed.
510 if (text.contains('\r') || text.contains('\n'))
511 newChild = textToFragment(text, ec);
512 else
513 newChild = Text::create(document(), text);
514
515 if (!this || !parentNode())
516 ec = HIERARCHY_REQUEST_ERR;
517 if (ec)
518 return;
519 parent->replaceChild(newChild.release(), this, ec);
520
521 RefPtr<Node> node = next ? next->previousSibling() : 0;
522 if (!ec && node && node->isTextNode())
523 mergeWithNextTextNode(node.release(), ec);
524
525 if (!ec && prev && prev->isTextNode())
526 mergeWithNextTextNode(prev.release(), ec);
527 }
528
insertAdjacent(const String & where,Node * newChild,ExceptionCode & ec)529 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionCode& ec)
530 {
531 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
532 // a document fragment is created and the elements appended in the correct order. This document
533 // fragment isn't returned anywhere.
534 //
535 // This is impossible for us to implement as the DOM tree does not allow for such structures,
536 // Opera also appears to disallow such usage.
537
538 if (equalIgnoringCase(where, "beforeBegin")) {
539 ContainerNode* parent = this->parentNode();
540 return (parent && parent->insertBefore(newChild, this, ec)) ? newChild : 0;
541 }
542
543 if (equalIgnoringCase(where, "afterBegin"))
544 return insertBefore(newChild, firstChild(), ec) ? newChild : 0;
545
546 if (equalIgnoringCase(where, "beforeEnd"))
547 return appendChild(newChild, ec) ? newChild : 0;
548
549 if (equalIgnoringCase(where, "afterEnd")) {
550 ContainerNode* parent = this->parentNode();
551 return (parent && parent->insertBefore(newChild, nextSibling(), ec)) ? newChild : 0;
552 }
553
554 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
555 ec = NOT_SUPPORTED_ERR;
556 return 0;
557 }
558
insertAdjacentElement(const String & where,Element * newChild,ExceptionCode & ec)559 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
560 {
561 if (!newChild) {
562 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
563 ec = TYPE_MISMATCH_ERR;
564 return 0;
565 }
566
567 Node* returnValue = insertAdjacent(where, newChild, ec);
568 ASSERT(!returnValue || returnValue->isElementNode());
569 return static_cast<Element*>(returnValue);
570 }
571
572 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
contextElementForInsertion(const String & where,Element * element,ExceptionCode & ec)573 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionCode& ec)
574 {
575 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
576 ContainerNode* parent = element->parentNode();
577 if (parent && parent->isDocumentNode()) {
578 ec = NO_MODIFICATION_ALLOWED_ERR;
579 return 0;
580 }
581 ASSERT(!parent || parent->isElementNode());
582 return static_cast<Element*>(parent);
583 }
584 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
585 return element;
586 ec = SYNTAX_ERR;
587 return 0;
588 }
589
insertAdjacentHTML(const String & where,const String & markup,ExceptionCode & ec)590 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec)
591 {
592 RefPtr<DocumentFragment> fragment = document()->createDocumentFragment();
593 Element* contextElement = contextElementForInsertion(where, this, ec);
594 if (!contextElement)
595 return;
596
597 if (document()->isHTMLDocument())
598 fragment->parseHTML(markup, contextElement);
599 else {
600 if (!fragment->parseXML(markup, contextElement))
601 // FIXME: We should propagate a syntax error exception out here.
602 return;
603 }
604
605 insertAdjacent(where, fragment.get(), ec);
606 }
607
insertAdjacentText(const String & where,const String & text,ExceptionCode & ec)608 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
609 {
610 RefPtr<Text> textNode = document()->createTextNode(text);
611 insertAdjacent(where, textNode.get(), ec);
612 }
613
addHTMLAlignment(Attribute * attr)614 void HTMLElement::addHTMLAlignment(Attribute* attr)
615 {
616 addHTMLAlignmentToStyledElement(this, attr);
617 }
618
addHTMLAlignmentToStyledElement(StyledElement * element,Attribute * attr)619 void HTMLElement::addHTMLAlignmentToStyledElement(StyledElement* element, Attribute* attr)
620 {
621 // Vertical alignment with respect to the current baseline of the text
622 // right or left means floating images.
623 int floatValue = CSSValueInvalid;
624 int verticalAlignValue = CSSValueInvalid;
625
626 const AtomicString& alignment = attr->value();
627 if (equalIgnoringCase(alignment, "absmiddle"))
628 verticalAlignValue = CSSValueMiddle;
629 else if (equalIgnoringCase(alignment, "absbottom"))
630 verticalAlignValue = CSSValueBottom;
631 else if (equalIgnoringCase(alignment, "left")) {
632 floatValue = CSSValueLeft;
633 verticalAlignValue = CSSValueTop;
634 } else if (equalIgnoringCase(alignment, "right")) {
635 floatValue = CSSValueRight;
636 verticalAlignValue = CSSValueTop;
637 } else if (equalIgnoringCase(alignment, "top"))
638 verticalAlignValue = CSSValueTop;
639 else if (equalIgnoringCase(alignment, "middle"))
640 verticalAlignValue = CSSValueWebkitBaselineMiddle;
641 else if (equalIgnoringCase(alignment, "center"))
642 verticalAlignValue = CSSValueMiddle;
643 else if (equalIgnoringCase(alignment, "bottom"))
644 verticalAlignValue = CSSValueBaseline;
645 else if (equalIgnoringCase(alignment, "texttop"))
646 verticalAlignValue = CSSValueTextTop;
647
648 if (floatValue != CSSValueInvalid)
649 element->addCSSProperty(attr, CSSPropertyFloat, floatValue);
650
651 if (verticalAlignValue != CSSValueInvalid)
652 element->addCSSProperty(attr, CSSPropertyVerticalAlign, verticalAlignValue);
653 }
654
supportsFocus() const655 bool HTMLElement::supportsFocus() const
656 {
657 return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable());
658 }
659
contentEditable() const660 String HTMLElement::contentEditable() const
661 {
662 const AtomicString& value = fastGetAttribute(contenteditableAttr);
663
664 if (value.isNull())
665 return "inherit";
666 if (value.isEmpty() || equalIgnoringCase(value, "true"))
667 return "true";
668 if (equalIgnoringCase(value, "false"))
669 return "false";
670 if (equalIgnoringCase(value, "plaintext-only"))
671 return "plaintext-only";
672
673 return "inherit";
674 }
675
setContentEditable(Attribute * attr)676 void HTMLElement::setContentEditable(Attribute* 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, "plaintext-only")) {
690 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
691 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
692 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
693 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
694 }
695 }
696
setContentEditable(const String & enabled,ExceptionCode & ec)697 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
698 {
699 if (equalIgnoringCase(enabled, "true"))
700 setAttribute(contenteditableAttr, "true", ec);
701 else if (equalIgnoringCase(enabled, "false"))
702 setAttribute(contenteditableAttr, "false", ec);
703 else if (equalIgnoringCase(enabled, "plaintext-only"))
704 setAttribute(contenteditableAttr, "plaintext-only");
705 else if (equalIgnoringCase(enabled, "inherit"))
706 removeAttribute(contenteditableAttr, ec);
707 else
708 ec = SYNTAX_ERR;
709 }
710
draggable() const711 bool HTMLElement::draggable() const
712 {
713 return equalIgnoringCase(getAttribute(draggableAttr), "true");
714 }
715
setDraggable(bool value)716 void HTMLElement::setDraggable(bool value)
717 {
718 setAttribute(draggableAttr, value ? "true" : "false");
719 }
720
spellcheck() const721 bool HTMLElement::spellcheck() const
722 {
723 return isSpellCheckingEnabled();
724 }
725
setSpellcheck(bool enable)726 void HTMLElement::setSpellcheck(bool enable)
727 {
728 setAttribute(spellcheckAttr, enable ? "true" : "false");
729 }
730
731
click()732 void HTMLElement::click()
733 {
734 dispatchSimulatedClick(0, false, false);
735 }
736
737 // accessKeyAction is used by the accessibility support code
738 // to send events to elements that our JavaScript caller does
739 // does not. The elements JS is interested in have subclasses
740 // that override this method to direct the click appropriately.
741 // Here in the base class, then, we only send the click if
742 // the caller wants it to go to any HTMLElement, and we say
743 // to send the mouse events in addition to the click.
accessKeyAction(bool sendToAnyElement)744 void HTMLElement::accessKeyAction(bool sendToAnyElement)
745 {
746 if (sendToAnyElement)
747 dispatchSimulatedClick(0, true);
748 }
749
title() const750 String HTMLElement::title() const
751 {
752 return getAttribute(titleAttr);
753 }
754
tabIndex() const755 short HTMLElement::tabIndex() const
756 {
757 if (supportsFocus())
758 return Element::tabIndex();
759 return -1;
760 }
761
setTabIndex(int value)762 void HTMLElement::setTabIndex(int value)
763 {
764 setAttribute(tabindexAttr, String::number(value));
765 }
766
children()767 PassRefPtr<HTMLCollection> HTMLElement::children()
768 {
769 return HTMLCollection::create(this, NodeChildren);
770 }
771
rendererIsNeeded(RenderStyle * style)772 bool HTMLElement::rendererIsNeeded(RenderStyle *style)
773 {
774 if (hasLocalName(noscriptTag)) {
775 Frame* frame = document()->frame();
776 #if ENABLE(XHTMLMP)
777 if (!document()->shouldProcessNoscriptElement())
778 return false;
779 #else
780 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
781 return false;
782 #endif
783 } else if (hasLocalName(noembedTag)) {
784 Frame* frame = document()->frame();
785 if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
786 return false;
787 }
788 return StyledElement::rendererIsNeeded(style);
789 }
790
createRenderer(RenderArena * arena,RenderStyle * style)791 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
792 {
793 if (hasLocalName(wbrTag))
794 return new (arena) RenderWordBreak(this);
795 return RenderObject::createObject(this, style);
796 }
797
findFormAncestor() const798 HTMLFormElement* HTMLElement::findFormAncestor() const
799 {
800 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
801 if (ancestor->hasTagName(formTag))
802 return static_cast<HTMLFormElement*>(ancestor);
803 }
804 return 0;
805 }
806
virtualForm() const807 HTMLFormElement* HTMLElement::virtualForm() const
808 {
809 return findFormAncestor();
810 }
811
setHasDirAutoFlagRecursively(Node * firstNode,bool flag,Node * lastNode=0)812 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
813 {
814 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
815
816 Node* node = firstNode->firstChild();
817
818 while (node) {
819 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
820 return;
821
822 if (node->isHTMLElement() && toElement(node)->hasAttribute(dirAttr)) {
823 if (node == lastNode)
824 return;
825 node = node->traverseNextSibling(firstNode);
826 continue;
827 }
828 node->setSelfOrAncestorHasDirAutoAttribute(flag);
829 if (node == lastNode)
830 return;
831 node = node->traverseNextNode(firstNode);
832 }
833 }
834
childrenChanged(bool changedByParser,Node * beforeChange,Node * afterChange,int childCountDelta)835 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
836 {
837 StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
838 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
839 }
840
directionalityIfhasDirAutoAttribute(bool & isAuto) const841 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
842 {
843 if (!(selfOrAncestorHasDirAutoAttribute() && equalIgnoringCase(getAttribute(dirAttr), "auto"))) {
844 isAuto = false;
845 return LTR;
846 }
847
848 isAuto = true;
849 return directionality();
850 }
851
directionality(Node ** strongDirectionalityTextNode) const852 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
853 {
854 Node* node = firstChild();
855 while (node) {
856 // Skip bdi, script and style elements
857 if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)) {
858 node = node->traverseNextSibling(this);
859 continue;
860 }
861
862 // Skip elements with valid dir attribute
863 if (node->isElementNode()) {
864 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
865 if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
866 node = node->traverseNextSibling(this);
867 continue;
868 }
869 }
870
871 if (node->isTextNode()) {
872 bool hasStrongDirectionality;
873 WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
874 if (hasStrongDirectionality) {
875 if (strongDirectionalityTextNode)
876 *strongDirectionalityTextNode = node;
877 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
878 }
879 }
880 node = node->traverseNextNode(this);
881 }
882 if (strongDirectionalityTextNode)
883 *strongDirectionalityTextNode = 0;
884 return LTR;
885 }
886
dirAttributeChanged(Attribute * attribute)887 void HTMLElement::dirAttributeChanged(Attribute* attribute)
888 {
889 Element* parent = parentElement();
890
891 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
892 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
893
894 if (equalIgnoringCase(attribute->value(), "auto"))
895 calculateAndAdjustDirectionality();
896 }
897
adjustDirectionalityIfNeededAfterChildAttributeChanged(Element * child)898 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
899 {
900 ASSERT(selfOrAncestorHasDirAutoAttribute());
901 Node* strongDirectionalityTextNode;
902 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
903 setHasDirAutoFlagRecursively(child, false);
904 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
905 Element* elementToAdjust = this;
906 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
907 if (elementToAdjust->hasAttribute(dirAttr)) {
908 elementToAdjust->setNeedsStyleRecalc();
909 return;
910 }
911 }
912 }
913 }
914
calculateAndAdjustDirectionality()915 void HTMLElement::calculateAndAdjustDirectionality()
916 {
917 Node* strongDirectionalityTextNode;
918 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
919 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
920 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
921 setNeedsStyleRecalc();
922 }
923
adjustDirectionalityIfNeededAfterChildrenChanged(Node * beforeChange,int childCountDelta)924 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
925 {
926 if ((!document() || document()->renderer()) && childCountDelta < 0) {
927 Node* node = beforeChange ? beforeChange->traverseNextSibling() : 0;
928 for (int counter = 0; node && counter < childCountDelta; counter++, node = node->traverseNextSibling()) {
929 if (node->isElementNode() && toElement(node)->hasAttribute(dirAttr))
930 continue;
931
932 setHasDirAutoFlagRecursively(node, false);
933 }
934 }
935
936 if (!selfOrAncestorHasDirAutoAttribute())
937 return;
938
939 Node* oldMarkedNode = beforeChange ? beforeChange->traverseNextSibling() : 0;
940 while (oldMarkedNode && oldMarkedNode->isHTMLElement() && toHTMLElement(oldMarkedNode)->hasAttribute(dirAttr))
941 oldMarkedNode = oldMarkedNode->traverseNextSibling(this);
942 if (oldMarkedNode)
943 setHasDirAutoFlagRecursively(oldMarkedNode, false);
944
945 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
946 if (elementToAdjust->isHTMLElement() && elementToAdjust->hasAttribute(dirAttr)) {
947 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
948 return;
949 }
950 }
951 }
952
953 } // namespace WebCore
954
955 #ifndef NDEBUG
956
957 // For use in the debugger
958 void dumpInnerHTML(WebCore::HTMLElement*);
959
dumpInnerHTML(WebCore::HTMLElement * element)960 void dumpInnerHTML(WebCore::HTMLElement* element)
961 {
962 printf("%s\n", element->innerHTML().ascii().data());
963 }
964 #endif
965