1 /*
2  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2008, 2009 Google Inc.
4  * Copyright (C) 2011 Igalia S.L.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "config.h"
29 #include "markup.h"
30 
31 #include "CDATASection.h"
32 #include "CSSComputedStyleDeclaration.h"
33 #include "CSSMutableStyleDeclaration.h"
34 #include "CSSPrimitiveValue.h"
35 #include "CSSProperty.h"
36 #include "CSSPropertyNames.h"
37 #include "CSSRule.h"
38 #include "CSSRuleList.h"
39 #include "CSSStyleRule.h"
40 #include "CSSStyleSelector.h"
41 #include "CSSValue.h"
42 #include "CSSValueKeywords.h"
43 #include "DeleteButtonController.h"
44 #include "DocumentFragment.h"
45 #include "DocumentType.h"
46 #include "Editor.h"
47 #include "Frame.h"
48 #include "HTMLBodyElement.h"
49 #include "HTMLElement.h"
50 #include "HTMLNames.h"
51 #include "KURL.h"
52 #include "MarkupAccumulator.h"
53 #include "Range.h"
54 #include "TextIterator.h"
55 #include "VisibleSelection.h"
56 #include "XMLNSNames.h"
57 #include "htmlediting.h"
58 #include "visible_units.h"
59 #include <wtf/StdLibExtras.h>
60 #include <wtf/unicode/CharacterNames.h>
61 
62 using namespace std;
63 
64 namespace WebCore {
65 
66 using namespace HTMLNames;
67 
68 static bool propertyMissingOrEqualToNone(CSSStyleDeclaration*, int propertyID);
69 
70 class AttributeChange {
71 public:
AttributeChange()72     AttributeChange()
73         : m_name(nullAtom, nullAtom, nullAtom)
74     {
75     }
76 
AttributeChange(PassRefPtr<Element> element,const QualifiedName & name,const String & value)77     AttributeChange(PassRefPtr<Element> element, const QualifiedName& name, const String& value)
78         : m_element(element), m_name(name), m_value(value)
79     {
80     }
81 
apply()82     void apply()
83     {
84         m_element->setAttribute(m_name, m_value);
85     }
86 
87 private:
88     RefPtr<Element> m_element;
89     QualifiedName m_name;
90     String m_value;
91 };
92 
completeURLs(Node * node,const String & baseURL)93 static void completeURLs(Node* node, const String& baseURL)
94 {
95     Vector<AttributeChange> changes;
96 
97     KURL parsedBaseURL(ParsedURLString, baseURL);
98 
99     Node* end = node->traverseNextSibling();
100     for (Node* n = node; n != end; n = n->traverseNextNode()) {
101         if (n->isElementNode()) {
102             Element* e = static_cast<Element*>(n);
103             NamedNodeMap* attributes = e->attributes();
104             unsigned length = attributes->length();
105             for (unsigned i = 0; i < length; i++) {
106                 Attribute* attribute = attributes->attributeItem(i);
107                 if (e->isURLAttribute(attribute))
108                     changes.append(AttributeChange(e, attribute->name(), KURL(parsedBaseURL, attribute->value()).string()));
109             }
110         }
111     }
112 
113     size_t numChanges = changes.size();
114     for (size_t i = 0; i < numChanges; ++i)
115         changes[i].apply();
116 }
117 
118 class StyledMarkupAccumulator : public MarkupAccumulator {
119 public:
120     enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
121 
StyledMarkupAccumulator(Vector<Node * > * nodes,EAbsoluteURLs shouldResolveURLs,EAnnotateForInterchange shouldAnnotate,const Range * range)122     StyledMarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs, EAnnotateForInterchange shouldAnnotate, const Range* range)
123     : MarkupAccumulator(nodes, shouldResolveURLs, range)
124     , m_shouldAnnotate(shouldAnnotate)
125     {
126     }
127 
128     Node* serializeNodes(Node* startNode, Node* pastEnd);
appendString(const String & s)129     virtual void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
130     void wrapWithNode(Node*, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
131     void wrapWithStyleNode(CSSStyleDeclaration*, Document*, bool isBlock = false);
132     String takeResults();
133 
134 private:
135     virtual void appendText(Vector<UChar>& out, Text*);
136     String renderedText(const Node*, const Range*);
137     String stringValueForRange(const Node*, const Range*);
138     void removeExteriorStyles(CSSMutableStyleDeclaration*);
139     void appendElement(Vector<UChar>& out, Element* element, bool addDisplayInline, RangeFullySelectsNode);
appendElement(Vector<UChar> & out,Element * element,Namespaces *)140     void appendElement(Vector<UChar>& out, Element* element, Namespaces*) { appendElement(out, element, false, DoesFullySelectNode); }
141 
shouldAnnotate()142     bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; }
143 
144     Vector<String> m_reversedPrecedingMarkup;
145     const EAnnotateForInterchange m_shouldAnnotate;
146 };
147 
wrapWithNode(Node * node,bool convertBlocksToInlines,RangeFullySelectsNode rangeFullySelectsNode)148 void StyledMarkupAccumulator::wrapWithNode(Node* node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
149 {
150     Vector<UChar> markup;
151     if (node->isElementNode())
152         appendElement(markup, static_cast<Element*>(node), convertBlocksToInlines && isBlock(const_cast<Node*>(node)), rangeFullySelectsNode);
153     else
154         appendStartMarkup(markup, node, 0);
155     m_reversedPrecedingMarkup.append(String::adopt(markup));
156     appendEndTag(node);
157     if (m_nodes)
158         m_nodes->append(node);
159 }
160 
wrapWithStyleNode(CSSStyleDeclaration * style,Document * document,bool isBlock)161 void StyledMarkupAccumulator::wrapWithStyleNode(CSSStyleDeclaration* style, Document* document, bool isBlock)
162 {
163     // All text-decoration-related elements should have been treated as special ancestors
164     // If we ever hit this ASSERT, we should export StyleChange in ApplyStyleCommand and use it here
165     ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyTextDecoration) && propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
166     DEFINE_STATIC_LOCAL(const String, divStyle, ("<div style=\""));
167     DEFINE_STATIC_LOCAL(const String, divClose, ("</div>"));
168     DEFINE_STATIC_LOCAL(const String, styleSpanOpen, ("<span class=\"" AppleStyleSpanClass "\" style=\""));
169     DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>"));
170     Vector<UChar> openTag;
171     append(openTag, isBlock ? divStyle : styleSpanOpen);
172     appendAttributeValue(openTag, style->cssText(), document->isHTMLDocument());
173     openTag.append('\"');
174     openTag.append('>');
175     m_reversedPrecedingMarkup.append(String::adopt(openTag));
176     appendString(isBlock ? divClose : styleSpanClose);
177 }
178 
takeResults()179 String StyledMarkupAccumulator::takeResults()
180 {
181     Vector<UChar> result;
182     result.reserveInitialCapacity(totalLength(m_reversedPrecedingMarkup) + length());
183 
184     for (size_t i = m_reversedPrecedingMarkup.size(); i > 0; --i)
185         append(result, m_reversedPrecedingMarkup[i - 1]);
186 
187     concatenateMarkup(result);
188 
189     // We remove '\0' characters because they are not visibly rendered to the user.
190     return String::adopt(result).replace(0, "");
191 }
192 
appendText(Vector<UChar> & out,Text * text)193 void StyledMarkupAccumulator::appendText(Vector<UChar>& out, Text* text)
194 {
195     if (!shouldAnnotate() || (text->parentElement() && text->parentElement()->tagQName() == textareaTag)) {
196         MarkupAccumulator::appendText(out, text);
197         return;
198     }
199 
200     bool useRenderedText = !enclosingNodeWithTag(firstPositionInNode(text), selectTag);
201     String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range);
202     Vector<UChar> buffer;
203     appendCharactersReplacingEntities(buffer, content.characters(), content.length(), EntityMaskInPCDATA);
204     append(out, convertHTMLTextToInterchangeFormat(String::adopt(buffer), text));
205 }
206 
renderedText(const Node * node,const Range * range)207 String StyledMarkupAccumulator::renderedText(const Node* node, const Range* range)
208 {
209     if (!node->isTextNode())
210         return String();
211 
212     ExceptionCode ec;
213     const Text* textNode = static_cast<const Text*>(node);
214     unsigned startOffset = 0;
215     unsigned endOffset = textNode->length();
216 
217     if (range && node == range->startContainer(ec))
218         startOffset = range->startOffset(ec);
219     if (range && node == range->endContainer(ec))
220         endOffset = range->endOffset(ec);
221 
222     Position start(const_cast<Node*>(node), startOffset);
223     Position end(const_cast<Node*>(node), endOffset);
224     return plainText(Range::create(node->document(), start, end).get());
225 }
226 
stringValueForRange(const Node * node,const Range * range)227 String StyledMarkupAccumulator::stringValueForRange(const Node* node, const Range* range)
228 {
229     if (!range)
230         return node->nodeValue();
231 
232     String str = node->nodeValue();
233     ExceptionCode ec;
234     if (node == range->endContainer(ec))
235         str.truncate(range->endOffset(ec));
236     if (node == range->startContainer(ec))
237         str.remove(0, range->startOffset(ec));
238     return str;
239 }
240 
styleFromMatchedRulesForElement(Element * element,bool authorOnly=true)241 static PassRefPtr<CSSMutableStyleDeclaration> styleFromMatchedRulesForElement(Element* element, bool authorOnly = true)
242 {
243     RefPtr<CSSMutableStyleDeclaration> style = CSSMutableStyleDeclaration::create();
244     RefPtr<CSSRuleList> matchedRules = element->document()->styleSelector()->styleRulesForElement(element, authorOnly);
245     if (matchedRules) {
246         for (unsigned i = 0; i < matchedRules->length(); i++) {
247             if (matchedRules->item(i)->type() == CSSRule::STYLE_RULE) {
248                 RefPtr<CSSMutableStyleDeclaration> s = static_cast<CSSStyleRule*>(matchedRules->item(i))->style();
249                 style->merge(s.get(), true);
250             }
251         }
252     }
253 
254     return style.release();
255 }
256 
appendElement(Vector<UChar> & out,Element * element,bool addDisplayInline,RangeFullySelectsNode rangeFullySelectsNode)257 void StyledMarkupAccumulator::appendElement(Vector<UChar>& out, Element* element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
258 {
259     bool documentIsHTML = element->document()->isHTMLDocument();
260     appendOpenTag(out, element, 0);
261 
262     NamedNodeMap* attributes = element->attributes();
263     unsigned length = attributes->length();
264     for (unsigned int i = 0; i < length; i++) {
265         Attribute* attribute = attributes->attributeItem(i);
266         // We'll handle the style attribute separately, below.
267         if (attribute->name() == styleAttr && element->isHTMLElement() && (shouldAnnotate() || addDisplayInline))
268             continue;
269         appendAttribute(out, element, *attribute, 0);
270     }
271 
272     if (element->isHTMLElement() && (shouldAnnotate() || addDisplayInline)) {
273         RefPtr<CSSMutableStyleDeclaration> style = toHTMLElement(element)->getInlineStyleDecl()->copy();
274         if (shouldAnnotate()) {
275             RefPtr<CSSMutableStyleDeclaration> styleFromMatchedRules = styleFromMatchedRulesForElement(const_cast<Element*>(element));
276             // Styles from the inline style declaration, held in the variable "style", take precedence
277             // over those from matched rules.
278             styleFromMatchedRules->merge(style.get());
279             style = styleFromMatchedRules;
280 
281             RefPtr<CSSComputedStyleDeclaration> computedStyleForElement = computedStyle(element);
282             RefPtr<CSSMutableStyleDeclaration> fromComputedStyle = CSSMutableStyleDeclaration::create();
283 
284             {
285                 CSSMutableStyleDeclaration::const_iterator end = style->end();
286                 for (CSSMutableStyleDeclaration::const_iterator it = style->begin(); it != end; ++it) {
287                     const CSSProperty& property = *it;
288                     CSSValue* value = property.value();
289                     // The property value, if it's a percentage, may not reflect the actual computed value.
290                     // For example: style="height: 1%; overflow: visible;" in quirksmode
291                     // FIXME: There are others like this, see <rdar://problem/5195123> Slashdot copy/paste fidelity problem
292                     if (value->cssValueType() == CSSValue::CSS_PRIMITIVE_VALUE)
293                         if (static_cast<CSSPrimitiveValue*>(value)->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
294                             if (RefPtr<CSSValue> computedPropertyValue = computedStyleForElement->getPropertyCSSValue(property.id()))
295                                 fromComputedStyle->addParsedProperty(CSSProperty(property.id(), computedPropertyValue));
296                 }
297             }
298             style->merge(fromComputedStyle.get());
299         }
300         if (addDisplayInline)
301             style->setProperty(CSSPropertyDisplay, CSSValueInline, true);
302         // 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
303         // only the ones that affect it and the nodes within it.
304         if (rangeFullySelectsNode == DoesNotFullySelectNode)
305             removeExteriorStyles(style.get());
306         if (style->length() > 0) {
307             DEFINE_STATIC_LOCAL(const String, stylePrefix, (" style=\""));
308             append(out, stylePrefix);
309             appendAttributeValue(out, style->cssText(), documentIsHTML);
310             out.append('\"');
311         }
312     }
313 
314     appendCloseTag(out, element);
315 }
316 
removeExteriorStyles(CSSMutableStyleDeclaration * style)317 void StyledMarkupAccumulator::removeExteriorStyles(CSSMutableStyleDeclaration* style)
318 {
319     style->removeProperty(CSSPropertyFloat);
320 }
321 
serializeNodes(Node * startNode,Node * pastEnd)322 Node* StyledMarkupAccumulator::serializeNodes(Node* startNode, Node* pastEnd)
323 {
324     Vector<Node*> ancestorsToClose;
325     Node* next;
326     Node* lastClosed = 0;
327     for (Node* n = startNode; n != pastEnd; n = next) {
328         // According to <rdar://problem/5730668>, it is possible for n to blow
329         // past pastEnd and become null here. This shouldn't be possible.
330         // This null check will prevent crashes (but create too much markup)
331         // and the ASSERT will hopefully lead us to understanding the problem.
332         ASSERT(n);
333         if (!n)
334             break;
335 
336         next = n->traverseNextNode();
337         bool openedTag = false;
338 
339         if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
340             // Don't write out empty block containers that aren't fully selected.
341             continue;
342 
343         if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
344             next = n->traverseNextSibling();
345             // Don't skip over pastEnd.
346             if (pastEnd && pastEnd->isDescendantOf(n))
347                 next = pastEnd;
348         } else {
349             // Add the node to the markup if we're not skipping the descendants
350             appendStartTag(n);
351 
352             // If node has no children, close the tag now.
353             if (!n->childNodeCount()) {
354                 appendEndTag(n);
355                 lastClosed = n;
356             } else {
357                 openedTag = true;
358                 ancestorsToClose.append(n);
359             }
360         }
361 
362         // 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.
363         // FIXME: What happens if we just inserted open tag and reached the end?
364         if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
365             // Close up the ancestors.
366             while (!ancestorsToClose.isEmpty()) {
367                 Node* ancestor = ancestorsToClose.last();
368                 if (next != pastEnd && next->isDescendantOf(ancestor))
369                     break;
370                 // Not at the end of the range, close ancestors up to sibling of next node.
371                 appendEndTag(ancestor);
372                 lastClosed = ancestor;
373                 ancestorsToClose.removeLast();
374             }
375 
376             // Surround the currently accumulated markup with markup for ancestors we never opened as we leave the subtree(s) rooted at those ancestors.
377             ContainerNode* nextParent = next ? next->parentNode() : 0;
378             if (next != pastEnd && n != nextParent) {
379                 Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
380                 for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
381                     // All ancestors that aren't in the ancestorsToClose list should either be a) unrendered:
382                     if (!parent->renderer())
383                         continue;
384                     // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
385                     ASSERT(startNode->isDescendantOf(parent));
386                     wrapWithNode(parent);
387                     lastClosed = parent;
388                 }
389             }
390         }
391     }
392 
393     return lastClosed;
394 }
395 
ancestorToRetainStructureAndAppearance(Node * commonAncestor)396 static Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
397 {
398     Node* commonAncestorBlock = enclosingBlock(commonAncestor);
399 
400     if (!commonAncestorBlock)
401         return 0;
402 
403     if (commonAncestorBlock->hasTagName(tbodyTag) || commonAncestorBlock->hasTagName(trTag)) {
404         ContainerNode* table = commonAncestorBlock->parentNode();
405         while (table && !table->hasTagName(tableTag))
406             table = table->parentNode();
407 
408         return table;
409     }
410 
411     if (commonAncestorBlock->hasTagName(listingTag)
412         || commonAncestorBlock->hasTagName(olTag)
413         || commonAncestorBlock->hasTagName(preTag)
414         || commonAncestorBlock->hasTagName(tableTag)
415         || commonAncestorBlock->hasTagName(ulTag)
416         || commonAncestorBlock->hasTagName(xmpTag)
417         || commonAncestorBlock->hasTagName(h1Tag)
418         || commonAncestorBlock->hasTagName(h2Tag)
419         || commonAncestorBlock->hasTagName(h3Tag)
420         || commonAncestorBlock->hasTagName(h4Tag)
421         || commonAncestorBlock->hasTagName(h5Tag))
422         return commonAncestorBlock;
423 
424     return 0;
425 }
426 
propertyMissingOrEqualToNone(CSSStyleDeclaration * style,int propertyID)427 static bool propertyMissingOrEqualToNone(CSSStyleDeclaration* style, int propertyID)
428 {
429     if (!style)
430         return false;
431     RefPtr<CSSValue> value = style->getPropertyCSSValue(propertyID);
432     if (!value)
433         return true;
434     if (!value->isPrimitiveValue())
435         return false;
436     return static_cast<CSSPrimitiveValue*>(value.get())->getIdent() == CSSValueNone;
437 }
438 
needInterchangeNewlineAfter(const VisiblePosition & v)439 static bool needInterchangeNewlineAfter(const VisiblePosition& v)
440 {
441     VisiblePosition next = v.next();
442     Node* upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
443     Node* downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
444     // Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it.
445     return isEndOfParagraph(v) && isStartOfParagraph(next) && !(upstreamNode->hasTagName(brTag) && upstreamNode == downstreamNode);
446 }
447 
styleFromMatchedRulesAndInlineDecl(const Node * node)448 static PassRefPtr<CSSMutableStyleDeclaration> styleFromMatchedRulesAndInlineDecl(const Node* node)
449 {
450     if (!node->isHTMLElement())
451         return 0;
452 
453     // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle
454     // the non-const-ness of styleFromMatchedRulesForElement.
455     HTMLElement* element = const_cast<HTMLElement*>(static_cast<const HTMLElement*>(node));
456     RefPtr<CSSMutableStyleDeclaration> style = styleFromMatchedRulesForElement(element);
457     RefPtr<CSSMutableStyleDeclaration> inlineStyleDecl = element->getInlineStyleDecl();
458     style->merge(inlineStyleDecl.get());
459     return style.release();
460 }
461 
isElementPresentational(const Node * node)462 static bool isElementPresentational(const Node* node)
463 {
464     if (node->hasTagName(uTag) || node->hasTagName(sTag) || node->hasTagName(strikeTag)
465         || node->hasTagName(iTag) || node->hasTagName(emTag) || node->hasTagName(bTag) || node->hasTagName(strongTag))
466         return true;
467     RefPtr<CSSMutableStyleDeclaration> style = styleFromMatchedRulesAndInlineDecl(node);
468     if (!style)
469         return false;
470     return !propertyMissingOrEqualToNone(style.get(), CSSPropertyTextDecoration);
471 }
472 
shouldIncludeWrapperForFullySelectedRoot(Node * fullySelectedRoot,CSSMutableStyleDeclaration * style)473 static bool shouldIncludeWrapperForFullySelectedRoot(Node* fullySelectedRoot, CSSMutableStyleDeclaration* style)
474 {
475     if (fullySelectedRoot->isElementNode() && static_cast<Element*>(fullySelectedRoot)->hasAttribute(backgroundAttr))
476         return true;
477 
478     return style->getPropertyCSSValue(CSSPropertyBackgroundImage) || style->getPropertyCSSValue(CSSPropertyBackgroundColor);
479 }
480 
highestAncestorToWrapMarkup(const Range * range,Node * fullySelectedRoot,EAnnotateForInterchange shouldAnnotate)481 static Node* highestAncestorToWrapMarkup(const Range* range, Node* fullySelectedRoot, EAnnotateForInterchange shouldAnnotate)
482 {
483     ExceptionCode ec;
484     Node* commonAncestor = range->commonAncestorContainer(ec);
485     ASSERT(commonAncestor);
486     Node* specialCommonAncestor = 0;
487     if (shouldAnnotate == AnnotateForInterchange) {
488         // Include ancestors that aren't completely inside the range but are required to retain
489         // the structure and appearance of the copied markup.
490         specialCommonAncestor = ancestorToRetainStructureAndAppearance(commonAncestor);
491 
492         // Retain the Mail quote level by including all ancestor mail block quotes.
493         if (Node* highestMailBlockquote = highestEnclosingNodeOfType(firstPositionInOrBeforeNode(range->firstNode()), isMailBlockquote, CanCrossEditingBoundary))
494             specialCommonAncestor = highestMailBlockquote;
495     }
496 
497     Node* checkAncestor = specialCommonAncestor ? specialCommonAncestor : commonAncestor;
498     if (checkAncestor->renderer()) {
499         Node* newSpecialCommonAncestor = highestEnclosingNodeOfType(firstPositionInNode(checkAncestor), &isElementPresentational);
500         if (newSpecialCommonAncestor)
501             specialCommonAncestor = newSpecialCommonAncestor;
502     }
503 
504     // If a single tab is selected, commonAncestor will be a text node inside a tab span.
505     // If two or more tabs are selected, commonAncestor will be the tab span.
506     // In either case, if there is a specialCommonAncestor already, it will necessarily be above
507     // any tab span that needs to be included.
508     if (!specialCommonAncestor && isTabSpanTextNode(commonAncestor))
509         specialCommonAncestor = commonAncestor->parentNode();
510     if (!specialCommonAncestor && isTabSpanNode(commonAncestor))
511         specialCommonAncestor = commonAncestor;
512 
513     if (Node *enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor : commonAncestor), aTag))
514         specialCommonAncestor = enclosingAnchor;
515 
516     if (shouldAnnotate == AnnotateForInterchange && fullySelectedRoot) {
517         RefPtr<CSSMutableStyleDeclaration> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot);
518         if (shouldIncludeWrapperForFullySelectedRoot(fullySelectedRoot, fullySelectedRootStyle.get()))
519             specialCommonAncestor = fullySelectedRoot;
520     }
521     return specialCommonAncestor;
522 }
523 
524 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange?
525 // FIXME: At least, annotation and style info should probably not be included in range.markupString()
createMarkup(const Range * range,Vector<Node * > * nodes,EAnnotateForInterchange shouldAnnotate,bool convertBlocksToInlines,EAbsoluteURLs shouldResolveURLs)526 String createMarkup(const Range* range, Vector<Node*>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs)
527 {
528     DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
529 
530     if (!range)
531         return "";
532 
533     Document* document = range->ownerDocument();
534     if (!document)
535         return "";
536 
537     // Disable the delete button so it's elements are not serialized into the markup,
538     // but make sure neither endpoint is inside the delete user interface.
539     Frame* frame = document->frame();
540     DeleteButtonController* deleteButton = frame ? frame->editor()->deleteButtonController() : 0;
541     RefPtr<Range> updatedRange = avoidIntersectionWithNode(range, deleteButton ? deleteButton->containerElement() : 0);
542     if (!updatedRange)
543         return "";
544 
545     if (deleteButton)
546         deleteButton->disable();
547 
548     ExceptionCode ec = 0;
549     bool collapsed = updatedRange->collapsed(ec);
550     ASSERT(!ec);
551     if (collapsed)
552         return "";
553     Node* commonAncestor = updatedRange->commonAncestorContainer(ec);
554     ASSERT(!ec);
555     if (!commonAncestor)
556         return "";
557 
558     document->updateLayoutIgnorePendingStylesheets();
559 
560     StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange.get());
561     Node* pastEnd = updatedRange->pastLastNode();
562 
563     Node* startNode = updatedRange->firstNode();
564     VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY);
565     VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY);
566     if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) {
567         if (visibleStart == visibleEnd.previous()) {
568             if (deleteButton)
569                 deleteButton->enable();
570             return interchangeNewlineString;
571         }
572 
573         accumulator.appendString(interchangeNewlineString);
574         startNode = visibleStart.next().deepEquivalent().deprecatedNode();
575 
576         ExceptionCode ec = 0;
577         if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ec) >= 0) {
578             ASSERT(!ec);
579             if (deleteButton)
580                 deleteButton->enable();
581             return interchangeNewlineString;
582         }
583         ASSERT(!ec);
584     }
585 
586     Node* body = enclosingNodeWithTag(firstPositionInNode(commonAncestor), bodyTag);
587     Node* fullySelectedRoot = 0;
588     // FIXME: Do this for all fully selected blocks, not just the body.
589     if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range))
590         fullySelectedRoot = body;
591 
592     Node* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange.get(), fullySelectedRoot, shouldAnnotate);
593 
594     Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd);
595 
596     if (specialCommonAncestor && lastClosed) {
597         // Also include all of the ancestors of lastClosed up to this special ancestor.
598         for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) {
599             if (ancestor == fullySelectedRoot && !convertBlocksToInlines) {
600                 RefPtr<CSSMutableStyleDeclaration> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot);
601 
602                 // Bring the background attribute over, but not as an attribute because a background attribute on a div
603                 // appears to have no effect.
604                 if (!fullySelectedRootStyle->getPropertyCSSValue(CSSPropertyBackgroundImage) && static_cast<Element*>(fullySelectedRoot)->hasAttribute(backgroundAttr))
605                     fullySelectedRootStyle->setProperty(CSSPropertyBackgroundImage, "url('" + static_cast<Element*>(fullySelectedRoot)->getAttribute(backgroundAttr) + "')");
606 
607                 if (fullySelectedRootStyle->length()) {
608                     // Reset the CSS properties to avoid an assertion error in addStyleMarkup().
609                     // This assertion is caused at least when we select all text of a <body> element whose
610                     // 'text-decoration' property is "inherit", and copy it.
611                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle.get(), CSSPropertyTextDecoration))
612                         fullySelectedRootStyle->setProperty(CSSPropertyTextDecoration, CSSValueNone);
613                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle.get(), CSSPropertyWebkitTextDecorationsInEffect))
614                         fullySelectedRootStyle->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
615                     accumulator.wrapWithStyleNode(fullySelectedRootStyle.get(), document, true);
616                 }
617             } else {
618                 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
619                 // so that styles that affect the exterior of the node are not included.
620                 accumulator.wrapWithNode(ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
621             }
622             if (nodes)
623                 nodes->append(ancestor);
624 
625             lastClosed = ancestor;
626 
627             if (ancestor == specialCommonAncestor)
628                 break;
629         }
630     }
631 
632     // Add a wrapper span with the styles that all of the nodes in the markup inherit.
633     ContainerNode* parentOfLastClosed = lastClosed ? lastClosed->parentNode() : 0;
634     if (parentOfLastClosed && parentOfLastClosed->renderer()) {
635         RefPtr<EditingStyle> style = EditingStyle::create(parentOfLastClosed, EditingStyle::InheritablePropertiesAndBackgroundColorInEffect);
636 
637         // Styles that Mail blockquotes contribute should only be placed on the Mail blockquote, to help
638         // us differentiate those styles from ones that the user has applied.  This helps us
639         // get the color of content pasted into blockquotes right.
640         style->removeStyleAddedByNode(enclosingNodeOfType(firstPositionInNode(parentOfLastClosed), isMailBlockquote, CanCrossEditingBoundary));
641 
642         if (!style->isEmpty())
643             accumulator.wrapWithStyleNode(style->style(), document);
644     }
645 
646     // FIXME: The interchange newline should be placed in the block that it's in, not after all of the content, unconditionally.
647     if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous()))
648         accumulator.appendString(interchangeNewlineString);
649 
650     if (deleteButton)
651         deleteButton->enable();
652 
653     return accumulator.takeResults();
654 }
655 
createFragmentFromMarkup(Document * document,const String & markup,const String & baseURL,FragmentScriptingPermission scriptingPermission)656 PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document* document, const String& markup, const String& baseURL, FragmentScriptingPermission scriptingPermission)
657 {
658     // We use a fake body element here to trick the HTML parser to using the
659     // InBody insertion mode.  Really, all this code is wrong and need to be
660     // changed not to use deprecatedCreateContextualFragment.
661     RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document);
662     // FIXME: This should not use deprecatedCreateContextualFragment
663     RefPtr<DocumentFragment> fragment = fakeBody->deprecatedCreateContextualFragment(markup, scriptingPermission);
664 
665     if (fragment && !baseURL.isEmpty() && baseURL != blankURL() && baseURL != document->baseURL())
666         completeURLs(fragment.get(), baseURL);
667 
668     return fragment.release();
669 }
670 
createMarkup(const Node * node,EChildrenOnly childrenOnly,Vector<Node * > * nodes,EAbsoluteURLs shouldResolveURLs)671 String createMarkup(const Node* node, EChildrenOnly childrenOnly, Vector<Node*>* nodes, EAbsoluteURLs shouldResolveURLs)
672 {
673     if (!node)
674         return "";
675 
676     HTMLElement* deleteButtonContainerElement = 0;
677     if (Frame* frame = node->document()->frame()) {
678         deleteButtonContainerElement = frame->editor()->deleteButtonController()->containerElement();
679         if (node->isDescendantOf(deleteButtonContainerElement))
680             return "";
681     }
682 
683     MarkupAccumulator accumulator(nodes, shouldResolveURLs);
684     return accumulator.serializeNodes(const_cast<Node*>(node), deleteButtonContainerElement, childrenOnly);
685 }
686 
fillContainerFromString(ContainerNode * paragraph,const String & string)687 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
688 {
689     Document* document = paragraph->document();
690 
691     ExceptionCode ec = 0;
692     if (string.isEmpty()) {
693         paragraph->appendChild(createBlockPlaceholderElement(document), ec);
694         ASSERT(!ec);
695         return;
696     }
697 
698     ASSERT(string.find('\n') == notFound);
699 
700     Vector<String> tabList;
701     string.split('\t', true, tabList);
702     String tabText = "";
703     bool first = true;
704     size_t numEntries = tabList.size();
705     for (size_t i = 0; i < numEntries; ++i) {
706         const String& s = tabList[i];
707 
708         // append the non-tab textual part
709         if (!s.isEmpty()) {
710             if (!tabText.isEmpty()) {
711                 paragraph->appendChild(createTabSpanElement(document, tabText), ec);
712                 ASSERT(!ec);
713                 tabText = "";
714             }
715             RefPtr<Node> textNode = document->createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
716             paragraph->appendChild(textNode.release(), ec);
717             ASSERT(!ec);
718         }
719 
720         // there is a tab after every entry, except the last entry
721         // (if the last character is a tab, the list gets an extra empty entry)
722         if (i + 1 != numEntries)
723             tabText.append('\t');
724         else if (!tabText.isEmpty()) {
725             paragraph->appendChild(createTabSpanElement(document, tabText), ec);
726             ASSERT(!ec);
727         }
728 
729         first = false;
730     }
731 }
732 
isPlainTextMarkup(Node * node)733 bool isPlainTextMarkup(Node *node)
734 {
735     if (!node->isElementNode() || !node->hasTagName(divTag) || static_cast<Element*>(node)->attributes()->length())
736         return false;
737 
738     if (node->childNodeCount() == 1 && (node->firstChild()->isTextNode() || (node->firstChild()->firstChild())))
739         return true;
740 
741     return (node->childNodeCount() == 2 && isTabSpanTextNode(node->firstChild()->firstChild()) && node->firstChild()->nextSibling()->isTextNode());
742 }
743 
createFragmentFromText(Range * context,const String & text)744 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
745 {
746     if (!context)
747         return 0;
748 
749     Node* styleNode = context->firstNode();
750     if (!styleNode) {
751         styleNode = context->startPosition().deprecatedNode();
752         if (!styleNode)
753             return 0;
754     }
755 
756     Document* document = styleNode->document();
757     RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
758 
759     if (text.isEmpty())
760         return fragment.release();
761 
762     String string = text;
763     string.replace("\r\n", "\n");
764     string.replace('\r', '\n');
765 
766     ExceptionCode ec = 0;
767     RenderObject* renderer = styleNode->renderer();
768     if (renderer && renderer->style()->preserveNewline()) {
769         fragment->appendChild(document->createTextNode(string), ec);
770         ASSERT(!ec);
771         if (string.endsWith("\n")) {
772             RefPtr<Element> element = createBreakElement(document);
773             element->setAttribute(classAttr, AppleInterchangeNewline);
774             fragment->appendChild(element.release(), ec);
775             ASSERT(!ec);
776         }
777         return fragment.release();
778     }
779 
780     // A string with no newlines gets added inline, rather than being put into a paragraph.
781     if (string.find('\n') == notFound) {
782         fillContainerFromString(fragment.get(), string);
783         return fragment.release();
784     }
785 
786     // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
787     Node* blockNode = enclosingBlock(context->firstNode());
788     Element* block = static_cast<Element*>(blockNode);
789     bool useClonesOfEnclosingBlock = blockNode
790         && blockNode->isElementNode()
791         && !block->hasTagName(bodyTag)
792         && !block->hasTagName(htmlTag)
793         && block != editableRootForPosition(context->startPosition());
794 
795     Vector<String> list;
796     string.split('\n', true, list); // true gets us empty strings in the list
797     size_t numLines = list.size();
798     for (size_t i = 0; i < numLines; ++i) {
799         const String& s = list[i];
800 
801         RefPtr<Element> element;
802         if (s.isEmpty() && i + 1 == numLines) {
803             // For last line, use the "magic BR" rather than a P.
804             element = createBreakElement(document);
805             element->setAttribute(classAttr, AppleInterchangeNewline);
806         } else {
807             if (useClonesOfEnclosingBlock)
808                 element = block->cloneElementWithoutChildren();
809             else
810                 element = createDefaultParagraphElement(document);
811             fillContainerFromString(element.get(), s);
812         }
813         fragment->appendChild(element.release(), ec);
814         ASSERT(!ec);
815     }
816     return fragment.release();
817 }
818 
createFragmentFromNodes(Document * document,const Vector<Node * > & nodes)819 PassRefPtr<DocumentFragment> createFragmentFromNodes(Document *document, const Vector<Node*>& nodes)
820 {
821     if (!document)
822         return 0;
823 
824     // disable the delete button so it's elements are not serialized into the markup
825     if (document->frame())
826         document->frame()->editor()->deleteButtonController()->disable();
827 
828     RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
829 
830     ExceptionCode ec = 0;
831     size_t size = nodes.size();
832     for (size_t i = 0; i < size; ++i) {
833         RefPtr<Element> element = createDefaultParagraphElement(document);
834         element->appendChild(nodes[i], ec);
835         ASSERT(!ec);
836         fragment->appendChild(element.release(), ec);
837         ASSERT(!ec);
838     }
839 
840     if (document->frame())
841         document->frame()->editor()->deleteButtonController()->enable();
842 
843     return fragment.release();
844 }
845 
createFullMarkup(const Node * node)846 String createFullMarkup(const Node* node)
847 {
848     if (!node)
849         return String();
850 
851     Document* document = node->document();
852     if (!document)
853         return String();
854 
855     Frame* frame = document->frame();
856     if (!frame)
857         return String();
858 
859     // FIXME: This is never "for interchange". Is that right?
860     String markupString = createMarkup(node, IncludeNode, 0);
861     Node::NodeType nodeType = node->nodeType();
862     if (nodeType != Node::DOCUMENT_NODE && nodeType != Node::DOCUMENT_TYPE_NODE)
863         markupString = frame->documentTypeString() + markupString;
864 
865     return markupString;
866 }
867 
createFullMarkup(const Range * range)868 String createFullMarkup(const Range* range)
869 {
870     if (!range)
871         return String();
872 
873     Node* node = range->startContainer();
874     if (!node)
875         return String();
876 
877     Document* document = node->document();
878     if (!document)
879         return String();
880 
881     Frame* frame = document->frame();
882     if (!frame)
883         return String();
884 
885     // FIXME: This is always "for interchange". Is that right? See the previous method.
886     return frame->documentTypeString() + createMarkup(range, 0, AnnotateForInterchange);
887 }
888 
urlToMarkup(const KURL & url,const String & title)889 String urlToMarkup(const KURL& url, const String& title)
890 {
891     Vector<UChar> markup;
892     append(markup, "<a href=\"");
893     append(markup, url.string());
894     append(markup, "\">");
895     appendCharactersReplacingEntities(markup, title.characters(), title.length(), EntityMaskInPCDATA);
896     append(markup, "</a>");
897     return String::adopt(markup);
898 }
899 
imageToMarkup(const KURL & url,Element * element)900 String imageToMarkup(const KURL& url, Element* element)
901 {
902     Vector<UChar> markup;
903     append(markup, "<img src=\"");
904     append(markup, url.string());
905     append(markup, "\"");
906 
907     NamedNodeMap* attrs = element->attributes();
908     unsigned length = attrs->length();
909     for (unsigned i = 0; i < length; ++i) {
910         Attribute* attr = attrs->attributeItem(i);
911         if (attr->localName() == "src")
912             continue;
913         append(markup, " ");
914         append(markup, attr->localName());
915         append(markup, "=\"");
916         appendCharactersReplacingEntities(markup, attr->value().characters(), attr->value().length(), EntityMaskInAttributeValue);
917         append(markup, "\"");
918     }
919 
920     append(markup, "/>");
921     return String::adopt(markup);
922 }
923 
924 }
925