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