forked from qt/qtwebkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplaceSelectionCommand.cpp
More file actions
1520 lines (1281 loc) · 68.9 KB
/
Copy pathReplaceSelectionCommand.cpp
File metadata and controls
1520 lines (1281 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009, 2010, 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ReplaceSelectionCommand.h"
#include "ApplyStyleCommand.h"
#include "BeforeTextInsertedEvent.h"
#include "BreakBlockquoteCommand.h"
#include "CSSStyleDeclaration.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "Element.h"
#include "ElementIterator.h"
#include "EventNames.h"
#include "ExceptionCodePlaceholder.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLTitleElement.h"
#include "NodeList.h"
#include "NodeRenderStyle.h"
#include "RenderInline.h"
#include "RenderObject.h"
#include "RenderText.h"
#include "ReplaceDeleteFromTextNodeCommand.h"
#include "ReplaceInsertIntoTextNodeCommand.h"
#include "SimplifyMarkupCommand.h"
#include "SmartReplace.h"
#include "StyleProperties.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisibleUnits.h"
#include "htmlediting.h"
#include "markup.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
namespace WebCore {
using namespace HTMLNames;
enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
// --- ReplacementFragment helper class
class ReplacementFragment {
WTF_MAKE_NONCOPYABLE(ReplacementFragment);
public:
ReplacementFragment(Document&, DocumentFragment*, const VisibleSelection&);
DocumentFragment* fragment() { return m_fragment.get(); }
Node* firstChild() const;
Node* lastChild() const;
bool isEmpty() const;
bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
void removeNode(PassRefPtr<Node>);
void removeNodePreservingChildren(PassRefPtr<Node>);
private:
PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* rootEditableNode);
void removeUnrenderedNodes(Node*);
void restoreAndRemoveTestRenderingNodesToFragment(StyledElement*);
void removeInterchangeNodes(Node*);
void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
Document& document() { return *m_document; }
RefPtr<Document> m_document;
RefPtr<DocumentFragment> m_fragment;
bool m_hasInterchangeNewlineAtStart;
bool m_hasInterchangeNewlineAtEnd;
};
static bool isInterchangeNewlineNode(const Node *node)
{
static NeverDestroyed<String> interchangeNewlineClassString(AppleInterchangeNewline);
return node && node->hasTagName(brTag) &&
static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
}
static bool isInterchangeConvertedSpaceSpan(const Node *node)
{
static NeverDestroyed<String> convertedSpaceSpanClassString(AppleConvertedSpace);
return node->isHTMLElement() &&
static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
}
static Position positionAvoidingPrecedingNodes(Position pos)
{
// If we're already on a break, it's probably a placeholder and we shouldn't change our position.
if (editingIgnoresContent(pos.deprecatedNode()))
return pos;
// We also stop when changing block flow elements because even though the visual position is the
// same. E.g.,
// <div>foo^</div>^
// The two positions above are the same visual position, but we want to stay in the same block.
Node* enclosingBlockNode = enclosingBlock(pos.containerNode());
for (Position nextPosition = pos; nextPosition.containerNode() != enclosingBlockNode; pos = nextPosition) {
if (lineBreakExistsAtPosition(pos))
break;
if (pos.containerNode()->nonShadowBoundaryParentNode())
nextPosition = positionInParentAfterNode(pos.containerNode());
if (nextPosition == pos
|| enclosingBlock(nextPosition.containerNode()) != enclosingBlockNode
|| VisiblePosition(pos) != VisiblePosition(nextPosition))
break;
}
return pos;
}
ReplacementFragment::ReplacementFragment(Document& document, DocumentFragment* fragment, const VisibleSelection& selection)
: m_document(&document)
, m_fragment(fragment)
, m_hasInterchangeNewlineAtStart(false)
, m_hasInterchangeNewlineAtEnd(false)
{
if (!m_fragment)
return;
if (!m_fragment->firstChild())
return;
RefPtr<Element> editableRoot = selection.rootEditableElement();
ASSERT(editableRoot);
if (!editableRoot)
return;
Node* shadowAncestorNode = editableRoot->deprecatedShadowAncestorNode();
if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
// FIXME: Remove these checks once textareas and textfields actually register an event handler.
!(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
editableRoot->hasRichlyEditableStyle()) {
removeInterchangeNodes(m_fragment.get());
return;
}
RefPtr<StyledElement> holder = insertFragmentForTestRendering(editableRoot.get());
if (!holder) {
removeInterchangeNodes(m_fragment.get());
return;
}
RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
String text = plainText(range.get(), static_cast<TextIteratorBehavior>(TextIteratorEmitsOriginalText | TextIteratorIgnoresStyleVisibility));
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
// Give the root a chance to change the text.
Ref<BeforeTextInsertedEvent> event = BeforeTextInsertedEvent::create(text);
editableRoot->dispatchEvent(event);
if (text != event->text() || !editableRoot->hasRichlyEditableStyle()) {
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
RefPtr<Range> range = selection.toNormalizedRange();
if (!range)
return;
m_fragment = createFragmentFromText(*range, event->text());
if (!m_fragment->firstChild())
return;
holder = insertFragmentForTestRendering(editableRoot.get());
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
}
}
bool ReplacementFragment::isEmpty() const
{
return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
}
Node *ReplacementFragment::firstChild() const
{
return m_fragment ? m_fragment->firstChild() : 0;
}
Node *ReplacementFragment::lastChild() const
{
return m_fragment ? m_fragment->lastChild() : 0;
}
void ReplacementFragment::removeNodePreservingChildren(PassRefPtr<Node> node)
{
if (!node)
return;
while (RefPtr<Node> n = node->firstChild()) {
removeNode(n);
insertNodeBefore(n.release(), node.get());
}
removeNode(node);
}
void ReplacementFragment::removeNode(PassRefPtr<Node> node)
{
if (!node)
return;
ContainerNode* parent = node->nonShadowBoundaryParentNode();
if (!parent)
return;
parent->removeChild(*node, ASSERT_NO_EXCEPTION);
}
void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
{
if (!node || !refNode)
return;
ContainerNode* parent = refNode->nonShadowBoundaryParentNode();
if (!parent)
return;
parent->insertBefore(*node, refNode, ASSERT_NO_EXCEPTION);
}
PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
{
RefPtr<StyledElement> holder = createDefaultParagraphElement(document());
holder->appendChild(*m_fragment, ASSERT_NO_EXCEPTION);
rootEditableElement->appendChild(holder.get(), ASSERT_NO_EXCEPTION);
document().updateLayoutIgnorePendingStylesheets();
return holder.release();
}
void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(StyledElement* holder)
{
if (!holder)
return;
while (RefPtr<Node> node = holder->firstChild()) {
holder->removeChild(*node, ASSERT_NO_EXCEPTION);
m_fragment->appendChild(*node, ASSERT_NO_EXCEPTION);
}
removeNode(holder);
}
void ReplacementFragment::removeUnrenderedNodes(Node* holder)
{
Vector<RefPtr<Node>> unrendered;
for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder)) {
if (!isNodeRendered(node) && !isTableStructureNode(node))
unrendered.append(node);
}
for (auto& node : unrendered)
removeNode(node);
}
void ReplacementFragment::removeInterchangeNodes(Node* container)
{
m_hasInterchangeNewlineAtStart = false;
m_hasInterchangeNewlineAtEnd = false;
// Interchange newlines at the "start" of the incoming fragment must be
// either the first node in the fragment or the first leaf in the fragment.
Node* node = container->firstChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtStart = true;
removeNode(node);
break;
}
node = node->firstChild();
}
if (!container->hasChildNodes())
return;
// Interchange newlines at the "end" of the incoming fragment must be
// either the last node in the fragment or the last leaf in the fragment.
node = container->lastChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtEnd = true;
removeNode(node);
break;
}
node = node->lastChild();
}
node = container->firstChild();
while (node) {
RefPtr<Node> next = NodeTraversal::next(*node);
if (isInterchangeConvertedSpaceSpan(node)) {
next = NodeTraversal::nextSkippingChildren(*node);
removeNodePreservingChildren(node);
}
node = next.get();
}
}
inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node* node)
{
if (!node)
return;
if (!m_firstNodeInserted)
m_firstNodeInserted = node;
m_lastNodeInserted = node;
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node* node)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::next(*node);
if (m_lastNodeInserted == node)
m_lastNodeInserted = node->lastChild() ? node->lastChild() : NodeTraversal::nextSkippingChildren(*node);
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node* node)
{
if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
m_firstNodeInserted = nullptr;
m_lastNodeInserted = nullptr;
} else if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
else if (m_lastNodeInserted == node)
m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
}
inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node* node, Node* newNode)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = newNode;
if (m_lastNodeInserted == node)
m_lastNodeInserted = newNode;
}
ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, RefPtr<DocumentFragment>&& fragment, CommandOptions options, EditAction editAction)
: CompositeEditCommand(document, editAction)
, m_selectReplacement(options & SelectReplacement)
, m_smartReplace(options & SmartReplace)
, m_matchStyle(options & MatchStyle)
, m_documentFragment(fragment)
, m_preventNesting(options & PreventNesting)
, m_movingParagraph(options & MovingParagraph)
, m_sanitizeFragment(options & SanitizeFragment)
, m_shouldMergeEnd(false)
, m_ignoreMailBlockquote(options & IgnoreMailBlockquote)
{
}
static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
{
Position existing = endOfExistingContent.deepEquivalent();
Position inserted = endOfInsertedContent.deepEquivalent();
bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
}
bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
{
if (m_movingParagraph)
return false;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
if (prev.isNull())
return false;
// When we have matching quote levels, its ok to merge more frequently.
// For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
// And we should only merge here if the selection start was inside a mail blockquote. This prevents against removing a
// blockquote from newly pasted quoted content that was pasted into an unquoted position. If that unquoted position happens
// to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
return true;
return !selectionStartWasStartOfParagraph
&& !fragmentHasInterchangeNewlineAtStart
&& isStartOfParagraph(startOfInsertedContent)
&& !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
&& shouldMerge(startOfInsertedContent, prev);
}
bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
{
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
if (next.isNull())
return false;
return !selectionEndWasEndOfParagraph
&& isEndOfParagraph(endOfInsertedContent)
&& !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
&& shouldMerge(endOfInsertedContent, next);
}
static bool isMailPasteAsQuotationNode(const Node* node)
{
return node && node->hasTagName(blockquoteTag) && downcast<Element>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
}
static bool isHeaderElement(const Node* a)
{
if (!a)
return false;
return a->hasTagName(h1Tag)
|| a->hasTagName(h2Tag)
|| a->hasTagName(h3Tag)
|| a->hasTagName(h4Tag)
|| a->hasTagName(h5Tag)
|| a->hasTagName(h6Tag);
}
static bool haveSameTagName(Node* a, Node* b)
{
return is<Element>(a) && is<Element>(b) && downcast<Element>(*a).tagName() == downcast<Element>(*b).tagName();
}
bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
{
if (source.isNull() || destination.isNull())
return false;
Node* sourceNode = source.deepEquivalent().deprecatedNode();
Node* destinationNode = destination.deepEquivalent().deprecatedNode();
Node* sourceBlock = enclosingBlock(sourceNode);
Node* destinationBlock = enclosingBlock(destinationNode);
return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) &&
enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
(!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
// Don't merge to or from a position before or after a block because it would
// be a no-op and cause infinite recursion.
!isBlock(sourceNode) && !isBlock(destinationNode);
}
// Style rules that match just inserted elements could change their appearance, like
// a div inserted into a document with div { display:inline; }.
void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
// FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
next = NodeTraversal::next(*node);
if (!is<StyledElement>(*node))
continue;
StyledElement* element = downcast<StyledElement>(node.get());
const StyleProperties* inlineStyle = element->inlineStyle();
RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
if (inlineStyle) {
if (is<HTMLElement>(*element)) {
Vector<QualifiedName> attributes;
HTMLElement& htmlElement = downcast<HTMLElement>(*element);
if (newInlineStyle->conflictsWithImplicitStyleOfElement(&htmlElement)) {
// e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
node = replaceElementWithSpanPreservingChildrenAndAttributes(&htmlElement);
element = downcast<StyledElement>(node.get());
insertedNodes.didReplaceNode(&htmlElement, node.get());
} else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(&htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
EditingStyle::DoNotExtractMatchingStyle)) {
// e.g. <font size="3" style="font-size: 20px;"> is converted to <font style="font-size: 20px;">
for (auto& attribute : attributes)
removeNodeAttribute(element, attribute);
}
}
ContainerNode* context = element->parentNode();
// If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
// styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
newInlineStyle->removeStyleFromRulesAndContext(element, document().documentElement());
newInlineStyle->removeStyleFromRulesAndContext(element, context);
}
if (!inlineStyle || newInlineStyle->isEmpty()) {
if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(element);
continue;
}
removeNodeAttribute(element, styleAttr);
} else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount())
setNodeAttribute(element, styleAttr, newInlineStyle->style()->asText());
// FIXME: Tolerate differences in id, class, and style attributes.
if (element->parentNode() && isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
&& VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
&& VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(element);
continue;
}
if (element->parentNode() && element->parentNode()->hasRichlyEditableStyle())
removeNodeAttribute(element, contenteditableAttr);
// WebKit used to not add display: inline and float: none on copy.
// Keep this code around for backward compatibility
if (isLegacyAppleStyleSpan(element)) {
if (!element->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(element);
continue;
}
// There are other styles that style rules can give to style spans,
// but these are the two important ones because they'll prevent
// inserted content from appearing in the right paragraph.
// FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
// results. We already know one issue because td elements ignore their display property
// in quirks mode (which Mail.app is always in). We should look for an alternative.
// Mutate using the CSSOM wrapper so we get the same event behavior as a script.
if (isBlock(element))
element->cssomStyle()->setPropertyInternal(CSSPropertyDisplay, "inline", false, IGNORE_EXCEPTION);
if (element->renderer() && element->renderer()->style().isFloating())
element->cssomStyle()->setPropertyInternal(CSSPropertyFloat, "none", false, IGNORE_EXCEPTION);
}
}
}
static bool isProhibitedParagraphChild(const AtomicString& name)
{
// https://dvcs.w3.org/hg/editing/raw-file/57abe6d3cb60/editing.html#prohibited-paragraph-child
static NeverDestroyed<HashSet<AtomicString>> elements;
if (elements.get().isEmpty()) {
elements.get().add(addressTag.localName());
elements.get().add(articleTag.localName());
elements.get().add(asideTag.localName());
elements.get().add(blockquoteTag.localName());
elements.get().add(captionTag.localName());
elements.get().add(centerTag.localName());
elements.get().add(colTag.localName());
elements.get().add(colgroupTag.localName());
elements.get().add(ddTag.localName());
elements.get().add(detailsTag.localName());
elements.get().add(dirTag.localName());
elements.get().add(divTag.localName());
elements.get().add(dlTag.localName());
elements.get().add(dtTag.localName());
elements.get().add(fieldsetTag.localName());
elements.get().add(figcaptionTag.localName());
elements.get().add(figureTag.localName());
elements.get().add(footerTag.localName());
elements.get().add(formTag.localName());
elements.get().add(h1Tag.localName());
elements.get().add(h2Tag.localName());
elements.get().add(h3Tag.localName());
elements.get().add(h4Tag.localName());
elements.get().add(h5Tag.localName());
elements.get().add(h6Tag.localName());
elements.get().add(headerTag.localName());
elements.get().add(hgroupTag.localName());
elements.get().add(hrTag.localName());
elements.get().add(liTag.localName());
elements.get().add(listingTag.localName());
elements.get().add(mainTag.localName()); // Missing in the specification.
elements.get().add(menuTag.localName());
elements.get().add(navTag.localName());
elements.get().add(olTag.localName());
elements.get().add(pTag.localName());
elements.get().add(plaintextTag.localName());
elements.get().add(preTag.localName());
elements.get().add(sectionTag.localName());
elements.get().add(summaryTag.localName());
elements.get().add(tableTag.localName());
elements.get().add(tbodyTag.localName());
elements.get().add(tdTag.localName());
elements.get().add(tfootTag.localName());
elements.get().add(thTag.localName());
elements.get().add(theadTag.localName());
elements.get().add(trTag.localName());
elements.get().add(ulTag.localName());
elements.get().add(xmpTag.localName());
}
return elements.get().contains(name);
}
void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
next = NodeTraversal::next(*node);
if (!is<HTMLElement>(*node))
continue;
if (isProhibitedParagraphChild(downcast<HTMLElement>(*node).localName())) {
if (auto* paragraphElement = enclosingElementWithTag(positionInParentBeforeNode(node.get()), pTag)) {
auto* parent = paragraphElement->parentNode();
if (parent && parent->hasEditableStyle())
moveNodeOutOfAncestor(node, paragraphElement, insertedNodes);
}
}
if (isHeaderElement(node.get())) {
auto* headerElement = highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement);
if (headerElement) {
if (headerElement->parentNode() && headerElement->parentNode()->isContentRichlyEditable())
moveNodeOutOfAncestor(node, headerElement, insertedNodes);
else {
HTMLElement* newSpanElement = replaceElementWithSpanPreservingChildrenAndAttributes(downcast<HTMLElement>(node.get()));
insertedNodes.didReplaceNode(node.get(), newSpanElement);
}
}
}
}
}
void ReplaceSelectionCommand::moveNodeOutOfAncestor(PassRefPtr<Node> prpNode, PassRefPtr<Node> prpAncestor, InsertedNodes& insertedNodes)
{
RefPtr<Node> node = prpNode;
RefPtr<Node> ancestor = prpAncestor;
VisiblePosition positionAtEndOfNode = lastPositionInOrAfterNode(node.get());
VisiblePosition lastPositionInParagraph = lastPositionInNode(ancestor.get());
if (positionAtEndOfNode == lastPositionInParagraph) {
removeNode(node);
if (ancestor->nextSibling())
insertNodeBefore(node, ancestor->nextSibling());
else
appendNode(node, ancestor->parentNode());
} else {
RefPtr<Node> nodeToSplitTo = splitTreeToNode(node.get(), ancestor.get(), true);
removeNode(node);
insertNodeBefore(node, nodeToSplitTo);
}
if (!ancestor->firstChild()) {
insertedNodes.willRemoveNode(ancestor.get());
removeNode(ancestor.release());
}
}
static inline bool hasRenderedText(const Text& text)
{
return text.renderer() && text.renderer()->hasRenderedText();
}
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
{
document().updateLayoutIgnorePendingStylesheets();
Node* lastLeafInserted = insertedNodes.lastLeafInserted();
if (is<Text>(lastLeafInserted) && !hasRenderedText(downcast<Text>(*lastLeafInserted))
&& !enclosingElementWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
&& !enclosingElementWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
insertedNodes.willRemoveNode(lastLeafInserted);
removeNode(lastLeafInserted);
}
// We don't have to make sure that firstNodeInserted isn't inside a select or script element
// because it is a top level node in the fragment and the user can't insert into those elements.
Node* firstNodeInserted = insertedNodes.firstNodeInserted();
if (is<Text>(firstNodeInserted) && !hasRenderedText(downcast<Text>(*firstNodeInserted))) {
insertedNodes.willRemoveNode(firstNodeInserted);
removeNode(firstNodeInserted);
}
}
VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
{
// FIXME: Why is this hack here? What's special about <select> tags?
auto* enclosingSelect = enclosingElementWithTag(m_endOfInsertedContent, selectTag);
return enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent;
}
VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
{
return m_startOfInsertedContent;
}
static void removeHeadContents(ReplacementFragment& fragment)
{
if (fragment.isEmpty())
return;
Vector<Element*> toRemove;
auto it = descendantsOfType<Element>(*fragment.fragment()).begin();
auto end = descendantsOfType<Element>(*fragment.fragment()).end();
while (it != end) {
if (is<HTMLBaseElement>(*it) || is<HTMLLinkElement>(*it) || is<HTMLMetaElement>(*it) || is<HTMLStyleElement>(*it) || is<HTMLTitleElement>(*it)) {
toRemove.append(&*it);
it.traverseNextSkippingChildren();
continue;
}
++it;
}
for (auto& element : toRemove)
fragment.removeNode(element);
}
// Remove style spans before insertion if they are unnecessary. It's faster because we'll
// avoid doing a layout.
static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
{
Node* topNode = fragment.firstChild();
// Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
// and doesn't receive the optimization.
if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
return false;
// Either there are no style spans in the fragment or a WebKit client has added content to the fragment
// before inserting it. Look for and handle style spans after insertion.
if (!isLegacyAppleStyleSpan(topNode))
return false;
Node* wrappingStyleSpan = topNode;
RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
String styleText = styleAtInsertionPos->style()->asText();
// FIXME: This string comparison is a naive way of comparing two styles.
// We should be taking the diff and check that the diff is empty.
if (styleText != downcast<Element>(*wrappingStyleSpan).getAttribute(styleAttr))
return false;
fragment.removeNodePreservingChildren(wrappingStyleSpan);
return true;
}
// At copy time, WebKit wraps copied content in a span that contains the source document's
// default styles. If the copied Range inherits any other styles from its ancestors, we put
// those styles on a second span.
// This function removes redundant styles from those spans, and removes the spans if all their
// styles are redundant.
// We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
// We should remove styles from spans that are overridden by all of their children, either here
// or at copy time.
void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
{
HTMLElement* wrappingStyleSpan = nullptr;
// The style span that contains the source document's default style should be at
// the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
// so search for the top level style span instead of assuming it's at the top.
for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
if (isLegacyAppleStyleSpan(node)) {
wrappingStyleSpan = downcast<HTMLElement>(node);
break;
}
}
// There might not be any style spans if we're pasting from another application or if
// we are here because of a document.execCommand("InsertHTML", ...) call.
if (!wrappingStyleSpan)
return;
RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->inlineStyle());
ContainerNode* context = wrappingStyleSpan->parentNode();
// If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
// styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
context = document().documentElement();
// This operation requires that only editing styles to be removed from sourceDocumentStyle.
style->prepareToApplyAt(firstPositionInNode(context));
// Remove block properties in the span's style. This prevents properties that probably have no effect
// currently from affecting blocks later if the style is cloned for a new block element during a future
// editing operation.
// FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
// with block styles by the editing engine used to style them. WebKit doesn't do this, but others might.
style->removeBlockProperties();
if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(wrappingStyleSpan);
removeNodePreservingChildren(wrappingStyleSpan);
} else
setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->asText());
}
void ReplaceSelectionCommand::mergeEndIfNeeded()
{
if (!m_shouldMergeEnd)
return;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
// Bail to avoid infinite recursion.
if (m_movingParagraph) {
ASSERT_NOT_REACHED();
return;
}
// Merging two paragraphs will destroy the moved one's block styles. Always move the end of inserted forward
// to preserve the block style of the paragraph already in the document, unless the paragraph to move would
// include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
// block styles.
bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
// Merging forward could result in deleting the destination anchor node.
// To avoid this, we add a placeholder node before the start of the paragraph.
if (endOfParagraph(startOfParagraphToMove) == destination) {
RefPtr<Node> placeholder = createBreakElement(document());
insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
destination = VisiblePosition(positionBeforeNode(placeholder.get()));
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
// Merging forward will remove m_endOfInsertedContent from the document.
if (mergeForward) {
if (m_startOfInsertedContent.isOrphan())
m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
// If we merged text nodes, m_endOfInsertedContent could be null. If this is the case, we use m_startOfInsertedContent.
if (m_endOfInsertedContent.isNull())
m_endOfInsertedContent = m_startOfInsertedContent;
}
}
static Node* enclosingInline(Node* node)
{
while (ContainerNode* parent = node->parentNode()) {
if (isBlockFlowElement(parent) || parent->hasTagName(bodyTag))
return node;
// Stop if any previous sibling is a block.
for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
if (isBlockFlowElement(sibling))
return node;
}
node = parent;
}
return node;
}
static bool isInlineNodeWithStyle(const Node* node)
{
// We don't want to skip over any block elements.
if (isBlock(node))
return false;
if (!node->isHTMLElement())
return false;
// We can skip over elements whose class attribute is
// one of our internal classes.
const HTMLElement* element = static_cast<const HTMLElement*>(node);
const AtomicString& classAttributeValue = element->getAttribute(classAttr);
if (classAttributeValue == AppleTabSpanClass
|| classAttributeValue == AppleConvertedSpace
|| classAttributeValue == ApplePasteAsQuotation)
return true;
return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(element);
}
inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
{
Node* containgBlock = enclosingBlock(insertionPos.containerNode());
return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
}
void ReplaceSelectionCommand::doApply()
{
VisibleSelection selection = endingSelection();
ASSERT(selection.isCaretOrRange());
ASSERT(selection.start().deprecatedNode());
if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
return;
if (!selection.rootEditableElement())
return;
// In plain text only regions, we create style-less fragments, so the inserted content will automatically
// match the style of the surrounding area and so we can avoid unnecessary work below for m_matchStyle.
if (!selection.isContentRichlyEditable())
m_matchStyle = false;
ReplacementFragment fragment(document(), m_documentFragment.get(), selection);
if (performTrivialReplace(fragment))
return;
// We can skip matching the style if the selection is plain text.
if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style().userModify() == READ_WRITE_PLAINTEXT_ONLY)
&& (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style().userModify() == READ_WRITE_PLAINTEXT_ONLY))
m_matchStyle = false;
if (m_matchStyle) {
m_insertionStyle = EditingStyle::create(selection.start());
m_insertionStyle->mergeTypingStyle(document());
}
VisiblePosition visibleStart = selection.visibleStart();
VisiblePosition visibleEnd = selection.visibleEnd();
bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
Position insertionPos = selection.start();
bool shouldHandleMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary) && !m_ignoreMailBlockquote;
bool selectionIsPlainText = !selection.isContentRichlyEditable();
Element* currentRoot = selection.rootEditableElement();
if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !shouldHandleMailBlockquote)
|| startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
m_preventNesting = false;
if (selection.isRange()) {
// When the end of the selection being pasted into is at the end of a paragraph, and that selection
// spans multiple blocks, not merging may leave an empty line.
// When the start of the selection being pasted into is at the start of a block, not merging
// will leave hanging block(s).
// Merge blocks if the start of the selection was in a Mail blockquote, since we handle
// that case specially to prevent nesting.
bool mergeBlocksAfterDelete = shouldHandleMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
// FIXME: We should only expand to include fully selected special elements if we are copying a
// selection and pasting it on top of itself.
deleteSelection(false, mergeBlocksAfterDelete, true, false);
visibleStart = endingSelection().visibleStart();
if (fragment.hasInterchangeNewlineAtStart()) {
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
if (!isEndOfEditableOrNonEditableContent(visibleStart))
setEndingSelection(visibleStart.next());
} else
insertParagraphSeparator();
}
insertionPos = endingSelection().start();
} else {
ASSERT(selection.isCaret());
if (fragment.hasInterchangeNewlineAtStart()) {
VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
setEndingSelection(next);
else {
insertParagraphSeparator();
visibleStart = endingSelection().visibleStart();
}
}
// We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
// For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
// As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
// not <div>xbar<div>bar</div><div>bazx</div></div>.
// Don't do this if the selection started in a Mail blockquote.
if (m_preventNesting && !shouldHandleMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
insertParagraphSeparator();
setEndingSelection(endingSelection().visibleStart().previous());
}
insertionPos = endingSelection().start();
}
// We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
// out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case
// breaking the blockquote will prevent the content from actually being inserted in the table.
if (shouldHandleMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
applyCommandToComposite(BreakBlockquoteCommand::create(document()));