|
1 /* |
|
2 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved. |
|
3 * |
|
4 * Redistribution and use in source and binary forms, with or without |
|
5 * modification, are permitted provided that the following conditions |
|
6 * are met: |
|
7 * 1. Redistributions of source code must retain the above copyright |
|
8 * notice, this list of conditions and the following disclaimer. |
|
9 * 2. Redistributions in binary form must reproduce the above copyright |
|
10 * notice, this list of conditions and the following disclaimer in the |
|
11 * documentation and/or other materials provided with the distribution. |
|
12 * |
|
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY |
|
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
|
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
|
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR |
|
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
|
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
|
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR |
|
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY |
|
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
|
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
|
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
|
24 */ |
|
25 |
|
26 #include "config.h" |
|
27 #include "ReplaceSelectionCommand.h" |
|
28 |
|
29 #include "ApplyStyleCommand.h" |
|
30 #include "BeforeTextInsertedEvent.h" |
|
31 #include "BreakBlockquoteCommand.h" |
|
32 #include "CSSComputedStyleDeclaration.h" |
|
33 #include "CSSMutableStyleDeclaration.h" |
|
34 #include "CSSProperty.h" |
|
35 #include "CSSPropertyNames.h" |
|
36 #include "CSSValueKeywords.h" |
|
37 #include "Document.h" |
|
38 #include "DocumentFragment.h" |
|
39 #include "EditingText.h" |
|
40 #include "Element.h" |
|
41 #include "EventNames.h" |
|
42 #include "Frame.h" |
|
43 #include "HTMLElement.h" |
|
44 #include "HTMLInputElement.h" |
|
45 #include "HTMLInterchange.h" |
|
46 #include "HTMLNames.h" |
|
47 #include "SelectionController.h" |
|
48 #include "SmartReplace.h" |
|
49 #include "TextIterator.h" |
|
50 #include "htmlediting.h" |
|
51 #include "markup.h" |
|
52 #include "visible_units.h" |
|
53 #include <wtf/StdLibExtras.h> |
|
54 |
|
55 namespace WebCore { |
|
56 |
|
57 using namespace HTMLNames; |
|
58 |
|
59 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment }; |
|
60 |
|
61 // --- ReplacementFragment helper class |
|
62 |
|
63 class ReplacementFragment : public Noncopyable { |
|
64 public: |
|
65 ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&); |
|
66 |
|
67 Node* firstChild() const; |
|
68 Node* lastChild() const; |
|
69 |
|
70 bool isEmpty() const; |
|
71 |
|
72 bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; } |
|
73 bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; } |
|
74 |
|
75 void removeNode(PassRefPtr<Node>); |
|
76 void removeNodePreservingChildren(Node*); |
|
77 |
|
78 private: |
|
79 PassRefPtr<Node> insertFragmentForTestRendering(Node* context); |
|
80 void removeUnrenderedNodes(Node*); |
|
81 void restoreTestRenderingNodesToFragment(Node*); |
|
82 void removeInterchangeNodes(Node*); |
|
83 |
|
84 void insertNodeBefore(PassRefPtr<Node> node, Node* refNode); |
|
85 |
|
86 RefPtr<Document> m_document; |
|
87 RefPtr<DocumentFragment> m_fragment; |
|
88 bool m_matchStyle; |
|
89 bool m_hasInterchangeNewlineAtStart; |
|
90 bool m_hasInterchangeNewlineAtEnd; |
|
91 }; |
|
92 |
|
93 static bool isInterchangeNewlineNode(const Node *node) |
|
94 { |
|
95 DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline)); |
|
96 return node && node->hasTagName(brTag) && |
|
97 static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString; |
|
98 } |
|
99 |
|
100 static bool isInterchangeConvertedSpaceSpan(const Node *node) |
|
101 { |
|
102 DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace)); |
|
103 return node->isHTMLElement() && |
|
104 static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString; |
|
105 } |
|
106 |
|
107 static Position positionAvoidingPrecedingNodes(Position pos) |
|
108 { |
|
109 // If we're already on a break, it's probably a placeholder and we shouldn't change our position. |
|
110 if (pos.node()->hasTagName(brTag)) |
|
111 return pos; |
|
112 |
|
113 // We also stop when changing block flow elements because even though the visual position is the |
|
114 // same. E.g., |
|
115 // <div>foo^</div>^ |
|
116 // The two positions above are the same visual position, but we want to stay in the same block. |
|
117 Node* stopNode = pos.node()->enclosingBlockFlowElement(); |
|
118 while (stopNode != pos.node() && VisiblePosition(pos) == VisiblePosition(pos.next())) |
|
119 pos = pos.next(); |
|
120 return pos; |
|
121 } |
|
122 |
|
123 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const VisibleSelection& selection) |
|
124 : m_document(document), |
|
125 m_fragment(fragment), |
|
126 m_matchStyle(matchStyle), |
|
127 m_hasInterchangeNewlineAtStart(false), |
|
128 m_hasInterchangeNewlineAtEnd(false) |
|
129 { |
|
130 if (!m_document) |
|
131 return; |
|
132 if (!m_fragment) |
|
133 return; |
|
134 if (!m_fragment->firstChild()) |
|
135 return; |
|
136 |
|
137 Element* editableRoot = selection.rootEditableElement(); |
|
138 ASSERT(editableRoot); |
|
139 if (!editableRoot) |
|
140 return; |
|
141 |
|
142 Node* shadowAncestorNode = editableRoot->shadowAncestorNode(); |
|
143 |
|
144 if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) && |
|
145 // FIXME: Remove these checks once textareas and textfields actually register an event handler. |
|
146 !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) && |
|
147 editableRoot->isContentRichlyEditable()) { |
|
148 removeInterchangeNodes(m_fragment.get()); |
|
149 return; |
|
150 } |
|
151 |
|
152 Node* styleNode = selection.base().node(); |
|
153 RefPtr<Node> holder = insertFragmentForTestRendering(styleNode); |
|
154 |
|
155 RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange(); |
|
156 String text = plainText(range.get()); |
|
157 // Give the root a chance to change the text. |
|
158 RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text); |
|
159 ExceptionCode ec = 0; |
|
160 editableRoot->dispatchEvent(evt, ec); |
|
161 ASSERT(ec == 0); |
|
162 if (text != evt->text() || !editableRoot->isContentRichlyEditable()) { |
|
163 restoreTestRenderingNodesToFragment(holder.get()); |
|
164 removeNode(holder); |
|
165 |
|
166 m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text()); |
|
167 if (!m_fragment->firstChild()) |
|
168 return; |
|
169 holder = insertFragmentForTestRendering(styleNode); |
|
170 } |
|
171 |
|
172 removeInterchangeNodes(holder.get()); |
|
173 |
|
174 removeUnrenderedNodes(holder.get()); |
|
175 restoreTestRenderingNodesToFragment(holder.get()); |
|
176 removeNode(holder); |
|
177 } |
|
178 |
|
179 bool ReplacementFragment::isEmpty() const |
|
180 { |
|
181 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd; |
|
182 } |
|
183 |
|
184 Node *ReplacementFragment::firstChild() const |
|
185 { |
|
186 return m_fragment ? m_fragment->firstChild() : 0; |
|
187 } |
|
188 |
|
189 Node *ReplacementFragment::lastChild() const |
|
190 { |
|
191 return m_fragment ? m_fragment->lastChild() : 0; |
|
192 } |
|
193 |
|
194 void ReplacementFragment::removeNodePreservingChildren(Node *node) |
|
195 { |
|
196 if (!node) |
|
197 return; |
|
198 |
|
199 while (RefPtr<Node> n = node->firstChild()) { |
|
200 removeNode(n); |
|
201 insertNodeBefore(n.release(), node); |
|
202 } |
|
203 removeNode(node); |
|
204 } |
|
205 |
|
206 void ReplacementFragment::removeNode(PassRefPtr<Node> node) |
|
207 { |
|
208 if (!node) |
|
209 return; |
|
210 |
|
211 Node *parent = node->parentNode(); |
|
212 if (!parent) |
|
213 return; |
|
214 |
|
215 ExceptionCode ec = 0; |
|
216 parent->removeChild(node.get(), ec); |
|
217 ASSERT(ec == 0); |
|
218 } |
|
219 |
|
220 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode) |
|
221 { |
|
222 if (!node || !refNode) |
|
223 return; |
|
224 |
|
225 Node* parent = refNode->parentNode(); |
|
226 if (!parent) |
|
227 return; |
|
228 |
|
229 ExceptionCode ec = 0; |
|
230 parent->insertBefore(node, refNode, ec); |
|
231 ASSERT(ec == 0); |
|
232 } |
|
233 |
|
234 PassRefPtr<Node> ReplacementFragment::insertFragmentForTestRendering(Node* context) |
|
235 { |
|
236 Node* body = m_document->body(); |
|
237 if (!body) |
|
238 return 0; |
|
239 |
|
240 RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get()); |
|
241 |
|
242 ExceptionCode ec = 0; |
|
243 |
|
244 // Copy the whitespace and user-select style from the context onto this element. |
|
245 // FIXME: We should examine other style properties to see if they would be appropriate to consider during the test rendering. |
|
246 Node* n = context; |
|
247 while (n && !n->isElementNode()) |
|
248 n = n->parentNode(); |
|
249 if (n) { |
|
250 RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n); |
|
251 CSSStyleDeclaration* style = holder->style(); |
|
252 style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec); |
|
253 ASSERT(ec == 0); |
|
254 style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec); |
|
255 ASSERT(ec == 0); |
|
256 } |
|
257 |
|
258 holder->appendChild(m_fragment, ec); |
|
259 ASSERT(ec == 0); |
|
260 |
|
261 body->appendChild(holder.get(), ec); |
|
262 ASSERT(ec == 0); |
|
263 |
|
264 m_document->updateLayoutIgnorePendingStylesheets(); |
|
265 |
|
266 return holder.release(); |
|
267 } |
|
268 |
|
269 void ReplacementFragment::restoreTestRenderingNodesToFragment(Node *holder) |
|
270 { |
|
271 if (!holder) |
|
272 return; |
|
273 |
|
274 ExceptionCode ec = 0; |
|
275 while (RefPtr<Node> node = holder->firstChild()) { |
|
276 holder->removeChild(node.get(), ec); |
|
277 ASSERT(ec == 0); |
|
278 m_fragment->appendChild(node.get(), ec); |
|
279 ASSERT(ec == 0); |
|
280 } |
|
281 } |
|
282 |
|
283 void ReplacementFragment::removeUnrenderedNodes(Node* holder) |
|
284 { |
|
285 Vector<Node*> unrendered; |
|
286 |
|
287 for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder)) |
|
288 if (!isNodeRendered(node) && !isTableStructureNode(node)) |
|
289 unrendered.append(node); |
|
290 |
|
291 size_t n = unrendered.size(); |
|
292 for (size_t i = 0; i < n; ++i) |
|
293 removeNode(unrendered[i]); |
|
294 } |
|
295 |
|
296 void ReplacementFragment::removeInterchangeNodes(Node* container) |
|
297 { |
|
298 // Interchange newlines at the "start" of the incoming fragment must be |
|
299 // either the first node in the fragment or the first leaf in the fragment. |
|
300 Node* node = container->firstChild(); |
|
301 while (node) { |
|
302 if (isInterchangeNewlineNode(node)) { |
|
303 m_hasInterchangeNewlineAtStart = true; |
|
304 removeNode(node); |
|
305 break; |
|
306 } |
|
307 node = node->firstChild(); |
|
308 } |
|
309 if (!container->hasChildNodes()) |
|
310 return; |
|
311 // Interchange newlines at the "end" of the incoming fragment must be |
|
312 // either the last node in the fragment or the last leaf in the fragment. |
|
313 node = container->lastChild(); |
|
314 while (node) { |
|
315 if (isInterchangeNewlineNode(node)) { |
|
316 m_hasInterchangeNewlineAtEnd = true; |
|
317 removeNode(node); |
|
318 break; |
|
319 } |
|
320 node = node->lastChild(); |
|
321 } |
|
322 |
|
323 node = container->firstChild(); |
|
324 while (node) { |
|
325 Node *next = node->traverseNextNode(); |
|
326 if (isInterchangeConvertedSpaceSpan(node)) { |
|
327 RefPtr<Node> n = 0; |
|
328 while ((n = node->firstChild())) { |
|
329 removeNode(n); |
|
330 insertNodeBefore(n, node); |
|
331 } |
|
332 removeNode(node); |
|
333 if (n) |
|
334 next = n->traverseNextNode(); |
|
335 } |
|
336 node = next; |
|
337 } |
|
338 } |
|
339 |
|
340 ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment, |
|
341 bool selectReplacement, bool smartReplace, bool matchStyle, bool preventNesting, bool movingParagraph, |
|
342 EditAction editAction) |
|
343 : CompositeEditCommand(document), |
|
344 m_selectReplacement(selectReplacement), |
|
345 m_smartReplace(smartReplace), |
|
346 m_matchStyle(matchStyle), |
|
347 m_documentFragment(fragment), |
|
348 m_preventNesting(preventNesting), |
|
349 m_movingParagraph(movingParagraph), |
|
350 m_editAction(editAction), |
|
351 m_shouldMergeEnd(false) |
|
352 { |
|
353 } |
|
354 |
|
355 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent) |
|
356 { |
|
357 Position existing = endOfExistingContent.deepEquivalent(); |
|
358 Position inserted = endOfInsertedContent.deepEquivalent(); |
|
359 bool isInsideMailBlockquote = nearestMailBlockquote(inserted.node()); |
|
360 return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted)); |
|
361 } |
|
362 |
|
363 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote) |
|
364 { |
|
365 if (m_movingParagraph) |
|
366 return false; |
|
367 |
|
368 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent()); |
|
369 VisiblePosition prev = startOfInsertedContent.previous(true); |
|
370 if (prev.isNull()) |
|
371 return false; |
|
372 |
|
373 // When we have matching quote levels, its ok to merge more frequently. |
|
374 // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph. |
|
375 // And we should only merge here if the selection start was inside a mail blockquote. This prevents against removing a |
|
376 // blockquote from newly pasted quoted content that was pasted into an unquoted position. If that unquoted position happens |
|
377 // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content. |
|
378 if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent())) |
|
379 return true; |
|
380 |
|
381 return !selectionStartWasStartOfParagraph && |
|
382 !fragmentHasInterchangeNewlineAtStart && |
|
383 isStartOfParagraph(startOfInsertedContent) && |
|
384 !startOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) && |
|
385 shouldMerge(startOfInsertedContent, prev); |
|
386 } |
|
387 |
|
388 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph) |
|
389 { |
|
390 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent()); |
|
391 VisiblePosition next = endOfInsertedContent.next(true); |
|
392 if (next.isNull()) |
|
393 return false; |
|
394 |
|
395 return !selectionEndWasEndOfParagraph && |
|
396 isEndOfParagraph(endOfInsertedContent) && |
|
397 !endOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) && |
|
398 shouldMerge(endOfInsertedContent, next); |
|
399 } |
|
400 |
|
401 static bool isMailPasteAsQuotationNode(const Node* node) |
|
402 { |
|
403 return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation; |
|
404 } |
|
405 |
|
406 // Wrap CompositeEditCommand::removeNodePreservingChildren() so we can update the nodes we track |
|
407 void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node) |
|
408 { |
|
409 if (m_firstNodeInserted == node) |
|
410 m_firstNodeInserted = node->traverseNextNode(); |
|
411 if (m_lastLeafInserted == node) |
|
412 m_lastLeafInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling(); |
|
413 CompositeEditCommand::removeNodePreservingChildren(node); |
|
414 } |
|
415 |
|
416 // Wrap CompositeEditCommand::removeNodeAndPruneAncestors() so we can update the nodes we track |
|
417 void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node) |
|
418 { |
|
419 // prepare in case m_firstNodeInserted and/or m_lastLeafInserted get removed |
|
420 // FIXME: shouldn't m_lastLeafInserted be adjusted using traversePreviousNode()? |
|
421 Node* afterFirst = m_firstNodeInserted ? m_firstNodeInserted->traverseNextSibling() : 0; |
|
422 Node* afterLast = m_lastLeafInserted ? m_lastLeafInserted->traverseNextSibling() : 0; |
|
423 |
|
424 CompositeEditCommand::removeNodeAndPruneAncestors(node); |
|
425 |
|
426 // adjust m_firstNodeInserted and m_lastLeafInserted since either or both may have been removed |
|
427 if (m_lastLeafInserted && !m_lastLeafInserted->inDocument()) |
|
428 m_lastLeafInserted = afterLast; |
|
429 if (m_firstNodeInserted && !m_firstNodeInserted->inDocument()) |
|
430 m_firstNodeInserted = m_lastLeafInserted && m_lastLeafInserted->inDocument() ? afterFirst : 0; |
|
431 } |
|
432 |
|
433 static bool isHeaderElement(Node* a) |
|
434 { |
|
435 if (!a) |
|
436 return false; |
|
437 |
|
438 return a->hasTagName(h1Tag) || |
|
439 a->hasTagName(h2Tag) || |
|
440 a->hasTagName(h3Tag) || |
|
441 a->hasTagName(h4Tag) || |
|
442 a->hasTagName(h5Tag); |
|
443 } |
|
444 |
|
445 static bool haveSameTagName(Node* a, Node* b) |
|
446 { |
|
447 return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName(); |
|
448 } |
|
449 |
|
450 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination) |
|
451 { |
|
452 if (source.isNull() || destination.isNull()) |
|
453 return false; |
|
454 |
|
455 Node* sourceNode = source.deepEquivalent().node(); |
|
456 Node* destinationNode = destination.deepEquivalent().node(); |
|
457 Node* sourceBlock = enclosingBlock(sourceNode); |
|
458 Node* destinationBlock = enclosingBlock(destinationNode); |
|
459 return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) && |
|
460 sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) && |
|
461 enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) && |
|
462 enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) && |
|
463 (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) && |
|
464 // Don't merge to or from a position before or after a block because it would |
|
465 // be a no-op and cause infinite recursion. |
|
466 !isBlock(sourceNode) && !isBlock(destinationNode); |
|
467 } |
|
468 |
|
469 // Style rules that match just inserted elements could change their appearance, like |
|
470 // a div inserted into a document with div { display:inline; }. |
|
471 void ReplaceSelectionCommand::negateStyleRulesThatAffectAppearance() |
|
472 { |
|
473 for (RefPtr<Node> node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) { |
|
474 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance |
|
475 if (isStyleSpan(node.get())) { |
|
476 HTMLElement* e = static_cast<HTMLElement*>(node.get()); |
|
477 // There are other styles that style rules can give to style spans, |
|
478 // but these are the two important ones because they'll prevent |
|
479 // inserted content from appearing in the right paragraph. |
|
480 // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent |
|
481 // results. We already know one issue because td elements ignore their display property |
|
482 // in quirks mode (which Mail.app is always in). We should look for an alternative. |
|
483 if (isBlock(e)) |
|
484 e->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline); |
|
485 if (e->renderer() && e->renderer()->style()->floating() != FNONE) |
|
486 e->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone); |
|
487 |
|
488 // Undo the effects of page zoom if we have an absolute font size. When we copy, we |
|
489 // compute the new font size as an absolute size so pasting will cause the zoom to be |
|
490 // applied twice. |
|
491 if (e->renderer() && e->renderer()->style() && e->renderer()->style()->effectiveZoom() != 1.0 |
|
492 && e->renderer()->style()->fontDescription().isAbsoluteSize()) { |
|
493 float newSize = e->renderer()->style()->fontDescription().specifiedSize() / e->renderer()->style()->effectiveZoom(); |
|
494 ExceptionCode ec = 0; |
|
495 e->style()->setProperty(CSSPropertyFontSize, String::number(newSize), false, ec); |
|
496 ASSERT(!ec); |
|
497 } |
|
498 } |
|
499 if (node == m_lastLeafInserted) |
|
500 break; |
|
501 } |
|
502 } |
|
503 |
|
504 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds() |
|
505 { |
|
506 document()->updateLayoutIgnorePendingStylesheets(); |
|
507 if (!m_lastLeafInserted->renderer() && |
|
508 m_lastLeafInserted->isTextNode() && |
|
509 !enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), selectTag) && |
|
510 !enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), scriptTag)) { |
|
511 if (m_firstNodeInserted == m_lastLeafInserted) { |
|
512 removeNode(m_lastLeafInserted.get()); |
|
513 m_lastLeafInserted = 0; |
|
514 m_firstNodeInserted = 0; |
|
515 return; |
|
516 } |
|
517 RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode(); |
|
518 removeNode(m_lastLeafInserted.get()); |
|
519 m_lastLeafInserted = previous; |
|
520 } |
|
521 |
|
522 // We don't have to make sure that m_firstNodeInserted isn't inside a select or script element, because |
|
523 // it is a top level node in the fragment and the user can't insert into those elements. |
|
524 if (!m_firstNodeInserted->renderer() && |
|
525 m_firstNodeInserted->isTextNode()) { |
|
526 if (m_firstNodeInserted == m_lastLeafInserted) { |
|
527 removeNode(m_firstNodeInserted.get()); |
|
528 m_firstNodeInserted = 0; |
|
529 m_lastLeafInserted = 0; |
|
530 return; |
|
531 } |
|
532 RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling(); |
|
533 removeNode(m_firstNodeInserted.get()); |
|
534 m_firstNodeInserted = next; |
|
535 } |
|
536 } |
|
537 |
|
538 void ReplaceSelectionCommand::handlePasteAsQuotationNode() |
|
539 { |
|
540 Node* node = m_firstNodeInserted.get(); |
|
541 if (isMailPasteAsQuotationNode(node)) |
|
542 removeNodeAttribute(static_cast<Element*>(node), classAttr); |
|
543 } |
|
544 |
|
545 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() |
|
546 { |
|
547 Node* lastNode = m_lastLeafInserted.get(); |
|
548 // FIXME: Why is this hack here? What's special about <select> tags? |
|
549 Node* enclosingSelect = enclosingNodeWithTag(firstDeepEditingPositionForNode(lastNode), selectTag); |
|
550 if (enclosingSelect) |
|
551 lastNode = enclosingSelect; |
|
552 return lastDeepEditingPositionForNode(lastNode); |
|
553 } |
|
554 |
|
555 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() |
|
556 { |
|
557 // Return the inserted content's first VisiblePosition. |
|
558 return VisiblePosition(nextCandidate(positionInParentBeforeNode(m_firstNodeInserted.get()))); |
|
559 } |
|
560 |
|
561 // Remove style spans before insertion if they are unnecessary. It's faster because we'll |
|
562 // avoid doing a layout. |
|
563 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos) |
|
564 { |
|
565 Node* topNode = fragment.firstChild(); |
|
566 |
|
567 // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans) |
|
568 // and doesn't receive the optimization. |
|
569 if (isMailPasteAsQuotationNode(topNode) || nearestMailBlockquote(topNode)) |
|
570 return false; |
|
571 |
|
572 // Either there are no style spans in the fragment or a WebKit client has added content to the fragment |
|
573 // before inserting it. Look for and handle style spans after insertion. |
|
574 if (!isStyleSpan(topNode)) |
|
575 return false; |
|
576 |
|
577 Node* sourceDocumentStyleSpan = topNode; |
|
578 RefPtr<Node> copiedRangeStyleSpan = sourceDocumentStyleSpan->firstChild(); |
|
579 |
|
580 RefPtr<CSSMutableStyleDeclaration> styleAtInsertionPos = ApplyStyleCommand::editingStyleAtPosition(rangeCompliantEquivalent(insertionPos)); |
|
581 |
|
582 String styleText = styleAtInsertionPos->cssText(); |
|
583 |
|
584 if (styleText == static_cast<Element*>(sourceDocumentStyleSpan)->getAttribute(styleAttr)) { |
|
585 fragment.removeNodePreservingChildren(sourceDocumentStyleSpan); |
|
586 if (!isStyleSpan(copiedRangeStyleSpan.get())) |
|
587 return true; |
|
588 } |
|
589 |
|
590 if (isStyleSpan(copiedRangeStyleSpan.get()) && styleText == static_cast<Element*>(copiedRangeStyleSpan.get())->getAttribute(styleAttr)) { |
|
591 fragment.removeNodePreservingChildren(copiedRangeStyleSpan.get()); |
|
592 return true; |
|
593 } |
|
594 |
|
595 return false; |
|
596 } |
|
597 |
|
598 // At copy time, WebKit wraps copied content in a span that contains the source document's |
|
599 // default styles. If the copied Range inherits any other styles from its ancestors, we put |
|
600 // those styles on a second span. |
|
601 // This function removes redundant styles from those spans, and removes the spans if all their |
|
602 // styles are redundant. |
|
603 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>. |
|
604 // We should remove styles from spans that are overridden by all of their children, either here |
|
605 // or at copy time. |
|
606 void ReplaceSelectionCommand::handleStyleSpans() |
|
607 { |
|
608 Node* sourceDocumentStyleSpan = 0; |
|
609 Node* copiedRangeStyleSpan = 0; |
|
610 // The style span that contains the source document's default style should be at |
|
611 // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation), |
|
612 // so search for the top level style span instead of assuming it's at the top. |
|
613 for (Node* node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) { |
|
614 if (isStyleSpan(node)) { |
|
615 sourceDocumentStyleSpan = node; |
|
616 // If the copied Range's common ancestor had user applied inheritable styles |
|
617 // on it, they'll be on a second style span, just below the one that holds the |
|
618 // document defaults. |
|
619 if (isStyleSpan(node->firstChild())) |
|
620 copiedRangeStyleSpan = node->firstChild(); |
|
621 break; |
|
622 } |
|
623 } |
|
624 |
|
625 // There might not be any style spans if we're pasting from another application or if |
|
626 // we are here because of a document.execCommand("InsertHTML", ...) call. |
|
627 if (!sourceDocumentStyleSpan) |
|
628 return; |
|
629 |
|
630 RefPtr<CSSMutableStyleDeclaration> sourceDocumentStyle = static_cast<HTMLElement*>(sourceDocumentStyleSpan)->getInlineStyleDecl()->copy(); |
|
631 Node* context = sourceDocumentStyleSpan->parentNode(); |
|
632 |
|
633 // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region, |
|
634 // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>. |
|
635 Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : nearestMailBlockquote(context); |
|
636 if (blockquoteNode) { |
|
637 RefPtr<CSSMutableStyleDeclaration> blockquoteStyle = ApplyStyleCommand::editingStyleAtPosition(Position(blockquoteNode, 0)); |
|
638 RefPtr<CSSMutableStyleDeclaration> parentStyle = ApplyStyleCommand::editingStyleAtPosition(Position(blockquoteNode->parentNode(), 0)); |
|
639 parentStyle->diff(blockquoteStyle.get()); |
|
640 |
|
641 CSSMutableStyleDeclaration::const_iterator end = blockquoteStyle->end(); |
|
642 for (CSSMutableStyleDeclaration::const_iterator it = blockquoteStyle->begin(); it != end; ++it) { |
|
643 const CSSProperty& property = *it; |
|
644 sourceDocumentStyle->removeProperty(property.id()); |
|
645 } |
|
646 |
|
647 context = blockquoteNode->parentNode(); |
|
648 } |
|
649 |
|
650 // This operation requires that only editing styles to be removed from sourceDocumentStyle. |
|
651 prepareEditingStyleToApplyAt(sourceDocumentStyle.get(), Position(context, 0)); |
|
652 |
|
653 // Remove block properties in the span's style. This prevents properties that probably have no effect |
|
654 // currently from affecting blocks later if the style is cloned for a new block element during a future |
|
655 // editing operation. |
|
656 // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked |
|
657 // with block styles by the editing engine used to style them. WebKit doesn't do this, but others might. |
|
658 sourceDocumentStyle->removeBlockProperties(); |
|
659 |
|
660 // The styles on sourceDocumentStyleSpan are all redundant, and there is no copiedRangeStyleSpan |
|
661 // to consider. We're finished. |
|
662 if (sourceDocumentStyle->length() == 0 && !copiedRangeStyleSpan) { |
|
663 removeNodePreservingChildren(sourceDocumentStyleSpan); |
|
664 return; |
|
665 } |
|
666 |
|
667 // There are non-redundant styles on sourceDocumentStyleSpan, but there is no |
|
668 // copiedRangeStyleSpan. Remove the span, because it could be surrounding block elements, |
|
669 // and apply the styles to its children. |
|
670 if (sourceDocumentStyle->length() > 0 && !copiedRangeStyleSpan) { |
|
671 copyStyleToChildren(sourceDocumentStyleSpan, sourceDocumentStyle.get()); |
|
672 removeNodePreservingChildren(sourceDocumentStyleSpan); |
|
673 return; |
|
674 } |
|
675 |
|
676 RefPtr<CSSMutableStyleDeclaration> copiedRangeStyle = static_cast<HTMLElement*>(copiedRangeStyleSpan)->getInlineStyleDecl()->copy(); |
|
677 |
|
678 // We're going to put sourceDocumentStyleSpan's non-redundant styles onto copiedRangeStyleSpan, |
|
679 // as long as they aren't overridden by ones on copiedRangeStyleSpan. |
|
680 sourceDocumentStyle->merge(copiedRangeStyle.get(), true); |
|
681 copiedRangeStyle = sourceDocumentStyle; |
|
682 |
|
683 removeNodePreservingChildren(sourceDocumentStyleSpan); |
|
684 |
|
685 // Remove redundant styles. |
|
686 context = copiedRangeStyleSpan->parentNode(); |
|
687 prepareEditingStyleToApplyAt(copiedRangeStyle.get(), Position(context, 0)); |
|
688 |
|
689 // See the comments above about removing block properties. |
|
690 copiedRangeStyle->removeBlockProperties(); |
|
691 |
|
692 // All the styles on copiedRangeStyleSpan are redundant, remove it. |
|
693 if (copiedRangeStyle->length() == 0) { |
|
694 removeNodePreservingChildren(copiedRangeStyleSpan); |
|
695 return; |
|
696 } |
|
697 |
|
698 // Clear the redundant styles from the span's style attribute. |
|
699 // FIXME: If font-family:-webkit-monospace is non-redundant, then the font-size should stay, even if it |
|
700 // appears redundant. |
|
701 setNodeAttribute(static_cast<Element*>(copiedRangeStyleSpan), styleAttr, copiedRangeStyle->cssText()); |
|
702 } |
|
703 |
|
704 // Take the style attribute of a span and apply it to it's children instead. This allows us to |
|
705 // convert invalid HTML where a span contains block elements into valid HTML while preserving |
|
706 // styles. |
|
707 void ReplaceSelectionCommand::copyStyleToChildren(Node* parentNode, const CSSMutableStyleDeclaration* parentStyle) |
|
708 { |
|
709 ASSERT(parentNode->hasTagName(spanTag)); |
|
710 for (Node* childNode = parentNode->firstChild(); childNode; childNode = childNode->nextSibling()) { |
|
711 if (childNode->isTextNode() || !isBlock(childNode) || childNode->hasTagName(preTag)) { |
|
712 // In this case, put a span tag around the child node. |
|
713 RefPtr<Node> newSpan = parentNode->cloneNode(false); |
|
714 setNodeAttribute(static_cast<Element*>(newSpan.get()), styleAttr, parentStyle->cssText()); |
|
715 insertNodeAfter(newSpan, childNode); |
|
716 ExceptionCode ec = 0; |
|
717 newSpan->appendChild(childNode, ec); |
|
718 ASSERT(!ec); |
|
719 childNode = newSpan.get(); |
|
720 } else if (childNode->isHTMLElement()) { |
|
721 // Copy the style attribute and merge them into the child node. We don't want to override |
|
722 // existing styles, so don't clobber on merge. |
|
723 RefPtr<CSSMutableStyleDeclaration> newStyle = parentStyle->copy(); |
|
724 HTMLElement* childElement = static_cast<HTMLElement*>(childNode); |
|
725 RefPtr<CSSMutableStyleDeclaration> existingStyles = childElement->getInlineStyleDecl()->copy(); |
|
726 existingStyles->merge(newStyle.get(), false); |
|
727 setNodeAttribute(childElement, styleAttr, existingStyles->cssText()); |
|
728 } |
|
729 } |
|
730 } |
|
731 |
|
732 void ReplaceSelectionCommand::mergeEndIfNeeded() |
|
733 { |
|
734 if (!m_shouldMergeEnd) |
|
735 return; |
|
736 |
|
737 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent()); |
|
738 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent()); |
|
739 |
|
740 // Bail to avoid infinite recursion. |
|
741 if (m_movingParagraph) { |
|
742 ASSERT_NOT_REACHED(); |
|
743 return; |
|
744 } |
|
745 |
|
746 // Merging two paragraphs will destroy the moved one's block styles. Always move the end of inserted forward |
|
747 // to preserve the block style of the paragraph already in the document, unless the paragraph to move would |
|
748 // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's |
|
749 // block styles. |
|
750 bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent)); |
|
751 |
|
752 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent; |
|
753 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next(); |
|
754 |
|
755 // Merging forward could result in deleting the destination anchor node. |
|
756 // To avoid this, we add a placeholder node before the start of the paragraph. |
|
757 if (endOfParagraph(startOfParagraphToMove) == destination) { |
|
758 RefPtr<Node> placeholder = createBreakElement(document()); |
|
759 insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().node()); |
|
760 destination = VisiblePosition(Position(placeholder.get(), 0)); |
|
761 } |
|
762 |
|
763 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination); |
|
764 |
|
765 // Merging forward will remove m_lastLeafInserted from the document. |
|
766 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are |
|
767 // only ever used to create positions where inserted content starts/ends. Also, we sometimes insert content |
|
768 // directly into text nodes already in the document, in which case tracking inserted nodes is inadequate. |
|
769 if (mergeForward) { |
|
770 m_lastLeafInserted = destination.previous().deepEquivalent().node(); |
|
771 if (!m_firstNodeInserted->inDocument()) |
|
772 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().node(); |
|
773 // If we merged text nodes, m_lastLeafInserted could be null. If this is the case, |
|
774 // we use m_firstNodeInserted. |
|
775 if (!m_lastLeafInserted) |
|
776 m_lastLeafInserted = m_firstNodeInserted; |
|
777 } |
|
778 } |
|
779 |
|
780 void ReplaceSelectionCommand::doApply() |
|
781 { |
|
782 VisibleSelection selection = endingSelection(); |
|
783 ASSERT(selection.isCaretOrRange()); |
|
784 ASSERT(selection.start().node()); |
|
785 if (selection.isNone() || !selection.start().node()) |
|
786 return; |
|
787 |
|
788 bool selectionIsPlainText = !selection.isContentRichlyEditable(); |
|
789 |
|
790 Element* currentRoot = selection.rootEditableElement(); |
|
791 ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection); |
|
792 |
|
793 if (performTrivialReplace(fragment)) |
|
794 return; |
|
795 |
|
796 if (m_matchStyle) |
|
797 m_insertionStyle = ApplyStyleCommand::editingStyleAtPosition(selection.start(), IncludeTypingStyle); |
|
798 |
|
799 VisiblePosition visibleStart = selection.visibleStart(); |
|
800 VisiblePosition visibleEnd = selection.visibleEnd(); |
|
801 |
|
802 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd); |
|
803 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart); |
|
804 |
|
805 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().node()); |
|
806 |
|
807 Position insertionPos = selection.start(); |
|
808 bool startIsInsideMailBlockquote = nearestMailBlockquote(insertionPos.node()); |
|
809 |
|
810 if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) || |
|
811 startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText) |
|
812 m_preventNesting = false; |
|
813 |
|
814 if (selection.isRange()) { |
|
815 // When the end of the selection being pasted into is at the end of a paragraph, and that selection |
|
816 // spans multiple blocks, not merging may leave an empty line. |
|
817 // When the start of the selection being pasted into is at the start of a block, not merging |
|
818 // will leave hanging block(s). |
|
819 // Merge blocks if the start of the selection was in a Mail blockquote, since we handle |
|
820 // that case specially to prevent nesting. |
|
821 bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart); |
|
822 // FIXME: We should only expand to include fully selected special elements if we are copying a |
|
823 // selection and pasting it on top of itself. |
|
824 deleteSelection(false, mergeBlocksAfterDelete, true, false); |
|
825 visibleStart = endingSelection().visibleStart(); |
|
826 if (fragment.hasInterchangeNewlineAtStart()) { |
|
827 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) { |
|
828 if (!isEndOfDocument(visibleStart)) |
|
829 setEndingSelection(visibleStart.next()); |
|
830 } else |
|
831 insertParagraphSeparator(); |
|
832 } |
|
833 insertionPos = endingSelection().start(); |
|
834 } else { |
|
835 ASSERT(selection.isCaret()); |
|
836 if (fragment.hasInterchangeNewlineAtStart()) { |
|
837 VisiblePosition next = visibleStart.next(true); |
|
838 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull()) |
|
839 setEndingSelection(next); |
|
840 else |
|
841 insertParagraphSeparator(); |
|
842 } |
|
843 // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block. |
|
844 // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret. |
|
845 // As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>, |
|
846 // not <div>xbar<div>bar</div><div>bazx</div></div>. |
|
847 // Don't do this if the selection started in a Mail blockquote. |
|
848 if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) { |
|
849 insertParagraphSeparator(); |
|
850 setEndingSelection(endingSelection().visibleStart().previous()); |
|
851 } |
|
852 insertionPos = endingSelection().start(); |
|
853 } |
|
854 |
|
855 // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break |
|
856 // out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case |
|
857 // breaking the blockquote will prevent the content from actually being inserted in the table. |
|
858 if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) { |
|
859 applyCommandToComposite(BreakBlockquoteCommand::create(document())); |
|
860 // This will leave a br between the split. |
|
861 Node* br = endingSelection().start().node(); |
|
862 ASSERT(br->hasTagName(brTag)); |
|
863 // Insert content between the two blockquotes, but remove the br (since it was just a placeholder). |
|
864 insertionPos = positionInParentBeforeNode(br); |
|
865 removeNode(br); |
|
866 } |
|
867 |
|
868 // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world. |
|
869 prepareWhitespaceAtPositionForSplit(insertionPos); |
|
870 |
|
871 // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after |
|
872 // p that maps to the same visible position as p (since in the case where a br is at the end of a block and collapsed |
|
873 // away, there are positions after the br which map to the same visible position as [br, 0]). |
|
874 Node* endBR = insertionPos.downstream().node()->hasTagName(brTag) ? insertionPos.downstream().node() : 0; |
|
875 VisiblePosition originalVisPosBeforeEndBR; |
|
876 if (endBR) |
|
877 originalVisPosBeforeEndBR = VisiblePosition(endBR, 0, DOWNSTREAM).previous(); |
|
878 |
|
879 startBlock = enclosingBlock(insertionPos.node()); |
|
880 |
|
881 // Adjust insertionPos to prevent nesting. |
|
882 // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above. |
|
883 if (m_preventNesting && startBlock && !startIsInsideMailBlockquote) { |
|
884 ASSERT(startBlock != currentRoot); |
|
885 VisiblePosition visibleInsertionPos(insertionPos); |
|
886 if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd())) |
|
887 insertionPos = positionInParentAfterNode(startBlock); |
|
888 else if (isStartOfBlock(visibleInsertionPos)) |
|
889 insertionPos = positionInParentBeforeNode(startBlock); |
|
890 } |
|
891 |
|
892 // Paste into run of tabs splits the tab span. |
|
893 insertionPos = positionOutsideTabSpan(insertionPos); |
|
894 |
|
895 // Paste at start or end of link goes outside of link. |
|
896 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos); |
|
897 |
|
898 // FIXME: Can this wait until after the operation has been performed? There doesn't seem to be |
|
899 // any work performed after this that queries or uses the typing style. |
|
900 if (Frame* frame = document()->frame()) |
|
901 frame->clearTypingStyle(); |
|
902 |
|
903 bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos); |
|
904 |
|
905 // We don't want the destination to end up inside nodes that weren't selected. To avoid that, we move the |
|
906 // position forward without changing the visible position so we're still at the same visible location, but |
|
907 // outside of preceding tags. |
|
908 insertionPos = positionAvoidingPrecedingNodes(insertionPos); |
|
909 |
|
910 // FIXME: When pasting rich content we're often prevented from heading down the fast path by style spans. Try |
|
911 // again here if they've been removed. |
|
912 |
|
913 // We're finished if there is nothing to add. |
|
914 if (fragment.isEmpty() || !fragment.firstChild()) |
|
915 return; |
|
916 |
|
917 // 1) Insert the content. |
|
918 // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>. |
|
919 // 3) Merge the start of the added content with the content before the position being pasted into. |
|
920 // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed, |
|
921 // b) merge the last paragraph of the incoming fragment with the paragraph that contained the |
|
922 // end of the selection that was pasted into, or c) handle an interchange newline at the end of the |
|
923 // incoming fragment. |
|
924 // 5) Add spaces for smart replace. |
|
925 // 6) Select the replacement if requested, and match style if requested. |
|
926 |
|
927 VisiblePosition startOfInsertedContent, endOfInsertedContent; |
|
928 |
|
929 RefPtr<Node> refNode = fragment.firstChild(); |
|
930 RefPtr<Node> node = refNode->nextSibling(); |
|
931 |
|
932 fragment.removeNode(refNode); |
|
933 |
|
934 Node* blockStart = enclosingBlock(insertionPos.node()); |
|
935 if ((isListElement(refNode.get()) || (isStyleSpan(refNode.get()) && isListElement(refNode->firstChild()))) |
|
936 && blockStart->renderer()->isListItem()) |
|
937 refNode = insertAsListItems(refNode, blockStart, insertionPos); |
|
938 else |
|
939 insertNodeAtAndUpdateNodesInserted(refNode, insertionPos); |
|
940 |
|
941 // Mutation events (bug 22634) may have already removed the inserted content |
|
942 if (!refNode->inDocument()) |
|
943 return; |
|
944 |
|
945 bool plainTextFragment = isPlainTextMarkup(refNode.get()); |
|
946 |
|
947 while (node) { |
|
948 Node* next = node->nextSibling(); |
|
949 fragment.removeNode(node); |
|
950 insertNodeAfterAndUpdateNodesInserted(node, refNode.get()); |
|
951 |
|
952 // Mutation events (bug 22634) may have already removed the inserted content |
|
953 if (!node->inDocument()) |
|
954 return; |
|
955 |
|
956 refNode = node; |
|
957 if (node && plainTextFragment) |
|
958 plainTextFragment = isPlainTextMarkup(node.get()); |
|
959 node = next; |
|
960 } |
|
961 |
|
962 removeUnrenderedTextNodesAtEnds(); |
|
963 |
|
964 negateStyleRulesThatAffectAppearance(); |
|
965 |
|
966 if (!handledStyleSpans) |
|
967 handleStyleSpans(); |
|
968 |
|
969 // Mutation events (bug 20161) may have already removed the inserted content |
|
970 if (!m_firstNodeInserted || !m_firstNodeInserted->inDocument()) |
|
971 return; |
|
972 |
|
973 endOfInsertedContent = positionAtEndOfInsertedContent(); |
|
974 startOfInsertedContent = positionAtStartOfInsertedContent(); |
|
975 |
|
976 // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and |
|
977 // didn't have a br after it, so the inserted content ended up in the same paragraph. |
|
978 if (startBlock && insertionPos.node() == startBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent)) |
|
979 insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent()); |
|
980 |
|
981 Position lastPositionToSelect; |
|
982 |
|
983 bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd(); |
|
984 |
|
985 if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) |
|
986 removeNodeAndPruneAncestors(endBR); |
|
987 |
|
988 // Determine whether or not we should merge the end of inserted content with what's after it before we do |
|
989 // the start merge so that the start merge doesn't effect our decision. |
|
990 m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph); |
|
991 |
|
992 if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) { |
|
993 VisiblePosition destination = startOfInsertedContent.previous(); |
|
994 VisiblePosition startOfParagraphToMove = startOfInsertedContent; |
|
995 |
|
996 // Merging the the first paragraph of inserted content with the content that came |
|
997 // before the selection that was pasted into would also move content after |
|
998 // the selection that was pasted into if: only one paragraph was being pasted, |
|
999 // and it was not wrapped in a block, the selection that was pasted into ended |
|
1000 // at the end of a block and the next paragraph didn't start at the start of a block. |
|
1001 // Insert a line break just after the inserted content to separate it from what |
|
1002 // comes after and prevent that from happening. |
|
1003 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent(); |
|
1004 if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) { |
|
1005 insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent()); |
|
1006 // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move |
|
1007 if (!startOfParagraphToMove.deepEquivalent().node()->inDocument()) |
|
1008 return; |
|
1009 } |
|
1010 |
|
1011 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are |
|
1012 // only ever used to create positions where inserted content starts/ends. |
|
1013 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination); |
|
1014 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().downstream().node(); |
|
1015 if (!m_lastLeafInserted->inDocument()) |
|
1016 m_lastLeafInserted = endingSelection().visibleEnd().deepEquivalent().upstream().node(); |
|
1017 } |
|
1018 |
|
1019 endOfInsertedContent = positionAtEndOfInsertedContent(); |
|
1020 startOfInsertedContent = positionAtStartOfInsertedContent(); |
|
1021 |
|
1022 if (interchangeNewlineAtEnd) { |
|
1023 VisiblePosition next = endOfInsertedContent.next(true); |
|
1024 |
|
1025 if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) { |
|
1026 if (!isStartOfParagraph(endOfInsertedContent)) { |
|
1027 setEndingSelection(endOfInsertedContent); |
|
1028 Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().node()); |
|
1029 if (isListItem(enclosingNode)) { |
|
1030 RefPtr<Node> newListItem = createListItemElement(document()); |
|
1031 insertNodeAfter(newListItem, enclosingNode); |
|
1032 setEndingSelection(VisiblePosition(Position(newListItem, 0))); |
|
1033 } else |
|
1034 // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph |
|
1035 // block's style seems to annoy users. |
|
1036 insertParagraphSeparator(true); |
|
1037 |
|
1038 // Select up to the paragraph separator that was added. |
|
1039 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent(); |
|
1040 updateNodesInserted(lastPositionToSelect.node()); |
|
1041 } |
|
1042 } else { |
|
1043 // Select up to the beginning of the next paragraph. |
|
1044 lastPositionToSelect = next.deepEquivalent().downstream(); |
|
1045 } |
|
1046 |
|
1047 } else |
|
1048 mergeEndIfNeeded(); |
|
1049 |
|
1050 handlePasteAsQuotationNode(); |
|
1051 |
|
1052 endOfInsertedContent = positionAtEndOfInsertedContent(); |
|
1053 startOfInsertedContent = positionAtStartOfInsertedContent(); |
|
1054 |
|
1055 // Add spaces for smart replace. |
|
1056 if (m_smartReplace && currentRoot) { |
|
1057 // Disable smart replace for password fields. |
|
1058 Node* start = currentRoot->shadowAncestorNode(); |
|
1059 if (start->hasTagName(inputTag) && static_cast<HTMLInputElement*>(start)->inputType() == HTMLInputElement::PASSWORD) |
|
1060 m_smartReplace = false; |
|
1061 } |
|
1062 if (m_smartReplace) { |
|
1063 bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && |
|
1064 !isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false); |
|
1065 if (needsTrailingSpace) { |
|
1066 RenderObject* renderer = m_lastLeafInserted->renderer(); |
|
1067 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace(); |
|
1068 Node* endNode = positionAtEndOfInsertedContent().deepEquivalent().upstream().node(); |
|
1069 if (endNode->isTextNode()) { |
|
1070 Text* text = static_cast<Text*>(endNode); |
|
1071 insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " "); |
|
1072 } else { |
|
1073 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " "); |
|
1074 insertNodeAfterAndUpdateNodesInserted(node, endNode); |
|
1075 } |
|
1076 } |
|
1077 |
|
1078 bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && |
|
1079 !isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true); |
|
1080 if (needsLeadingSpace) { |
|
1081 RenderObject* renderer = m_lastLeafInserted->renderer(); |
|
1082 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace(); |
|
1083 Node* startNode = positionAtStartOfInsertedContent().deepEquivalent().downstream().node(); |
|
1084 if (startNode->isTextNode()) { |
|
1085 Text* text = static_cast<Text*>(startNode); |
|
1086 insertTextIntoNode(text, 0, collapseWhiteSpace ? nonBreakingSpaceString() : " "); |
|
1087 } else { |
|
1088 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " "); |
|
1089 // Don't updateNodesInserted. Doing so would set m_lastLeafInserted to be the node containing the |
|
1090 // leading space, but m_lastLeafInserted is supposed to mark the end of pasted content. |
|
1091 insertNodeBefore(node, startNode); |
|
1092 // FIXME: Use positions to track the start/end of inserted content. |
|
1093 m_firstNodeInserted = node; |
|
1094 } |
|
1095 } |
|
1096 } |
|
1097 |
|
1098 // If we are dealing with a fragment created from plain text |
|
1099 // no style matching is necessary. |
|
1100 if (plainTextFragment) |
|
1101 m_matchStyle = false; |
|
1102 |
|
1103 completeHTMLReplacement(lastPositionToSelect); |
|
1104 } |
|
1105 |
|
1106 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR) |
|
1107 { |
|
1108 if (!endBR || !endBR->inDocument()) |
|
1109 return false; |
|
1110 |
|
1111 VisiblePosition visiblePos(Position(endBR, 0)); |
|
1112 |
|
1113 // Don't remove the br if nothing was inserted. |
|
1114 if (visiblePos.previous() == originalVisPosBeforeEndBR) |
|
1115 return false; |
|
1116 |
|
1117 // Remove the br if it is collapsed away and so is unnecessary. |
|
1118 if (!document()->inStrictMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos)) |
|
1119 return true; |
|
1120 |
|
1121 // A br that was originally holding a line open should be displaced by inserted content or turned into a line break. |
|
1122 // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder. |
|
1123 return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos); |
|
1124 } |
|
1125 |
|
1126 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect) |
|
1127 { |
|
1128 Position start; |
|
1129 Position end; |
|
1130 |
|
1131 // FIXME: This should never not be the case. |
|
1132 if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastLeafInserted && m_lastLeafInserted->inDocument()) { |
|
1133 |
|
1134 start = positionAtStartOfInsertedContent().deepEquivalent(); |
|
1135 end = positionAtEndOfInsertedContent().deepEquivalent(); |
|
1136 |
|
1137 // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps. |
|
1138 rebalanceWhitespaceAt(start); |
|
1139 rebalanceWhitespaceAt(end); |
|
1140 |
|
1141 if (m_matchStyle) { |
|
1142 ASSERT(m_insertionStyle); |
|
1143 applyStyle(m_insertionStyle.get(), start, end); |
|
1144 } |
|
1145 |
|
1146 if (lastPositionToSelect.isNotNull()) |
|
1147 end = lastPositionToSelect; |
|
1148 } else if (lastPositionToSelect.isNotNull()) |
|
1149 start = end = lastPositionToSelect; |
|
1150 else |
|
1151 return; |
|
1152 |
|
1153 if (m_selectReplacement) |
|
1154 setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY)); |
|
1155 else |
|
1156 setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY)); |
|
1157 } |
|
1158 |
|
1159 EditAction ReplaceSelectionCommand::editingAction() const |
|
1160 { |
|
1161 return m_editAction; |
|
1162 } |
|
1163 |
|
1164 void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild) |
|
1165 { |
|
1166 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed |
|
1167 insertNodeAfter(insertChild, refChild); |
|
1168 updateNodesInserted(nodeToUpdate); |
|
1169 } |
|
1170 |
|
1171 void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild, const Position& p) |
|
1172 { |
|
1173 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed |
|
1174 insertNodeAt(insertChild, p); |
|
1175 updateNodesInserted(nodeToUpdate); |
|
1176 } |
|
1177 |
|
1178 void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild) |
|
1179 { |
|
1180 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed |
|
1181 insertNodeBefore(insertChild, refChild); |
|
1182 updateNodesInserted(nodeToUpdate); |
|
1183 } |
|
1184 |
|
1185 // If the user is inserting a list into an existing list, instead of nesting the list, |
|
1186 // we put the list items into the existing list. |
|
1187 Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<Node> listElement, Node* insertionBlock, const Position& insertPos) |
|
1188 { |
|
1189 while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1) |
|
1190 listElement = listElement->firstChild(); |
|
1191 |
|
1192 bool isStart = isStartOfParagraph(insertPos); |
|
1193 bool isEnd = isEndOfParagraph(insertPos); |
|
1194 bool isMiddle = !isStart && !isEnd; |
|
1195 Node* lastNode = insertionBlock; |
|
1196 |
|
1197 // If we're in the middle of a list item, we should split it into two separate |
|
1198 // list items and insert these nodes between them. |
|
1199 if (isMiddle) { |
|
1200 int textNodeOffset = insertPos.offsetInContainerNode(); |
|
1201 if (insertPos.node()->isTextNode() && textNodeOffset > 0) |
|
1202 splitTextNode(static_cast<Text*>(insertPos.node()), textNodeOffset); |
|
1203 splitTreeToNode(insertPos.node(), lastNode, true); |
|
1204 } |
|
1205 |
|
1206 while (RefPtr<Node> listItem = listElement->firstChild()) { |
|
1207 ExceptionCode ec = 0; |
|
1208 listElement->removeChild(listItem.get(), ec); |
|
1209 ASSERT(!ec); |
|
1210 if (isStart || isMiddle) |
|
1211 insertNodeBefore(listItem, lastNode); |
|
1212 else if (isEnd) { |
|
1213 insertNodeAfter(listItem, lastNode); |
|
1214 lastNode = listItem.get(); |
|
1215 } else |
|
1216 ASSERT_NOT_REACHED(); |
|
1217 } |
|
1218 if (isStart || isMiddle) |
|
1219 lastNode = lastNode->previousSibling(); |
|
1220 if (isMiddle) |
|
1221 insertNodeAfter(createListItemElement(document()), lastNode); |
|
1222 updateNodesInserted(lastNode); |
|
1223 return lastNode; |
|
1224 } |
|
1225 |
|
1226 void ReplaceSelectionCommand::updateNodesInserted(Node *node) |
|
1227 { |
|
1228 if (!node) |
|
1229 return; |
|
1230 |
|
1231 if (!m_firstNodeInserted) |
|
1232 m_firstNodeInserted = node; |
|
1233 |
|
1234 if (node == m_lastLeafInserted) |
|
1235 return; |
|
1236 |
|
1237 m_lastLeafInserted = node->lastDescendant(); |
|
1238 } |
|
1239 |
|
1240 // During simple pastes, where we're just pasting a text node into a run of text, we insert the text node |
|
1241 // directly into the text node that holds the selection. This is much faster than the generalized code in |
|
1242 // ReplaceSelectionCommand, and works around <https://bugs.webkit.org/show_bug.cgi?id=6148> since we don't |
|
1243 // split text nodes. |
|
1244 bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment) |
|
1245 { |
|
1246 if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode()) |
|
1247 return false; |
|
1248 |
|
1249 // FIXME: Would be nice to handle smart replace in the fast path. |
|
1250 if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd()) |
|
1251 return false; |
|
1252 |
|
1253 Text* textNode = static_cast<Text*>(fragment.firstChild()); |
|
1254 // Our fragment creation code handles tabs, spaces, and newlines, so we don't have to worry about those here. |
|
1255 String text(textNode->data()); |
|
1256 |
|
1257 Position start = endingSelection().start(); |
|
1258 Position end = endingSelection().end(); |
|
1259 |
|
1260 if (start.anchorNode() != end.anchorNode() || !start.anchorNode()->isTextNode()) |
|
1261 return false; |
|
1262 |
|
1263 replaceTextInNode(static_cast<Text*>(start.anchorNode()), start.offsetInContainerNode(), end.offsetInContainerNode() - start.offsetInContainerNode(), text); |
|
1264 |
|
1265 end = Position(start.anchorNode(), start.offsetInContainerNode() + text.length()); |
|
1266 |
|
1267 VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end); |
|
1268 |
|
1269 setEndingSelection(selectionAfterReplace); |
|
1270 |
|
1271 return true; |
|
1272 } |
|
1273 |
|
1274 } // namespace WebCore |