-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathmarkup.cpp
1503 lines (1273 loc) · 61.6 KB
/
markup.cpp
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) 2004-2021 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009, 2010, 2011 Google Inc. All rights reserved.
* Copyright (C) 2011 Igalia S.L.
* Copyright (C) 2011 Motorola Mobility. 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 "markup.h"
#include "ArchiveResource.h"
#include "CSSPrimitiveValue.h"
#include "CSSPropertyNames.h"
#include "CSSValue.h"
#include "CSSValueKeywords.h"
#include "CacheStorageProvider.h"
#include "ChildListMutationScope.h"
#include "Comment.h"
#include "CommonAtomStrings.h"
#include "ComposedTreeIterator.h"
#include "DeprecatedGlobalSettings.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DocumentType.h"
#include "Editing.h"
#include "Editor.h"
#include "EditorClient.h"
#include "ElementChildIteratorInlines.h"
#include "ElementRareData.h"
#include "EmptyClients.h"
#include "File.h"
#include "FrameLoader.h"
#include "HTMLAttachmentElement.h"
#include "HTMLBRElement.h"
#include "HTMLBodyElement.h"
#include "HTMLDivElement.h"
#include "HTMLHeadElement.h"
#include "HTMLHtmlElement.h"
#include "HTMLImageElement.h"
#include "HTMLNames.h"
#include "HTMLStyleElement.h"
#include "HTMLTableElement.h"
#include "HTMLTextAreaElement.h"
#include "HTMLTextFormControlElement.h"
#include "LocalFrame.h"
#include "MarkupAccumulator.h"
#include "MutableStyleProperties.h"
#include "NodeList.h"
#include "Page.h"
#include "PageConfiguration.h"
#include "PasteboardItemInfo.h"
#include "Quirks.h"
#include "Range.h"
#include "RenderBlock.h"
#include "ScriptWrappableInlines.h"
#include "Settings.h"
#include "SocketProvider.h"
#include "TextIterator.h"
#include "TextManipulationController.h"
#include "TypedElementDescendantIteratorInlines.h"
#include "VisibleSelection.h"
#include "VisibleUnits.h"
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <wtf/StdLibExtras.h>
#include <wtf/URL.h>
#include <wtf/URLParser.h>
#include <wtf/text/StringBuilder.h>
#if ENABLE(DATA_DETECTION)
#include "DataDetection.h"
#endif
namespace WebCore {
using namespace HTMLNames;
static bool propertyMissingOrEqualToNone(const StyleProperties*, CSSPropertyID);
class AttributeChange {
public:
AttributeChange()
: m_name(nullAtom(), nullAtom(), nullAtom())
{
}
AttributeChange(RefPtr<Element>&& element, QualifiedName&& name, AtomString&& value)
: m_element(WTFMove(element))
, m_name(WTFMove(name))
, m_value(WTFMove(value))
{
}
void apply()
{
m_element->setAttribute(m_name, m_value);
}
private:
RefPtr<Element> m_element;
QualifiedName m_name;
AtomString m_value;
};
static void completeURLs(DocumentFragment* fragment, const String& baseURL)
{
Vector<AttributeChange> changes;
URL parsedBaseURL({ }, baseURL);
for (Ref element : descendantsOfType<Element>(*fragment)) {
if (!element->hasAttributes())
continue;
for (const Attribute& attribute : element->attributesIterator()) {
if (element->attributeContainsURL(attribute) && !attribute.value().isEmpty())
changes.append(AttributeChange(element.copyRef(), QualifiedName { attribute.name() }, AtomString { element->completeURLsInAttributeValue(parsedBaseURL, attribute) }));
}
}
for (auto& change : changes)
change.apply();
}
void replaceSubresourceURLs(Ref<DocumentFragment>&& fragment, HashMap<AtomString, AtomString>&& replacementMap)
{
Vector<AttributeChange> changes;
for (Ref element : descendantsOfType<Element>(fragment)) {
if (!element->hasAttributes())
continue;
for (const Attribute& attribute : element->attributesIterator()) {
// FIXME: This won't work for srcset.
if (element->attributeContainsURL(attribute) && !attribute.value().isEmpty()) {
auto replacement = replacementMap.get(attribute.value());
if (!replacement.isNull())
changes.append({ element.copyRef(), QualifiedName { attribute.name() }, WTFMove(replacement) });
}
}
}
for (auto& change : changes)
change.apply();
}
struct ElementAttribute {
Ref<Element> element;
QualifiedName attributeName;
};
void removeSubresourceURLAttributes(Ref<DocumentFragment>&& fragment, Function<bool(const URL&)> shouldRemoveURL)
{
Vector<ElementAttribute> attributesToRemove;
for (Ref element : descendantsOfType<Element>(fragment)) {
if (!element->hasAttributes())
continue;
for (const Attribute& attribute : element->attributesIterator()) {
// FIXME: This won't work for srcset.
if (element->attributeContainsURL(attribute) && !attribute.value().isEmpty()) {
if (shouldRemoveURL(URL { attribute.value() }))
attributesToRemove.append({ element.copyRef(), attribute.name() });
}
}
}
for (auto& [element, attribute] : attributesToRemove)
element->removeAttribute(attribute);
}
std::unique_ptr<Page> createPageForSanitizingWebContent()
{
auto pageConfiguration = pageConfigurationWithEmptyClients(std::nullopt, PAL::SessionID::defaultSessionID());
auto page = makeUnique<Page>(WTFMove(pageConfiguration));
#if ENABLE(VIDEO)
page->settings().setMediaEnabled(false);
#endif
page->settings().setScriptEnabled(false);
page->settings().setHTMLParserScriptingFlagPolicy(HTMLParserScriptingFlagPolicy::Enabled);
page->settings().setPluginsEnabled(false);
page->settings().setAcceleratedCompositingEnabled(false);
page->settings().setLinkPreloadEnabled(false);
RefPtr frame = dynamicDowncast<LocalFrame>(page->mainFrame());
if (!frame)
return page;
frame->setView(LocalFrameView::create(*frame, IntSize { 800, 600 }));
frame->init();
FrameLoader& loader = frame->loader();
static constexpr ASCIILiteral markup = "<!DOCTYPE html><html><body></body></html>"_s;
RefPtr activeDocumentLoader = loader.activeDocumentLoader();
ASSERT(activeDocumentLoader);
auto& writer = activeDocumentLoader->writer();
writer.setMIMEType("text/html"_s);
writer.begin();
writer.insertDataSynchronously(markup);
writer.end();
RELEASE_ASSERT(frame->document()->body());
return page;
}
String sanitizeMarkup(const String& rawHTML, MSOListQuirks msoListQuirks, std::optional<Function<void(DocumentFragment&)>> fragmentSanitizer)
{
auto page = createPageForSanitizingWebContent();
RefPtr localMainFrame = dynamicDowncast<LocalFrame>(page->mainFrame());
if (!localMainFrame)
return String();
RefPtr stagingDocument = localMainFrame->document();
ASSERT(stagingDocument);
auto fragment = createFragmentFromMarkup(*stagingDocument, rawHTML, emptyString(), { });
if (fragmentSanitizer)
(*fragmentSanitizer)(fragment);
return sanitizedMarkupForFragmentInDocument(WTFMove(fragment), *stagingDocument, msoListQuirks, rawHTML);
}
UserSelectNoneStateCache::UserSelectNoneStateCache(TreeType treeType)
: m_useComposedTree(treeType == ComposedTree)
{
ASSERT(treeType == Tree || treeType == ComposedTree);
}
ContainerNode* UserSelectNoneStateCache::parentNode(Node& node)
{
if (m_useComposedTree)
return node.parentInComposedTree();
return node.parentOrShadowHostNode();
}
Node* UserSelectNoneStateCache::firstChild(Node& node)
{
if (m_useComposedTree)
return firstChildInComposedTreeIgnoringUserAgentShadow(node);
return node.firstChild();
}
Node* UserSelectNoneStateCache::nextSibling(Node& node)
{
if (m_useComposedTree)
return nextSiblingInComposedTreeIgnoringUserAgentShadow(node);
return node.nextSibling();
}
auto UserSelectNoneStateCache::computeState(Node& targetNode) -> State
{
auto it = m_cache.find(targetNode);
if (it != m_cache.end())
return it->value;
if (!Position::nodeIsUserSelectNone(&targetNode))
return State::NotUserSelectNone;
auto state = State::OnlyUserSelectNone;
RefPtr currentNode = &targetNode;
bool foundMixed = false;
while (currentNode) {
if (!Position::nodeIsUserSelectNone(currentNode.get())) {
state = State::Mixed;
// Only traverse upward once any mixed content is found
// since inner element may only contain user-select: none but we won't be able to tell apart.
foundMixed = true;
}
if (RefPtr child = firstChild(*currentNode); child && !foundMixed)
currentNode = WTFMove(child);
else if (currentNode == &targetNode)
break;
else if (RefPtr sibling = nextSibling(*currentNode); sibling && !foundMixed)
currentNode = WTFMove(sibling);
else {
RefPtr<Node> ancestor;
for (ancestor = parentNode(*currentNode); ancestor; ancestor = parentNode(*ancestor)) {
m_cache.set(*ancestor, state);
if (ancestor == &targetNode) {
currentNode = nullptr;
break;
}
if (RefPtr sibling = nextSibling(*ancestor); sibling && !foundMixed) {
currentNode = WTFMove(sibling);
break;
}
}
if (!ancestor)
currentNode = nullptr;
}
}
return state;
}
enum class MSOListMode : bool { Preserve, DoNotPreserve };
class StyledMarkupAccumulator final : public MarkupAccumulator {
public:
enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
StyledMarkupAccumulator(const Position& start, const Position& end, Vector<Ref<Node>>* nodes, ResolveURLs, SerializeComposedTree, IgnoreUserSelectNone,
AnnotateForInterchange, StandardFontFamilySerializationMode, MSOListMode, bool needsPositionStyleConversion, Node* highestNodeToBeSerialized = nullptr);
RefPtr<Node> serializeNodes(const Position& start, const Position& end);
void wrapWithNode(Node&, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
void wrapWithStyleNode(StyleProperties*, Document&, bool isBlock = false);
String takeResults();
bool needRelativeStyleWrapper() const { return m_needRelativeStyleWrapper; }
bool needClearingDiv() const { return m_needClearingDiv; }
using MarkupAccumulator::append;
ContainerNode* parentNode(Node& node)
{
if (UNLIKELY(m_useComposedTree))
return node.parentInComposedTree();
return node.parentOrShadowHostNode();
}
void prependMetaCharsetUTF8TagIfNonASCIICharactersArePresent()
{
if (!containsOnlyASCII())
m_reversedPrecedingMarkup.append("<meta charset=\"UTF-8\">"_s);
}
private:
bool containsOnlyASCII() const;
void appendStyleNodeOpenTag(StringBuilder&, StyleProperties*, Document&, bool isBlock = false);
const String& styleNodeCloseTag(bool isBlock = false);
String renderedTextRespectingRange(const Text&);
String textContentRespectingRange(const Text&);
bool shouldPreserveMSOListStyleForElement(const Element&);
enum class SpanReplacementType : uint8_t {
None,
Slot,
#if ENABLE(DATA_DETECTION)
DataDetector,
#endif
};
SpanReplacementType spanReplacementForElement(const Element&);
void appendStartTag(StringBuilder& out, const Element&, bool addDisplayInline, RangeFullySelectsNode);
void appendEndTag(StringBuilder& out, const Element&) override;
void appendCustomAttributes(StringBuilder&, const Element&, Namespaces*) override;
void appendText(StringBuilder& out, const Text&) override;
void appendStartTag(StringBuilder& out, const Element& element, Namespaces*) override
{
appendStartTag(out, element, false, DoesFullySelectNode);
}
Node* firstChild(Node& node)
{
if (UNLIKELY(m_useComposedTree))
return firstChildInComposedTreeIgnoringUserAgentShadow(node);
return node.firstChild();
}
Node* nextSibling(Node& node)
{
if (UNLIKELY(m_useComposedTree))
return nextSiblingInComposedTreeIgnoringUserAgentShadow(node);
return node.nextSibling();
}
Node* nextSkippingChildren(Node& node)
{
if (UNLIKELY(m_useComposedTree))
return nextSkippingChildrenInComposedTreeIgnoringUserAgentShadow(node);
return NodeTraversal::nextSkippingChildren(node);
}
bool hasChildNodes(Node& node)
{
if (UNLIKELY(m_useComposedTree))
return firstChildInComposedTreeIgnoringUserAgentShadow(node);
return node.hasChildNodes();
}
bool isDescendantOf(Node& node, Node& possibleAncestor)
{
if (UNLIKELY(m_useComposedTree))
return node.isDescendantOrShadowDescendantOf(&possibleAncestor);
return node.isDescendantOf(&possibleAncestor);
}
enum class NodeTraversalMode { EmitString, DoNotEmitString };
RefPtr<Node> traverseNodesForSerialization(Node& startNode, Node* pastEnd, NodeTraversalMode);
bool appendNodeToPreserveMSOList(Node&);
bool shouldAnnotate()
{
return m_annotate == AnnotateForInterchange::Yes;
}
bool shouldApplyWrappingStyle(const Node& node) const
{
return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode() && m_wrappingStyle && m_wrappingStyle->style();
}
Position m_start;
Position m_end;
Vector<String> m_reversedPrecedingMarkup;
const AnnotateForInterchange m_annotate;
RefPtr<Node> m_highestNodeToBeSerialized;
RefPtr<EditingStyle> m_wrappingStyle;
bool m_useComposedTree;
bool m_ignoresUserSelectNone;
bool m_needsPositionStyleConversion;
StandardFontFamilySerializationMode m_standardFontFamilySerializationMode;
bool m_shouldPreserveMSOList;
bool m_needRelativeStyleWrapper { false };
bool m_needClearingDiv { false };
bool m_inMSOList { false };
};
inline StyledMarkupAccumulator::StyledMarkupAccumulator(const Position& start, const Position& end, Vector<Ref<Node>>* nodes, ResolveURLs resolveURLs,
SerializeComposedTree serializeComposedTree, IgnoreUserSelectNone ignoreUserSelectNone, AnnotateForInterchange annotate,
StandardFontFamilySerializationMode standardFontFamilySerializationMode, MSOListMode msoListMode, bool needsPositionStyleConversion, Node* highestNodeToBeSerialized)
: MarkupAccumulator(nodes, resolveURLs, start.document()->isHTMLDocument() ? SerializationSyntax::HTML : SerializationSyntax::XML)
, m_start(start)
, m_end(end)
, m_annotate(annotate)
, m_highestNodeToBeSerialized(highestNodeToBeSerialized)
, m_useComposedTree(serializeComposedTree == SerializeComposedTree::Yes)
, m_ignoresUserSelectNone(ignoreUserSelectNone == IgnoreUserSelectNone::Yes && !start.document()->quirks().needsToCopyUserSelectNoneQuirk())
, m_needsPositionStyleConversion(needsPositionStyleConversion)
, m_standardFontFamilySerializationMode(standardFontFamilySerializationMode)
, m_shouldPreserveMSOList(msoListMode == MSOListMode::Preserve)
{
}
void StyledMarkupAccumulator::wrapWithNode(Node& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
{
StringBuilder markup;
if (is<Element>(node))
appendStartTag(markup, downcast<Element>(node), convertBlocksToInlines && isBlock(node), rangeFullySelectsNode);
else
appendNonElementNode(markup, node, nullptr);
m_reversedPrecedingMarkup.append(markup.toString());
endAppendingNode(node);
if (m_nodes)
m_nodes->append(node);
}
void StyledMarkupAccumulator::wrapWithStyleNode(StyleProperties* style, Document& document, bool isBlock)
{
StringBuilder openTag;
appendStyleNodeOpenTag(openTag, style, document, isBlock);
m_reversedPrecedingMarkup.append(openTag.toString());
append(styleNodeCloseTag(isBlock));
}
void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StyleProperties* style, Document& document, bool isBlock)
{
// With AnnotateForInterchange::Yes, wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
ASSERT(!shouldAnnotate() || propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
if (isBlock)
out.append("<div style=\"");
else
out.append("<span style=\"");
appendAttributeValue(out, style->asText(), document.isHTMLDocument());
out.append("\">");
}
const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
{
static NeverDestroyed<const String> divClose(MAKE_STATIC_STRING_IMPL("</div>"));
static NeverDestroyed<const String> styleSpanClose(MAKE_STATIC_STRING_IMPL("</span>"));
return isBlock ? divClose : styleSpanClose;
}
bool StyledMarkupAccumulator::containsOnlyASCII() const
{
for (auto& preceding : m_reversedPrecedingMarkup) {
if (!preceding.containsOnlyASCII())
return false;
}
return MarkupAccumulator::containsOnlyASCII();
}
String StyledMarkupAccumulator::takeResults()
{
CheckedUint32 length = this->length();
for (auto& string : m_reversedPrecedingMarkup)
length += string.length();
StringBuilder result;
result.reserveCapacity(length);
for (auto& string : makeReversedRange(m_reversedPrecedingMarkup))
result.append(string);
result.append(takeMarkup());
// Remove '\0' characters because they are not visibly rendered to the user.
return makeStringByReplacingAll(result.toString(), '\0', ""_s);
}
void StyledMarkupAccumulator::appendText(StringBuilder& out, const Text& text)
{
const bool parentIsTextarea = is<HTMLTextAreaElement>(text.parentElement());
const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
if (wrappingSpan) {
auto wrappingStyle = m_wrappingStyle->copy();
// FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
// Make sure spans are inline style in paste side e.g. span { display: block }.
wrappingStyle->forceInline();
// FIXME: Should this be included in forceInline?
wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
appendStyleNodeOpenTag(out, wrappingStyle->style(), text.protectedDocument());
}
if (!shouldAnnotate() || parentIsTextarea) {
auto content = textContentRespectingRange(text);
appendCharactersReplacingEntities(out, content, 0, content.length(), entityMaskForText(text));
} else {
const bool useRenderedText = !enclosingElementWithTag(firstPositionInNode(const_cast<Text*>(&text)), selectTag);
String content = useRenderedText ? renderedTextRespectingRange(text) : textContentRespectingRange(text);
StringBuilder buffer;
appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA);
out.append(convertHTMLTextToInterchangeFormat(buffer.toString(), &text));
}
if (wrappingSpan)
out.append(styleNodeCloseTag());
}
String StyledMarkupAccumulator::renderedTextRespectingRange(const Text& text)
{
TextIteratorBehaviors behaviors;
Position start = &text == m_start.containerNode() ? m_start : firstPositionInNode(const_cast<Text*>(&text));
Position end;
if (&text == m_end.containerNode())
end = m_end;
else {
end = lastPositionInNode(const_cast<Text*>(&text));
if (!m_end.isNull())
behaviors.add(TextIteratorBehavior::BehavesAsIfNodesFollowing);
}
if (m_ignoresUserSelectNone)
behaviors.add(TextIteratorBehavior::IgnoresUserSelectNone);
auto range = makeSimpleRange(start, end);
return range ? plainText(*range, behaviors) : emptyString();
}
String StyledMarkupAccumulator::textContentRespectingRange(const Text& text)
{
if (m_start.isNull() && m_end.isNull())
return text.data();
unsigned start = 0;
unsigned end = std::numeric_limits<unsigned>::max();
if (&text == m_start.containerNode())
start = m_start.offsetInContainerNode();
if (&text == m_end.containerNode())
end = m_end.offsetInContainerNode();
ASSERT(start < end);
return text.data().substring(start, end - start);
}
void StyledMarkupAccumulator::appendCustomAttributes(StringBuilder& out, const Element& element, Namespaces* namespaces)
{
#if ENABLE(ATTACHMENT_ELEMENT)
if (!DeprecatedGlobalSettings::attachmentElementEnabled())
return;
if (RefPtr attachment = dynamicDowncast<HTMLAttachmentElement>(element)) {
appendAttribute(out, element, { webkitattachmentidAttr, AtomString { attachment->uniqueIdentifier() } }, namespaces);
if (RefPtr file = attachment->file()) {
// These attributes are only intended for File deserialization, and are removed from the generated attachment
// element after we've deserialized and set its backing File, in restoreAttachmentElementsInFragment.
appendAttribute(out, element, { webkitattachmentpathAttr, AtomString { file->path() } }, namespaces);
appendAttribute(out, element, { webkitattachmentbloburlAttr, AtomString { file->url().string() } }, namespaces);
}
} else if (is<HTMLImageElement>(element)) {
if (RefPtr attachment = downcast<HTMLImageElement>(element).attachmentElement())
appendAttribute(out, element, { webkitattachmentidAttr, AtomString { attachment->uniqueIdentifier() } }, namespaces);
}
#else
UNUSED_PARAM(out);
UNUSED_PARAM(element);
UNUSED_PARAM(namespaces);
#endif
}
bool StyledMarkupAccumulator::shouldPreserveMSOListStyleForElement(const Element& element)
{
if (m_inMSOList)
return true;
if (m_shouldPreserveMSOList) {
auto style = element.getAttribute(styleAttr);
return style.startsWith("mso-list:"_s) || style.contains(";mso-list:"_s) || style.contains("\nmso-list:"_s);
}
return false;
}
StyledMarkupAccumulator::SpanReplacementType StyledMarkupAccumulator::spanReplacementForElement(const Element& element)
{
if (is<HTMLSlotElement>(element))
return SpanReplacementType::Slot;
#if ENABLE(DATA_DETECTION)
if (DataDetection::isDataDetectorElement(element))
return SpanReplacementType::DataDetector;
#endif
return SpanReplacementType::None;
}
void StyledMarkupAccumulator::appendStartTag(StringBuilder& out, const Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
{
const bool documentIsHTML = element.document().isHTMLDocument();
auto replacementType = spanReplacementForElement(element);
if (UNLIKELY(replacementType != SpanReplacementType::None))
out.append("<span");
else
appendOpenTag(out, element, nullptr);
appendCustomAttributes(out, element, nullptr);
const bool shouldAnnotateOrForceInline = element.isHTMLElement() && (shouldAnnotate() || addDisplayInline);
bool shouldOverrideStyleAttr = (shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element) || replacementType != SpanReplacementType::None) && !shouldPreserveMSOListStyleForElement(element);
if (element.hasAttributes()) {
for (const Attribute& attribute : element.attributesIterator()) {
// We'll handle the style attribute separately, below.
if (attribute.name() == styleAttr && shouldOverrideStyleAttr)
continue;
if (element.isEventHandlerAttribute(attribute) || element.attributeContainsJavaScriptURL(attribute))
continue;
#if ENABLE(DATA_DETECTION)
if (replacementType == SpanReplacementType::DataDetector && DataDetection::isDataDetectorAttribute(attribute.name()))
continue;
#endif
appendAttribute(out, element, attribute, 0);
}
}
if (shouldOverrideStyleAttr) {
RefPtr<EditingStyle> newInlineStyle;
if (shouldApplyWrappingStyle(element)) {
newInlineStyle = m_wrappingStyle->copy();
newInlineStyle->removePropertiesInElementDefaultStyle(*const_cast<Element*>(&element));
newInlineStyle->removeStyleConflictingWithStyleOfNode(*const_cast<Element*>(&element));
} else
newInlineStyle = EditingStyle::create();
if (replacementType == SpanReplacementType::Slot)
newInlineStyle->addDisplayContents();
if (is<StyledElement>(element) && downcast<StyledElement>(element).inlineStyle())
newInlineStyle->overrideWithStyle(*downcast<StyledElement>(element).inlineStyle());
#if ENABLE(DATA_DETECTION)
if (replacementType == SpanReplacementType::DataDetector && newInlineStyle->style())
newInlineStyle->style()->removeProperty(CSSPropertyTextDecorationColor);
#endif
if (shouldAnnotateOrForceInline) {
if (shouldAnnotate())
newInlineStyle->mergeStyleFromRulesForSerialization(downcast<HTMLElement>(*const_cast<Element*>(&element)), m_standardFontFamilySerializationMode);
if (addDisplayInline)
newInlineStyle->forceInline();
if (m_needsPositionStyleConversion) {
m_needRelativeStyleWrapper |= newInlineStyle->convertPositionStyle();
m_needClearingDiv |= newInlineStyle->isFloating();
}
// If the node is not fully selected by the range, then we don't want to keep styles that affect its relationship to the nodes around it
// only the ones that affect it and the nodes within it.
if (rangeFullySelectsNode == DoesNotFullySelectNode && newInlineStyle->style())
newInlineStyle->style()->removeProperty(CSSPropertyFloat);
}
if (!newInlineStyle->isEmpty()) {
out.append(" style=\"");
appendAttributeValue(out, newInlineStyle->style()->asText(), documentIsHTML);
out.append('"');
}
}
appendCloseTag(out, element);
}
void StyledMarkupAccumulator::appendEndTag(StringBuilder& out, const Element& element)
{
if (UNLIKELY(spanReplacementForElement(element) != SpanReplacementType::None))
out.append("</span>");
else
MarkupAccumulator::appendEndTag(out, element);
}
RefPtr<Node> StyledMarkupAccumulator::serializeNodes(const Position& start, const Position& end)
{
ASSERT(start <= end);
RefPtr startNode = start.firstNode();
if (!startNode)
return nullptr;
RefPtr pastEnd = end.computeNodeAfterPosition();
if (!pastEnd && end.containerNode())
pastEnd = nextSkippingChildren(*end.protectedContainerNode());
if (!m_highestNodeToBeSerialized)
m_highestNodeToBeSerialized = traverseNodesForSerialization(*startNode, pastEnd.get(), NodeTraversalMode::DoNotEmitString);
if (m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode())
m_wrappingStyle = EditingStyle::wrappingStyleForSerialization(*m_highestNodeToBeSerialized->protectedParentNode(), shouldAnnotate(), m_standardFontFamilySerializationMode);
return traverseNodesForSerialization(*startNode, pastEnd.get(), NodeTraversalMode::EmitString);
}
RefPtr<Node> StyledMarkupAccumulator::traverseNodesForSerialization(Node& startNode, Node* pastEnd, NodeTraversalMode traversalMode)
{
const bool shouldEmit = traversalMode == NodeTraversalMode::EmitString;
UserSelectNoneStateCache userSelectNoneStateCache(m_useComposedTree ? ComposedTree : Tree);
m_inMSOList = false;
unsigned depth = 0;
auto enterNode = [&] (Node& node) {
if (UNLIKELY(m_shouldPreserveMSOList) && shouldEmit) {
if (appendNodeToPreserveMSOList(node))
return false;
}
bool isDisplayContents = is<Element>(node) && downcast<Element>(node).hasDisplayContents();
if (!node.renderer() && !isDisplayContents && !enclosingElementWithTag(firstPositionInOrBeforeNode(&node), selectTag))
return false;
if (m_ignoresUserSelectNone && userSelectNoneStateCache.nodeOnlyContainsUserSelectNone(node))
return false;
++depth;
if (shouldEmit)
startAppendingNode(node);
return true;
};
RefPtr<Node> lastClosed;
auto exitNode = [&] (Node& node) {
bool closing = depth;
if (depth)
--depth;
if (shouldEmit) {
if (closing)
endAppendingNode(node);
else
wrapWithNode(node);
}
lastClosed = &node;
};
RefPtr<Node> lastNode;
RefPtr<Node> next;
for (RefPtr n = &startNode; n != pastEnd; lastNode = n, n = next) {
Vector<RefPtr<Node>, 8> exitedAncestors;
next = nullptr;
auto advanceToAncestorSibling = [&]() {
if (auto* sibling = nextSibling(*n)) {
next = sibling;
return;
}
for (RefPtr ancestor = parentNode(*n); ancestor; ancestor = parentNode(*ancestor)) {
exitedAncestors.append(ancestor);
if (RefPtr sibling = nextSibling(*ancestor)) {
next = WTFMove(sibling);
return;
}
}
};
if (RefPtr child = firstChild(*n))
next = WTFMove(child);
else
advanceToAncestorSibling();
ASSERT(next || !pastEnd || n->containsIncludingShadowDOM(pastEnd));
if (isBlock(*n) && canHaveChildrenForEditing(*n) && next == pastEnd) {
// Don't write out empty block containers that aren't fully selected.
continue;
}
bool didEnterNode = false;
if (!enterNode(*n)) {
exitedAncestors.clear();
advanceToAncestorSibling();
} else if (!hasChildNodes(*n))
exitNode(*n);
else
didEnterNode = true;
bool aboutToGoPastEnd = pastEnd && !didEnterNode && (!next || isDescendantOf(*pastEnd, *n));
if (aboutToGoPastEnd)
next = pastEnd;
for (auto& ancestor : exitedAncestors) {
if (!depth && next == pastEnd)
break;
exitNode(*ancestor);
}
}
ASSERT(lastNode || !depth);
if (depth) {
for (RefPtr ancestor = parentNode(pastEnd ? *pastEnd : *lastNode); ancestor && depth; ancestor = parentNode(*ancestor))
exitNode(*ancestor);
}
return lastClosed;
}
bool StyledMarkupAccumulator::appendNodeToPreserveMSOList(Node& node)
{
if (RefPtr commentNode = dynamicDowncast<Comment>(node)) {
if (!m_inMSOList && commentNode->data() == "[if !supportLists]"_s)
m_inMSOList = true;
else if (m_inMSOList && commentNode->data() == "[endif]"_s)
m_inMSOList = false;
else
return false;
startAppendingNode(*commentNode);
return true;
}
if (is<HTMLStyleElement>(node)) {
RefPtr textChild = dynamicDowncast<Text>(node.firstChild());
if (!textChild)
return false;
auto& styleContent = textChild->data();
const auto msoStyleDefinitionsStart = styleContent.find("/* Style Definitions */"_s);
const auto msoListDefinitionsStart = styleContent.find("/* List Definitions */"_s);
const auto lastListItem = styleContent.reverseFind("\n@list"_s);
if (msoListDefinitionsStart == notFound || lastListItem == notFound)
return false;
const auto start = msoStyleDefinitionsStart != notFound && msoStyleDefinitionsStart < msoListDefinitionsStart ? msoStyleDefinitionsStart : msoListDefinitionsStart;
const auto msoListDefinitionsEnd = styleContent.find(";}\n"_s, lastListItem);
if (msoListDefinitionsEnd == notFound || start >= msoListDefinitionsEnd)
return false;
append("<head><style class=\"", WebKitMSOListQuirksStyle, "\">\n<!--\n",
StringView(textChild->data()).substring(start, msoListDefinitionsEnd - start + 3),
"\n-->\n</style></head>");
return true;
}
return false;
}
static Node* ancestorToRetainStructureAndAppearanceForBlock(Node* commonAncestorBlock)
{
if (!commonAncestorBlock)
return nullptr;
if (commonAncestorBlock->hasTagName(tbodyTag) || commonAncestorBlock->hasTagName(trTag)) {
ContainerNode* table = commonAncestorBlock->parentNode();
while (table && !is<HTMLTableElement>(*table))
table = table->parentNode();
return table;
}
if (isNonTableCellHTMLBlockElement(commonAncestorBlock))
return commonAncestorBlock;
return nullptr;
}
static inline Node* ancestorToRetainStructureAndAppearance(Node* commonAncestor)
{
return ancestorToRetainStructureAndAppearanceForBlock(enclosingBlock(commonAncestor).get());
}
static bool propertyMissingOrEqualToNone(const StyleProperties* style, CSSPropertyID propertyID)
{
if (!style)
return false;
return style->propertyAsValueID(propertyID).value_or(CSSValueNone) == CSSValueNone;
}
static bool needInterchangeNewlineAfter(const VisiblePosition& v)
{
VisiblePosition next = v.next();
RefPtr upstreamNode = next.deepEquivalent().upstream().deprecatedNode();
RefPtr downstreamNode = v.deepEquivalent().downstream().deprecatedNode();
// Add an interchange newline if a paragraph break is selected and a br won't already be added to the markup to represent it.
return isEndOfParagraph(v) && isStartOfParagraph(next) && !(upstreamNode->hasTagName(brTag) && upstreamNode == downstreamNode);
}
static RefPtr<EditingStyle> styleFromMatchedRulesAndInlineDecl(Node& node)
{
if (!is<HTMLElement>(node))
return nullptr;
Ref element = downcast<HTMLElement>(node);
auto style = EditingStyle::create(element->inlineStyle());
style->mergeStyleFromRules(element);
return style;
}
static bool isElementPresentational(const Node& node)
{
return node.hasTagName(uTag) || node.hasTagName(sTag) || node.hasTagName(strikeTag)
|| node.hasTagName(iTag) || node.hasTagName(emTag) || node.hasTagName(bTag) || node.hasTagName(strongTag);
}
static RefPtr<Node> highestAncestorToWrapMarkup(const Position& start, const Position& end, Node& commonAncestor, AnnotateForInterchange annotate)
{
RefPtr<Node> specialCommonAncestor;
if (annotate == AnnotateForInterchange::Yes) {
// Include ancestors that aren't completely inside the range but are required to retain
// the structure and appearance of the copied markup.
specialCommonAncestor = ancestorToRetainStructureAndAppearance(&commonAncestor);
if (auto parentListNode = enclosingNodeOfType(start, isListItem)) {
if (!editingIgnoresContent(*parentListNode) && VisibleSelection::selectionFromContentsOfNode(parentListNode.get()) == VisibleSelection(start, end)) {
specialCommonAncestor = parentListNode->parentNode();
while (specialCommonAncestor && !isListHTMLElement(specialCommonAncestor.get()))
specialCommonAncestor = specialCommonAncestor->parentNode();
}
}
// Retain the Mail quote level by including all ancestor mail block quotes.
if (RefPtr highestMailBlockquote = highestEnclosingNodeOfType(start, isMailBlockquote, CanCrossEditingBoundary))
specialCommonAncestor = WTFMove(highestMailBlockquote);
}
RefPtr checkAncestor = specialCommonAncestor ? specialCommonAncestor : RefPtr { &commonAncestor };
if (checkAncestor->renderer() && checkAncestor->renderer()->containingBlock()) {
RefPtr newSpecialCommonAncestor = highestEnclosingNodeOfType(firstPositionInNode(checkAncestor.get()), &isElementPresentational, CanCrossEditingBoundary, checkAncestor->renderer()->containingBlock()->protectedElement().get());
if (newSpecialCommonAncestor)
specialCommonAncestor = WTFMove(newSpecialCommonAncestor);
}
// If a single tab is selected, commonAncestor will be a text node inside a tab span.
// If two or more tabs are selected, commonAncestor will be the tab span.
// In either case, if there is a specialCommonAncestor already, it will necessarily be above
// any tab span that needs to be included.
if (!specialCommonAncestor && isTabSpanTextNode(&commonAncestor))
specialCommonAncestor = commonAncestor.parentNode();
if (!specialCommonAncestor && isTabSpanNode(&commonAncestor))
specialCommonAncestor = &commonAncestor;
if (RefPtr enclosingAnchor = enclosingElementWithTag(firstPositionInNode(specialCommonAncestor ? specialCommonAncestor.get() : &commonAncestor), aTag))
specialCommonAncestor = WTFMove(enclosingAnchor);
return specialCommonAncestor;
}
static String serializePreservingVisualAppearanceInternal(const Position& start, const Position& end, Vector<Ref<Node>>* nodes, ResolveURLs resolveURLs, SerializeComposedTree serializeComposedTree, IgnoreUserSelectNone ignoreUserSelectNone,
AnnotateForInterchange annotate, ConvertBlocksToInlines convertBlocksToInlines, StandardFontFamilySerializationMode standardFontFamilySerializationMode, MSOListMode msoListMode)
{
static NeverDestroyed<const String> interchangeNewlineString(MAKE_STATIC_STRING_IMPL("<br class=\"" AppleInterchangeNewline "\">"));
if (!(start < end))
return emptyString();
RefPtr commonAncestor = commonInclusiveAncestor(start, end);
if (!commonAncestor)
return emptyString();
Ref document = *start.document();
document->updateLayoutIgnorePendingStylesheets();
VisiblePosition visibleStart { start };
VisiblePosition visibleEnd { end };
RefPtr body = enclosingElementWithTag(firstPositionInNode(commonAncestor.get()), bodyTag);
RefPtr<Element> fullySelectedRoot;
// FIXME: Do this for all fully selected blocks, not just the body.
if (body && VisiblePosition(firstPositionInNode(body.get())) == visibleStart && VisiblePosition(lastPositionInNode(body.get())) == visibleEnd)
fullySelectedRoot = body;
bool needsPositionStyleConversion = body && fullySelectedRoot == body && document->settings().shouldConvertPositionStyleOnCopy();
RefPtr specialCommonAncestor = highestAncestorToWrapMarkup(start, end, *commonAncestor, annotate);