1 /* 2 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. 3 * Copyright (C) 2008, 2009, 2010, 2011 Google Inc. All rights reserved. 4 * Copyright (C) 2011 Igalia S.L. 5 * Copyright (C) 2011 Motorola Mobility. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY 17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR 20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 24 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 #include "config.h" 30 #include "core/editing/markup.h" 31 32 #include "bindings/v8/ExceptionState.h" 33 #include "core/CSSPropertyNames.h" 34 #include "core/CSSValueKeywords.h" 35 #include "core/HTMLNames.h" 36 #include "core/css/CSSPrimitiveValue.h" 37 #include "core/css/CSSValue.h" 38 #include "core/css/StylePropertySet.h" 39 #include "core/dom/CDATASection.h" 40 #include "core/dom/ChildListMutationScope.h" 41 #include "core/dom/ContextFeatures.h" 42 #include "core/dom/DocumentFragment.h" 43 #include "core/dom/ElementTraversal.h" 44 #include "core/dom/ExceptionCode.h" 45 #include "core/dom/NodeTraversal.h" 46 #include "core/dom/Range.h" 47 #include "core/editing/Editor.h" 48 #include "core/editing/MarkupAccumulator.h" 49 #include "core/editing/TextIterator.h" 50 #include "core/editing/VisibleSelection.h" 51 #include "core/editing/VisibleUnits.h" 52 #include "core/editing/htmlediting.h" 53 #include "core/frame/LocalFrame.h" 54 #include "core/html/HTMLBodyElement.h" 55 #include "core/html/HTMLElement.h" 56 #include "core/html/HTMLTableCellElement.h" 57 #include "core/html/HTMLTextFormControlElement.h" 58 #include "core/rendering/RenderObject.h" 59 #include "platform/weborigin/KURL.h" 60 #include "wtf/StdLibExtras.h" 61 #include "wtf/text/StringBuilder.h" 62 63 namespace WebCore { 64 65 using namespace HTMLNames; 66 67 static bool propertyMissingOrEqualToNone(StylePropertySet*, CSSPropertyID); 68 69 class AttributeChange { 70 ALLOW_ONLY_INLINE_ALLOCATION(); 71 public: 72 AttributeChange() 73 : m_name(nullAtom, nullAtom, nullAtom) 74 { 75 } 76 77 AttributeChange(PassRefPtrWillBeRawPtr<Element> element, const QualifiedName& name, const String& value) 78 : m_element(element), m_name(name), m_value(value) 79 { 80 } 81 82 void apply() 83 { 84 m_element->setAttribute(m_name, AtomicString(m_value)); 85 } 86 87 void trace(Visitor* visitor) 88 { 89 visitor->trace(m_element); 90 } 91 92 private: 93 RefPtrWillBeMember<Element> m_element; 94 QualifiedName m_name; 95 String m_value; 96 }; 97 98 } // namespace WebCore 99 100 WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(WebCore::AttributeChange); 101 102 namespace WebCore { 103 104 static void completeURLs(DocumentFragment& fragment, const String& baseURL) 105 { 106 WillBeHeapVector<AttributeChange> changes; 107 108 KURL parsedBaseURL(ParsedURLString, baseURL); 109 110 for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(*element, &fragment)) { 111 if (!element->hasAttributes()) 112 continue; 113 AttributeCollection attributes = element->attributes(); 114 AttributeCollection::const_iterator end = attributes.end(); 115 for (AttributeCollection::const_iterator it = attributes.begin(); it != end; ++it) { 116 if (element->isURLAttribute(*it) && !it->value().isEmpty()) 117 changes.append(AttributeChange(element, it->name(), KURL(parsedBaseURL, it->value()).string())); 118 } 119 } 120 121 size_t numChanges = changes.size(); 122 for (size_t i = 0; i < numChanges; ++i) 123 changes[i].apply(); 124 } 125 126 class StyledMarkupAccumulator FINAL : public MarkupAccumulator { 127 public: 128 enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode }; 129 130 StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node> >* nodes, EAbsoluteURLs, EAnnotateForInterchange, RawPtr<const Range>, Node* highestNodeToBeSerialized = 0); 131 Node* serializeNodes(Node* startNode, Node* pastEnd); 132 void appendString(const String& s) { return MarkupAccumulator::appendString(s); } 133 void wrapWithNode(Node&, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode); 134 void wrapWithStyleNode(StylePropertySet*, const Document&, bool isBlock = false); 135 String takeResults(); 136 137 private: 138 void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, const Document&, bool isBlock = false); 139 const String& styleNodeCloseTag(bool isBlock = false); 140 virtual void appendText(StringBuilder& out, Text&) OVERRIDE; 141 String renderedText(Node&, const Range*); 142 String stringValueForRange(const Node&, const Range*); 143 void appendElement(StringBuilder& out, Element&, bool addDisplayInline, RangeFullySelectsNode); 144 virtual void appendElement(StringBuilder& out, Element& element, Namespaces*) OVERRIDE { appendElement(out, element, false, DoesFullySelectNode); } 145 146 enum NodeTraversalMode { EmitString, DoNotEmitString }; 147 Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode); 148 149 bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; } 150 bool shouldApplyWrappingStyle(const Node& node) const 151 { 152 return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode() 153 && m_wrappingStyle && m_wrappingStyle->style(); 154 } 155 156 Vector<String> m_reversedPrecedingMarkup; 157 const EAnnotateForInterchange m_shouldAnnotate; 158 RawPtrWillBeMember<Node> m_highestNodeToBeSerialized; 159 RefPtrWillBeMember<EditingStyle> m_wrappingStyle; 160 }; 161 162 inline StyledMarkupAccumulator::StyledMarkupAccumulator(WillBeHeapVector<RawPtrWillBeMember<Node> >* nodes, EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate, RawPtr<const Range> range, Node* highestNodeToBeSerialized) 163 : MarkupAccumulator(nodes, shouldResolveURLs, range) 164 , m_shouldAnnotate(shouldAnnotate) 165 , m_highestNodeToBeSerialized(highestNodeToBeSerialized) 166 { 167 } 168 169 void StyledMarkupAccumulator::wrapWithNode(Node& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode) 170 { 171 StringBuilder markup; 172 if (node.isElementNode()) 173 appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode); 174 else 175 appendStartMarkup(markup, node, 0); 176 m_reversedPrecedingMarkup.append(markup.toString()); 177 appendEndTag(node); 178 if (m_nodes) 179 m_nodes->append(&node); 180 } 181 182 void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock) 183 { 184 StringBuilder openTag; 185 appendStyleNodeOpenTag(openTag, style, document, isBlock); 186 m_reversedPrecedingMarkup.append(openTag.toString()); 187 appendString(styleNodeCloseTag(isBlock)); 188 } 189 190 void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock) 191 { 192 // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect 193 ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect)); 194 if (isBlock) 195 out.appendLiteral("<div style=\""); 196 else 197 out.appendLiteral("<span style=\""); 198 appendAttributeValue(out, style->asText(), document.isHTMLDocument()); 199 out.appendLiteral("\">"); 200 } 201 202 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock) 203 { 204 DEFINE_STATIC_LOCAL(const String, divClose, ("</div>")); 205 DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>")); 206 return isBlock ? divClose : styleSpanClose; 207 } 208 209 String StyledMarkupAccumulator::takeResults() 210 { 211 StringBuilder result; 212 result.reserveCapacity(totalLength(m_reversedPrecedingMarkup) + length()); 213 214 for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i) 215 result.append(m_reversedPrecedingMarkup[i - 1]); 216 217 concatenateMarkup(result); 218 219 // We remove '\0' characters because they are not visibly rendered to the user. 220 return result.toString().replace(0, ""); 221 } 222 223 void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text) 224 { 225 const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag; 226 const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea; 227 if (wrappingSpan) { 228 RefPtrWillBeRawPtr<EditingStyle> wrappingStyle = m_wrappingStyle->copy(); 229 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance 230 // Make sure spans are inline style in paste side e.g. span { display: block }. 231 wrappingStyle->forceInline(); 232 // FIXME: Should this be included in forceInline? 233 wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone); 234 235 appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document()); 236 } 237 238 if (!shouldAnnotate() || parentIsTextarea) 239 MarkupAccumulator::appendText(out, text); 240 else { 241 const bool useRenderedText = !enclosingNodeWithTag(firstPositionInNode(&text), selectTag); 242 String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range); 243 StringBuilder buffer; 244 appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA); 245 out.append(convertHTMLTextToInterchangeFormat(buffer.toString(), text)); 246 } 247 248 if (wrappingSpan) 249 out.append(styleNodeCloseTag()); 250 } 251 252 String StyledMarkupAccumulator::renderedText(Node& node, const Range* range) 253 { 254 if (!node.isTextNode()) 255 return String(); 256 257 const Text& textNode = toText(node); 258 unsigned startOffset = 0; 259 unsigned endOffset = textNode.length(); 260 261 if (range && node == range->startContainer()) 262 startOffset = range->startOffset(); 263 if (range && node == range->endContainer()) 264 endOffset = range->endOffset(); 265 266 Position start = createLegacyEditingPosition(&node, startOffset); 267 Position end = createLegacyEditingPosition(&node, endOffset); 268 return plainText(Range::create(node.document(), start, end).get()); 269 } 270 271 String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range) 272 { 273 if (!range) 274 return node.nodeValue(); 275 276 String str = node.nodeValue(); 277 if (node == range->endContainer()) 278 str.truncate(range->endOffset()); 279 if (node == range->startContainer()) 280 str.remove(0, range->startOffset()); 281 return str; 282 } 283 284 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode) 285 { 286 const bool documentIsHTML = element.document().isHTMLDocument(); 287 appendOpenTag(out, element, 0); 288 289 const bool shouldAnnotateOrForceInline = element.isHTMLElement() && (shouldAnnotate() || addDisplayInline); 290 const bool shouldOverrideStyleAttr = shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element); 291 292 if (element.hasAttributes()) { 293 AttributeCollection attributes = element.attributes(); 294 AttributeCollection::const_iterator end = attributes.end(); 295 for (AttributeCollection::const_iterator it = attributes.begin(); it != end; ++it) { 296 // We'll handle the style attribute separately, below. 297 if (it->name() == styleAttr && shouldOverrideStyleAttr) 298 continue; 299 appendAttribute(out, element, *it, 0); 300 } 301 } 302 303 if (shouldOverrideStyleAttr) { 304 RefPtrWillBeRawPtr<EditingStyle> newInlineStyle = nullptr; 305 306 if (shouldApplyWrappingStyle(element)) { 307 newInlineStyle = m_wrappingStyle->copy(); 308 newInlineStyle->removePropertiesInElementDefaultStyle(&element); 309 newInlineStyle->removeStyleConflictingWithStyleOfNode(&element); 310 } else 311 newInlineStyle = EditingStyle::create(); 312 313 if (element.isStyledElement() && element.inlineStyle()) 314 newInlineStyle->overrideWithStyle(element.inlineStyle()); 315 316 if (shouldAnnotateOrForceInline) { 317 if (shouldAnnotate()) 318 newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element)); 319 320 if (addDisplayInline) 321 newInlineStyle->forceInline(); 322 323 // If the node is not fully selected by the range, then we don't want to keep styles that affect its relationship to the nodes around it 324 // only the ones that affect it and the nodes within it. 325 if (rangeFullySelectsNode == DoesNotFullySelectNode && newInlineStyle->style()) 326 newInlineStyle->style()->removeProperty(CSSPropertyFloat); 327 } 328 329 if (!newInlineStyle->isEmpty()) { 330 out.appendLiteral(" style=\""); 331 appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML); 332 out.append('\"'); 333 } 334 } 335 336 appendCloseTag(out, element); 337 } 338 339 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd) 340 { 341 if (!m_highestNodeToBeSerialized) { 342 Node* lastClosed = traverseNodesForSerialization(startNode, pastEnd, DoNotEmitString); 343 m_highestNodeToBeSerialized = lastClosed; 344 } 345 346 if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode()) 347 m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(m_highestNodeToBeSerialized->parentNode(), shouldAnnotate()); 348 349 return traverseNodesForSerialization(startNode, pastEnd, EmitString); 350 } 351 352 Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode) 353 { 354 const bool shouldEmit = traversalMode == EmitString; 355 WillBeHeapVector<RawPtrWillBeMember<Node> > ancestorsToClose; 356 Node* next; 357 Node* lastClosed = 0; 358 for (Node* n = startNode; n != pastEnd; n = next) { 359 // According to <rdar://problem/5730668>, it is possible for n to blow 360 // past pastEnd and become null here. This shouldn't be possible. 361 // This null check will prevent crashes (but create too much markup) 362 // and the ASSERT will hopefully lead us to understanding the problem. 363 ASSERT(n); 364 if (!n) 365 break; 366 367 next = NodeTraversal::next(*n); 368 bool openedTag = false; 369 370 if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd) 371 // Don't write out empty block containers that aren't fully selected. 372 continue; 373 374 if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) { 375 next = NodeTraversal::nextSkippingChildren(*n); 376 // Don't skip over pastEnd. 377 if (pastEnd && pastEnd->isDescendantOf(n)) 378 next = pastEnd; 379 } else { 380 // Add the node to the markup if we're not skipping the descendants 381 if (shouldEmit) 382 appendStartTag(*n); 383 384 // If node has no children, close the tag now. 385 if (!n->hasChildren()) { 386 if (shouldEmit) 387 appendEndTag(*n); 388 lastClosed = n; 389 } else { 390 openedTag = true; 391 ancestorsToClose.append(n); 392 } 393 } 394 395 // If we didn't insert open tag and there's no more siblings or we're at the end of the traversal, take care of ancestors. 396 // FIXME: What happens if we just inserted open tag and reached the end? 397 if (!openedTag && (!n->nextSibling() || next == pastEnd)) { 398 // Close up the ancestors. 399 while (!ancestorsToClose.isEmpty()) { 400 Node* ancestor = ancestorsToClose.last(); 401 ASSERT(ancestor); 402 if (next != pastEnd && next->isDescendantOf(ancestor)) 403 break; 404 // Not at the end of the range, close ancestors up to sibling of next node. 405 if (shouldEmit) 406 appendEndTag(*ancestor); 407 lastClosed = ancestor; 408 ancestorsToClose.removeLast(); 409 } 410 411 // Surround the currently accumulated markup with markup for ancestors we never opened as we leave the subtree(s) rooted at those ancestors. 412 ContainerNode* nextParent = next ? next->parentNode() : 0; 413 if (next != pastEnd && n != nextParent) { 414 Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n; 415 for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) { 416 // All ancestors that aren't in the ancestorsToClose list should either be a) unrendered: 417 if (!parent->renderer()) 418 continue; 419 // or b) ancestors that we never encountered during a pre-order traversal starting at startNode: 420 ASSERT(startNode->isDescendantOf(parent)); 421 if (shouldEmit) 422 wrapWithNode(*parent); 423 lastClosed = parent; 424 } 425 } 426 } 427 } 428 429 return lastClosed; 430 } 431 432 static bool isHTMLBlockElement(const Node* node) 433 { 434 ASSERT(node); 435 return isHTMLTableCellElement(*node) 436 || isNonTableCellHTMLBlockElement(node); 437 } 438 439 static Node* ancestorToRetainStructureAndAppearanceForBlock(Node* commonAncestorBlock) 440 { 441 if (!commonAncestorBlock) 442 return 0; 443 444 if (commonAncestorBlock->hasTagName(tbodyTag) || isHTMLTableRowElement(*commonAncestorBlock)) { 445 ContainerNode* table = commonAncestorBlock->parentNode(); 446 while (table && !isHTMLTableElement(*table)) 447 table = table->parentNode(); 448 449 return table; 450 } 451 452 if (isNonTableCellHTMLBlockElement(commonAncestorBlock)) 453 return commonAncestorBlock; 454 455 return 0; 456 } 457 458 static inline Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor) 459 { 460 return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor)); 461 } 462 463 static inline Node* ancestorToRetainStructureAndAppearanceWithNoRenderer(Node* commonAncestor) 464 { 465 Node* commonAncestorBlock = enclosingNodeOfType(firstPositionInOrBeforeNode(commonAncestor), isHTMLBlockElement); 466 return ancestorToRetainStructureAndAppearanceForBlock(commonAncestorBlock); 467 } 468 469 static bool propertyMissingOrEqualToNone(StylePropertySet* style, CSSPropertyID propertyID) 470 { 471 if (!style) 472 return false; 473 RefPtrWillBeRawPtr<CSSValue> value = style->getPropertyCSSValue(propertyID); 474 if (!value) 475 return true; 476 if (!value->isPrimitiveValue()) 477 return false; 478 return toCSSPrimitiveValue(value.get())->getValueID() == CSSValueNone; 479 } 480 481 static bool needInterchangeNewlineAfter(const VisiblePosition& v) 482 { 483 VisiblePosition next = v.next(); 484 Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode(); 485 Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode(); 486 // Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it. 487 return isEndOfParagraph(v) && isStartOfParagraph(next) && !(isHTMLBRElement(*upstreamNode) && upstreamNode == downstreamNode); 488 } 489 490 static PassRefPtrWillBeRawPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(const Node* node) 491 { 492 if (!node->isHTMLElement()) 493 return nullptr; 494 495 // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle 496 // the non-const-ness of styleFromMatchedRulesForElement. 497 HTMLElement* element = const_cast<HTMLElement*>(toHTMLElement(node)); 498 RefPtrWillBeRawPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle()); 499 style->mergeStyleFromRules(element); 500 return style.release(); 501 } 502 503 static bool isElementPresentational(const Node* node) 504 { 505 return node->hasTagName(uTag) || node->hasTagName(sTag) || node->hasTagName(strikeTag) 506 || node->hasTagName(iTag) || node->hasTagName(emTag) || node->hasTagName(bTag) || node->hasTagName(strongTag); 507 } 508 509 static Node* highestAncestorToWrapMarkup(const Range* range, EAnnotateForInterchange shouldAnnotate, Node* constrainingAncestor) 510 { 511 Node* commonAncestor = range->commonAncestorContainer(); 512 ASSERT(commonAncestor); 513 Node* specialCommonAncestor = 0; 514 if (shouldAnnotate == AnnotateForInterchange) { 515 // Include ancestors that aren't completely inside the range but are required to retain 516 // the structure and appearance of the copied markup. 517 specialCommonAncestor = ancestorToRetainStructureAndAppearance(commonAncestor); 518 519 if (Node* parentListNode = enclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isListItem)) { 520 if (WebCore::areRangesEqual(VisibleSelection::selectionFromContentsOfNode(parentListNode).toNormalizedRange().get(), range)) { 521 specialCommonAncestor = parentListNode->parentNode(); 522 while (specialCommonAncestor && !isListElement(specialCommonAncestor)) 523 specialCommonAncestor = specialCommonAncestor->parentNode(); 524 } 525 } 526 527 // Retain the Mail quote level by including all ancestor mail block quotes. 528 if (Node* highestMailBlockquote = highestEnclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isMailBlockquote, CanCrossEditingBoundary)) 529 specialCommonAncestor = highestMailBlockquote; 530 } 531 532 Node* checkAncestor = specialCommonAncestor ? specialCommonAncestor : commonAncestor; 533 if (checkAncestor->renderer()) { 534 Node* newSpecialCommonAncestor = highestEnclosingNodeOfType(firstPositionInNode(checkAncestor), &isElementPresentational, CanCrossEditingBoundary, constrainingAncestor); 535 if (newSpecialCommonAncestor) 536 specialCommonAncestor = newSpecialCommonAncestor; 537 } 538 539 // If a single tab is selected, commonAncestor will be a text node inside a tab span. 540 // If two or more tabs are selected, commonAncestor will be the tab span. 541 // In either case, if there is a specialCommonAncestor already, it will necessarily be above 542 // any tab span that needs to be included. 543 if (!specialCommonAncestor && isTabSpanTextNode(commonAncestor)) 544 specialCommonAncestor = commonAncestor->parentNode(); 545 if (!specialCommonAncestor && isTabSpanNode(commonAncestor)) 546 specialCommonAncestor = commonAncestor; 547 548 if (Node *enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag)) 549 specialCommonAncestor = enclosingAnchor; 550 551 return specialCommonAncestor; 552 } 553 554 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange? 555 // FIXME: At least, annotation and style info should probably not be included in range.markupString() 556 static String createMarkupInternal(Document& document, const Range* range, const Range* updatedRange, WillBeHeapVector<RawPtrWillBeMember<Node> >* nodes, 557 EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor) 558 { 559 ASSERT(range); 560 ASSERT(updatedRange); 561 DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">")); 562 563 bool collapsed = updatedRange->collapsed(); 564 if (collapsed) 565 return emptyString(); 566 Node* commonAncestor = updatedRange->commonAncestorContainer(); 567 if (!commonAncestor) 568 return emptyString(); 569 570 document.updateLayoutIgnorePendingStylesheets(); 571 572 Node* body = enclosingNodeWithTag(firstPositionInNode(commonAncestor), bodyTag); 573 Node* fullySelectedRoot = 0; 574 // FIXME: Do this for all fully selected blocks, not just the body. 575 if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range)) 576 fullySelectedRoot = body; 577 Node* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange, shouldAnnotate, constrainingAncestor); 578 StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange, specialCommonAncestor); 579 Node* pastEnd = updatedRange->pastLastNode(); 580 581 Node* startNode = updatedRange->firstNode(); 582 VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY); 583 VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY); 584 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) { 585 if (visibleStart == visibleEnd.previous()) 586 return interchangeNewlineString; 587 588 accumulator.appendString(interchangeNewlineString); 589 startNode = visibleStart.next().deepEquivalent().deprecatedNode(); 590 591 if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ASSERT_NO_EXCEPTION) >= 0) 592 return interchangeNewlineString; 593 } 594 595 Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd); 596 597 if (specialCommonAncestor && lastClosed) { 598 // Also include all of the ancestors of lastClosed up to this special ancestor. 599 for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) { 600 if (ancestor == fullySelectedRoot && !convertBlocksToInlines) { 601 RefPtrWillBeRawPtr<EditingStyle> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot); 602 603 // Bring the background attribute over, but not as an attribute because a background attribute on a div 604 // appears to have no effect. 605 if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue(CSSPropertyBackgroundImage)) 606 && toElement(fullySelectedRoot)->hasAttribute(backgroundAttr)) 607 fullySelectedRootStyle->style()->setProperty(CSSPropertyBackgroundImage, "url('" + toElement(fullySelectedRoot)->getAttribute(backgroundAttr) + "')"); 608 609 if (fullySelectedRootStyle->style()) { 610 // Reset the CSS properties to avoid an assertion error in addStyleMarkup(). 611 // This assertion is caused at least when we select all text of a <body> element whose 612 // 'text-decoration' property is "inherit", and copy it. 613 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration)) 614 fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone); 615 if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect)) 616 fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone); 617 accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true); 618 } 619 } else { 620 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode 621 // so that styles that affect the exterior of the node are not included. 622 accumulator.wrapWithNode(*ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode); 623 } 624 if (nodes) 625 nodes->append(ancestor); 626 627 if (ancestor == specialCommonAncestor) 628 break; 629 } 630 } 631 632 // FIXME: The interchange newline should be placed in the block that it's in, not after all of the content, unconditionally. 633 if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous())) 634 accumulator.appendString(interchangeNewlineString); 635 636 return accumulator.takeResults(); 637 } 638 639 String createMarkup(const Range* range, WillBeHeapVector<RawPtrWillBeMember<Node> >* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor) 640 { 641 if (!range) 642 return emptyString(); 643 644 Document& document = range->ownerDocument(); 645 const Range* updatedRange = range; 646 647 return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor); 648 } 649 650 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy) 651 { 652 // We use a fake body element here to trick the HTML parser to using the InBody insertion mode. 653 RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document); 654 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document); 655 656 fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy); 657 658 if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL()) 659 completeURLs(*fragment, baseURL); 660 661 return fragment.release(); 662 } 663 664 static const char fragmentMarkerTag[] = "webkit-fragment-marker"; 665 666 static bool findNodesSurroundingContext(Document* document, RefPtrWillBeRawPtr<Node>& nodeBeforeContext, RefPtrWillBeRawPtr<Node>& nodeAfterContext) 667 { 668 for (Node* node = document->firstChild(); node; node = NodeTraversal::next(*node)) { 669 if (node->nodeType() == Node::COMMENT_NODE && toCharacterData(node)->data() == fragmentMarkerTag) { 670 if (!nodeBeforeContext) 671 nodeBeforeContext = node; 672 else { 673 nodeAfterContext = node; 674 return true; 675 } 676 } 677 } 678 return false; 679 } 680 681 static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, Node* nodeAfterContext) 682 { 683 RefPtrWillBeRawPtr<Node> next = nullptr; 684 for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = next) { 685 if (nodeBeforeContext->isDescendantOf(node.get())) { 686 next = NodeTraversal::next(*node); 687 continue; 688 } 689 next = NodeTraversal::nextSkippingChildren(*node); 690 ASSERT(!node->contains(nodeAfterContext)); 691 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION); 692 if (nodeBeforeContext == node) 693 break; 694 } 695 696 ASSERT(nodeAfterContext->parentNode()); 697 for (RefPtrWillBeRawPtr<Node> node = nodeAfterContext; node; node = next) { 698 next = NodeTraversal::nextSkippingChildren(*node); 699 node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION); 700 } 701 } 702 703 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd, 704 const String& baseURL, ParserContentPolicy parserContentPolicy) 705 { 706 // FIXME: Need to handle the case where the markup already contains these markers. 707 708 StringBuilder taggedMarkup; 709 taggedMarkup.append(markup.left(fragmentStart)); 710 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag); 711 taggedMarkup.append(markup.substring(fragmentStart, fragmentEnd - fragmentStart)); 712 MarkupAccumulator::appendComment(taggedMarkup, fragmentMarkerTag); 713 taggedMarkup.append(markup.substring(fragmentEnd)); 714 715 RefPtrWillBeRawPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy); 716 RefPtrWillBeRawPtr<Document> taggedDocument = Document::create(); 717 taggedDocument->setContextFeatures(document.contextFeatures()); 718 719 // FIXME: It's not clear what this code is trying to do. It puts nodes as direct children of a 720 // Document that are not normally allowed by using the parser machinery. 721 taggedDocument->parserTakeAllChildrenFrom(*taggedFragment); 722 723 RefPtrWillBeRawPtr<Node> nodeBeforeContext = nullptr; 724 RefPtrWillBeRawPtr<Node> nodeAfterContext = nullptr; 725 if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext)) 726 return nullptr; 727 728 RefPtrWillBeRawPtr<Range> range = Range::create(*taggedDocument.get(), 729 positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(), 730 positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent()); 731 732 Node* commonAncestor = range->commonAncestorContainer(); 733 Node* specialCommonAncestor = ancestorToRetainStructureAndAppearanceWithNoRenderer(commonAncestor); 734 735 // When there's a special common ancestor outside of the fragment, we must include it as well to 736 // preserve the structure and appearance of the fragment. For example, if the fragment contains 737 // TD, we need to include the enclosing TABLE tag as well. 738 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document); 739 if (specialCommonAncestor) 740 fragment->appendChild(specialCommonAncestor); 741 else 742 fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor)); 743 744 trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get()); 745 746 return fragment; 747 } 748 749 String createMarkup(const Node* node, EChildrenOnly childrenOnly, WillBeHeapVector<RawPtrWillBeMember<Node> >* nodes, EAbsoluteURLs shouldResolveURLs, Vector<QualifiedName>* tagNamesToSkip) 750 { 751 if (!node) 752 return ""; 753 754 MarkupAccumulator accumulator(nodes, shouldResolveURLs); 755 return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip); 756 } 757 758 static void fillContainerFromString(ContainerNode* paragraph, const String& string) 759 { 760 Document& document = paragraph->document(); 761 762 if (string.isEmpty()) { 763 paragraph->appendChild(createBlockPlaceholderElement(document)); 764 return; 765 } 766 767 ASSERT(string.find('\n') == kNotFound); 768 769 Vector<String> tabList; 770 string.split('\t', true, tabList); 771 StringBuilder tabText; 772 bool first = true; 773 size_t numEntries = tabList.size(); 774 for (size_t i = 0; i < numEntries; ++i) { 775 const String& s = tabList[i]; 776 777 // append the non-tab textual part 778 if (!s.isEmpty()) { 779 if (!tabText.isEmpty()) { 780 paragraph->appendChild(createTabSpanElement(document, tabText.toString())); 781 tabText.clear(); 782 } 783 RefPtrWillBeRawPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries)); 784 paragraph->appendChild(textNode.release()); 785 } 786 787 // there is a tab after every entry, except the last entry 788 // (if the last character is a tab, the list gets an extra empty entry) 789 if (i + 1 != numEntries) 790 tabText.append('\t'); 791 else if (!tabText.isEmpty()) 792 paragraph->appendChild(createTabSpanElement(document, tabText.toString())); 793 794 first = false; 795 } 796 } 797 798 bool isPlainTextMarkup(Node* node) 799 { 800 ASSERT(node); 801 if (!node->isElementNode()) 802 return false; 803 804 Element* element = toElement(node); 805 if (!isHTMLDivElement(*element) || !element->hasAttributes()) 806 return false; 807 808 if (element->hasOneChild() && (element->firstChild()->isTextNode() || (element->firstChild()->firstChild()))) 809 return true; 810 811 return element->hasChildCount(2) && isTabSpanTextNode(element->firstChild()->firstChild()) && element->lastChild()->isTextNode(); 812 } 813 814 static bool shouldPreserveNewline(const Range& range) 815 { 816 if (Node* node = range.firstNode()) { 817 if (RenderObject* renderer = node->renderer()) 818 return renderer->style()->preserveNewline(); 819 } 820 821 if (Node* node = range.startPosition().anchorNode()) { 822 if (RenderObject* renderer = node->renderer()) 823 return renderer->style()->preserveNewline(); 824 } 825 826 return false; 827 } 828 829 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text) 830 { 831 if (!context) 832 return nullptr; 833 834 Document& document = context->ownerDocument(); 835 RefPtrWillBeRawPtr<DocumentFragment> fragment = document.createDocumentFragment(); 836 837 if (text.isEmpty()) 838 return fragment.release(); 839 840 String string = text; 841 string.replace("\r\n", "\n"); 842 string.replace('\r', '\n'); 843 844 if (shouldPreserveNewline(*context)) { 845 fragment->appendChild(document.createTextNode(string)); 846 if (string.endsWith('\n')) { 847 RefPtrWillBeRawPtr<Element> element = createBreakElement(document); 848 element->setAttribute(classAttr, AppleInterchangeNewline); 849 fragment->appendChild(element.release()); 850 } 851 return fragment.release(); 852 } 853 854 // A string with no newlines gets added inline, rather than being put into a paragraph. 855 if (string.find('\n') == kNotFound) { 856 fillContainerFromString(fragment.get(), string); 857 return fragment.release(); 858 } 859 860 // Break string into paragraphs. Extra line breaks turn into empty paragraphs. 861 Node* blockNode = enclosingBlock(context->firstNode()); 862 Element* block = toElement(blockNode); 863 bool useClonesOfEnclosingBlock = blockNode 864 && blockNode->isElementNode() 865 && !isHTMLBodyElement(*block) 866 && !isHTMLHtmlElement(*block) 867 && block != editableRootForPosition(context->startPosition()); 868 bool useLineBreak = enclosingTextFormControl(context->startPosition()); 869 870 Vector<String> list; 871 string.split('\n', true, list); // true gets us empty strings in the list 872 size_t numLines = list.size(); 873 for (size_t i = 0; i < numLines; ++i) { 874 const String& s = list[i]; 875 876 RefPtrWillBeRawPtr<Element> element = nullptr; 877 if (s.isEmpty() && i + 1 == numLines) { 878 // For last line, use the "magic BR" rather than a P. 879 element = createBreakElement(document); 880 element->setAttribute(classAttr, AppleInterchangeNewline); 881 } else if (useLineBreak) { 882 element = createBreakElement(document); 883 fillContainerFromString(fragment.get(), s); 884 } else { 885 if (useClonesOfEnclosingBlock) 886 element = block->cloneElementWithoutChildren(); 887 else 888 element = createDefaultParagraphElement(document); 889 fillContainerFromString(element.get(), s); 890 } 891 fragment->appendChild(element.release()); 892 } 893 return fragment.release(); 894 } 895 896 String createFullMarkup(const Node* node) 897 { 898 if (!node) 899 return String(); 900 901 LocalFrame* frame = node->document().frame(); 902 if (!frame) 903 return String(); 904 905 // FIXME: This is never "for interchange". Is that right? 906 String markupString = createMarkup(node, IncludeNode, 0); 907 Node::NodeType nodeType = node->nodeType(); 908 if (nodeType != Node::DOCUMENT_NODE && !node->isDocumentTypeNode()) 909 markupString = frame->documentTypeString() + markupString; 910 911 return markupString; 912 } 913 914 String urlToMarkup(const KURL& url, const String& title) 915 { 916 StringBuilder markup; 917 markup.appendLiteral("<a href=\""); 918 markup.append(url.string()); 919 markup.appendLiteral("\">"); 920 MarkupAccumulator::appendCharactersReplacingEntities(markup, title, 0, title.length(), EntityMaskInPCDATA); 921 markup.appendLiteral("</a>"); 922 return markup.toString(); 923 } 924 925 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState) 926 { 927 ASSERT(contextElement); 928 Document& document = isHTMLTemplateElement(*contextElement) ? contextElement->document().ensureTemplateDocument() : contextElement->document(); 929 RefPtrWillBeRawPtr<DocumentFragment> fragment = DocumentFragment::create(document); 930 931 if (document.isHTMLDocument()) { 932 fragment->parseHTML(markup, contextElement, parserContentPolicy); 933 return fragment; 934 } 935 936 bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy); 937 if (!wasValid) { 938 exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document."); 939 return nullptr; 940 } 941 return fragment.release(); 942 } 943 944 PassRefPtrWillBeRawPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc) 945 { 946 RefPtrWillBeRawPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment(); 947 948 if (sourceMIMEType == "text/html") { 949 // As far as I can tell, there isn't a spec for how transformToFragment is supposed to work. 950 // Based on the documentation I can find, it looks like we want to start parsing the fragment in the InBody insertion mode. 951 // Unfortunately, that's an implementation detail of the parser. 952 // We achieve that effect here by passing in a fake body element as context for the fragment. 953 RefPtrWillBeRawPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc); 954 fragment->parseHTML(sourceString, fakeBody.get()); 955 } else if (sourceMIMEType == "text/plain") { 956 fragment->parserAppendChild(Text::create(outputDoc, sourceString)); 957 } else { 958 bool successfulParse = fragment->parseXML(sourceString, 0); 959 if (!successfulParse) 960 return nullptr; 961 } 962 963 // FIXME: Do we need to mess with URLs here? 964 965 return fragment.release(); 966 } 967 968 static inline void removeElementPreservingChildren(PassRefPtrWillBeRawPtr<DocumentFragment> fragment, HTMLElement* element) 969 { 970 RefPtrWillBeRawPtr<Node> nextChild = nullptr; 971 for (RefPtrWillBeRawPtr<Node> child = element->firstChild(); child; child = nextChild) { 972 nextChild = child->nextSibling(); 973 element->removeChild(child.get()); 974 fragment->insertBefore(child, element); 975 } 976 fragment->removeChild(element); 977 } 978 979 PassRefPtrWillBeRawPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState) 980 { 981 ASSERT(element); 982 if (element->ieForbidsInsertHTML() || element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag) 983 || element->hasLocalName(headTag) || element->hasLocalName(styleTag) || element->hasLocalName(titleTag)) { 984 exceptionState.throwDOMException(NotSupportedError, "The range's container is '" + element->localName() + "', which is not supported."); 985 return nullptr; 986 } 987 988 RefPtrWillBeRawPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState); 989 if (!fragment) 990 return nullptr; 991 992 // We need to pop <html> and <body> elements and remove <head> to 993 // accommodate folks passing complete HTML documents to make the 994 // child of an element. 995 996 RefPtrWillBeRawPtr<Node> nextNode = nullptr; 997 for (RefPtrWillBeRawPtr<Node> node = fragment->firstChild(); node; node = nextNode) { 998 nextNode = node->nextSibling(); 999 if (isHTMLHtmlElement(*node) || isHTMLHeadElement(*node) || isHTMLBodyElement(*node)) { 1000 HTMLElement* element = toHTMLElement(node); 1001 if (Node* firstChild = element->firstChild()) 1002 nextNode = firstChild; 1003 removeElementPreservingChildren(fragment, element); 1004 } 1005 } 1006 return fragment.release(); 1007 } 1008 1009 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtrWillBeRawPtr<DocumentFragment> fragment, ExceptionState& exceptionState) 1010 { 1011 ASSERT(container); 1012 RefPtrWillBeRawPtr<ContainerNode> containerNode(container); 1013 1014 ChildListMutationScope mutation(*containerNode); 1015 1016 if (!fragment->firstChild()) { 1017 containerNode->removeChildren(); 1018 return; 1019 } 1020 1021 // FIXME: This is wrong if containerNode->firstChild() has more than one ref! 1022 if (containerNode->hasOneTextChild() && fragment->hasOneTextChild()) { 1023 toText(containerNode->firstChild())->setData(toText(fragment->firstChild())->data()); 1024 return; 1025 } 1026 1027 // FIXME: No need to replace the child it is a text node and its contents are already == text. 1028 if (containerNode->hasOneChild()) { 1029 containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState); 1030 return; 1031 } 1032 1033 containerNode->removeChildren(); 1034 containerNode->appendChild(fragment, exceptionState); 1035 } 1036 1037 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState) 1038 { 1039 ASSERT(container); 1040 RefPtrWillBeRawPtr<ContainerNode> containerNode(container); 1041 1042 ChildListMutationScope mutation(*containerNode); 1043 1044 // FIXME: This is wrong if containerNode->firstChild() has more than one ref! Example: 1045 // <div>foo</div> 1046 // <script> 1047 // var oldText = div.firstChild; 1048 // console.log(oldText.data); // foo 1049 // div.innerText = "bar"; 1050 // console.log(oldText.data); // bar!?! 1051 // </script> 1052 // I believe this is an intentional benchmark cheat from years ago. 1053 // We should re-visit if we actually want this still. 1054 if (containerNode->hasOneTextChild()) { 1055 toText(containerNode->firstChild())->setData(text); 1056 return; 1057 } 1058 1059 // NOTE: This method currently always creates a text node, even if that text node will be empty. 1060 RefPtrWillBeRawPtr<Text> textNode = Text::create(containerNode->document(), text); 1061 1062 // FIXME: No need to replace the child it is a text node and its contents are already == text. 1063 if (containerNode->hasOneChild()) { 1064 containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState); 1065 return; 1066 } 1067 1068 containerNode->removeChildren(); 1069 containerNode->appendChild(textNode.release(), exceptionState); 1070 } 1071 1072 void mergeWithNextTextNode(PassRefPtrWillBeRawPtr<Node> node, ExceptionState& exceptionState) 1073 { 1074 ASSERT(node && node->isTextNode()); 1075 Node* next = node->nextSibling(); 1076 if (!next || !next->isTextNode()) 1077 return; 1078 1079 RefPtrWillBeRawPtr<Text> textNode = toText(node.get()); 1080 RefPtrWillBeRawPtr<Text> textNext = toText(next); 1081 textNode->appendData(textNext->data()); 1082 if (textNext->parentNode()) // Might have been removed by mutation event. 1083 textNext->remove(exceptionState); 1084 } 1085 1086 } 1087