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->isDocumentNode()) {
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, "inherit")) {
686 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueInherit);
687 attr->decl()->removeProperty(CSSPropertyWordWrap, false);
688 attr->decl()->removeProperty(CSSPropertyWebkitNbspMode, false);
689 attr->decl()->removeProperty(CSSPropertyWebkitLineBreak, false);
690 } else if (equalIgnoringCase(enabled, "plaintext-only")) {
691 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
692 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
693 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
694 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
695 }
696 }
697
setContentEditable(const String & enabled,ExceptionCode & ec)698 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
699 {
700 if (equalIgnoringCase(enabled, "true"))
701 setAttribute(contenteditableAttr, "true", ec);
702 else if (equalIgnoringCase(enabled, "false"))
703 setAttribute(contenteditableAttr, "false", ec);
704 else if (equalIgnoringCase(enabled, "plaintext-only"))
705 setAttribute(contenteditableAttr, "plaintext-only");
706 else if (equalIgnoringCase(enabled, "inherit"))
707 removeAttribute(contenteditableAttr, ec);
708 else
709 ec = SYNTAX_ERR;
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
spellcheck() const722 bool HTMLElement::spellcheck() const
723 {
724 return isSpellCheckingEnabled();
725 }
726
setSpellcheck(bool enable)727 void HTMLElement::setSpellcheck(bool enable)
728 {
729 setAttribute(spellcheckAttr, enable ? "true" : "false");
730 }
731
732
click()733 void HTMLElement::click()
734 {
735 dispatchSimulatedClick(0, false, false);
736 }
737
738 // accessKeyAction is used by the accessibility support code
739 // to send events to elements that our JavaScript caller does
740 // does not. The elements JS is interested in have subclasses
741 // that override this method to direct the click appropriately.
742 // Here in the base class, then, we only send the click if
743 // the caller wants it to go to any HTMLElement, and we say
744 // to send the mouse events in addition to the click.
accessKeyAction(bool sendToAnyElement)745 void HTMLElement::accessKeyAction(bool sendToAnyElement)
746 {
747 if (sendToAnyElement)
748 dispatchSimulatedClick(0, true);
749 }
750
title() const751 String HTMLElement::title() const
752 {
753 return getAttribute(titleAttr);
754 }
755
tabIndex() const756 short HTMLElement::tabIndex() const
757 {
758 if (supportsFocus())
759 return Element::tabIndex();
760 return -1;
761 }
762
setTabIndex(int value)763 void HTMLElement::setTabIndex(int value)
764 {
765 setAttribute(tabindexAttr, String::number(value));
766 }
767
children()768 PassRefPtr<HTMLCollection> HTMLElement::children()
769 {
770 return HTMLCollection::create(this, NodeChildren);
771 }
772
rendererIsNeeded(RenderStyle * style)773 bool HTMLElement::rendererIsNeeded(RenderStyle *style)
774 {
775 if (hasLocalName(noscriptTag)) {
776 Frame* frame = document()->frame();
777 #if ENABLE(XHTMLMP)
778 if (!document()->shouldProcessNoscriptElement())
779 return false;
780 #else
781 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
782 return false;
783 #endif
784 } else if (hasLocalName(noembedTag)) {
785 Frame* frame = document()->frame();
786 if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
787 return false;
788 }
789 return StyledElement::rendererIsNeeded(style);
790 }
791
createRenderer(RenderArena * arena,RenderStyle * style)792 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
793 {
794 if (hasLocalName(wbrTag))
795 return new (arena) RenderWordBreak(this);
796 return RenderObject::createObject(this, style);
797 }
798
findFormAncestor() const799 HTMLFormElement* HTMLElement::findFormAncestor() const
800 {
801 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
802 if (ancestor->hasTagName(formTag))
803 return static_cast<HTMLFormElement*>(ancestor);
804 }
805 return 0;
806 }
807
virtualForm() const808 HTMLFormElement* HTMLElement::virtualForm() const
809 {
810 return findFormAncestor();
811 }
812
setHasDirAutoFlagRecursively(Node * firstNode,bool flag,Node * lastNode=0)813 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
814 {
815 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
816
817 Node* node = firstNode->firstChild();
818
819 while (node) {
820 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
821 return;
822
823 if (node->isHTMLElement() && toElement(node)->hasAttribute(dirAttr)) {
824 if (node == lastNode)
825 return;
826 node = node->traverseNextSibling(firstNode);
827 continue;
828 }
829 node->setSelfOrAncestorHasDirAutoAttribute(flag);
830 if (node == lastNode)
831 return;
832 node = node->traverseNextNode(firstNode);
833 }
834 }
835
childrenChanged(bool changedByParser,Node * beforeChange,Node * afterChange,int childCountDelta)836 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
837 {
838 StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
839 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
840 }
841
directionalityIfhasDirAutoAttribute(bool & isAuto) const842 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
843 {
844 if (!(selfOrAncestorHasDirAutoAttribute() && equalIgnoringCase(getAttribute(dirAttr), "auto"))) {
845 isAuto = false;
846 return LTR;
847 }
848
849 isAuto = true;
850 return directionality();
851 }
852
directionality(Node ** strongDirectionalityTextNode) const853 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
854 {
855 Node* node = firstChild();
856 while (node) {
857 // Skip bdi, script and style elements
858 if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)) {
859 node = node->traverseNextSibling(this);
860 continue;
861 }
862
863 // Skip elements with valid dir attribute
864 if (node->isElementNode()) {
865 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
866 if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
867 node = node->traverseNextSibling(this);
868 continue;
869 }
870 }
871
872 if (node->isTextNode()) {
873 bool hasStrongDirectionality;
874 WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
875 if (hasStrongDirectionality) {
876 if (strongDirectionalityTextNode)
877 *strongDirectionalityTextNode = node;
878 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
879 }
880 }
881 node = node->traverseNextNode(this);
882 }
883 if (strongDirectionalityTextNode)
884 *strongDirectionalityTextNode = 0;
885 return LTR;
886 }
887
dirAttributeChanged(Attribute * attribute)888 void HTMLElement::dirAttributeChanged(Attribute* attribute)
889 {
890 Element* parent = parentElement();
891
892 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
893 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
894
895 if (equalIgnoringCase(attribute->value(), "auto"))
896 calculateAndAdjustDirectionality();
897 }
898
adjustDirectionalityIfNeededAfterChildAttributeChanged(Element * child)899 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
900 {
901 ASSERT(selfOrAncestorHasDirAutoAttribute());
902 Node* strongDirectionalityTextNode;
903 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
904 setHasDirAutoFlagRecursively(child, false);
905 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
906 Element* elementToAdjust = this;
907 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
908 if (elementToAdjust->hasAttribute(dirAttr)) {
909 elementToAdjust->setNeedsStyleRecalc();
910 return;
911 }
912 }
913 }
914 }
915
calculateAndAdjustDirectionality()916 void HTMLElement::calculateAndAdjustDirectionality()
917 {
918 Node* strongDirectionalityTextNode;
919 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
920 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
921 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
922 setNeedsStyleRecalc();
923 }
924
adjustDirectionalityIfNeededAfterChildrenChanged(Node * beforeChange,int childCountDelta)925 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
926 {
927 if ((!document() || document()->renderer()) && childCountDelta < 0) {
928 Node* node = beforeChange ? beforeChange->traverseNextSibling() : 0;
929 for (int counter = 0; node && counter < childCountDelta; counter++, node = node->traverseNextSibling()) {
930 if (node->isElementNode() && toElement(node)->hasAttribute(dirAttr))
931 continue;
932
933 setHasDirAutoFlagRecursively(node, false);
934 }
935 }
936
937 if (!selfOrAncestorHasDirAutoAttribute())
938 return;
939
940 Node* oldMarkedNode = beforeChange ? beforeChange->traverseNextSibling() : 0;
941 while (oldMarkedNode && oldMarkedNode->isHTMLElement() && toHTMLElement(oldMarkedNode)->hasAttribute(dirAttr))
942 oldMarkedNode = oldMarkedNode->traverseNextSibling(this);
943 if (oldMarkedNode)
944 setHasDirAutoFlagRecursively(oldMarkedNode, false);
945
946 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
947 if (elementToAdjust->isHTMLElement() && elementToAdjust->hasAttribute(dirAttr)) {
948 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
949 return;
950 }
951 }
952 }
953
954 } // namespace WebCore
955
956 #ifndef NDEBUG
957
958 // For use in the debugger
959 void dumpInnerHTML(WebCore::HTMLElement*);
960
dumpInnerHTML(WebCore::HTMLElement * element)961 void dumpInnerHTML(WebCore::HTMLElement* element)
962 {
963 printf("%s\n", element->innerHTML().ascii().data());
964 }
965 #endif
966