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