/
StyleProperties.cpp
2021 lines (1758 loc) · 75.9 KB
/
StyleProperties.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
/*
* (C) 1999-2003 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004-2022 Apple Inc. All rights reserved.
* Copyright (C) 2011 Research In Motion Limited. All rights reserved.
* Copyright (C) 2013 Intel Corporation. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "StyleProperties.h"
#include "CSSBorderImageWidthValue.h"
#include "CSSComputedStyleDeclaration.h"
#include "CSSCustomPropertyValue.h"
#include "CSSGridLineNamesValue.h"
#include "CSSGridTemplateAreasValue.h"
#include "CSSOffsetRotateValue.h"
#include "CSSParser.h"
#include "CSSParserIdioms.h"
#include "CSSPendingSubstitutionValue.h"
#include "CSSPrimitiveValue.h"
#include "CSSPropertyParser.h"
#include "CSSTokenizer.h"
#include "CSSValueKeywords.h"
#include "CSSValueList.h"
#include "CSSValuePool.h"
#include "Color.h"
#include "Document.h"
#include "FontSelectionValueInlines.h"
#include "PropertySetCSSStyleDeclaration.h"
#include "Rect.h"
#include "StylePropertyShorthand.h"
#include "StylePropertyShorthandFunctions.h"
#include "StyleSheetContents.h"
#include <bitset>
#include <wtf/text/StringBuilder.h>
#ifndef NDEBUG
#include <stdio.h>
#include <wtf/text/CString.h>
#endif
namespace WebCore {
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(StyleProperties);
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(ImmutableStyleProperties);
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(MutableStyleProperties);
static size_t sizeForImmutableStylePropertiesWithPropertyCount(unsigned count)
{
return sizeof(ImmutableStyleProperties) - sizeof(void*) + sizeof(StylePropertyMetadata) * count + sizeof(PackedPtr<const CSSValue>) * count;
}
static bool isCSSWideValueKeyword(StringView value)
{
return value == "initial"_s || value == "inherit"_s || value == "unset"_s || value == "revert"_s || value == "revert-layer"_s;
}
static bool isValueIDIncludingList(const CSSValue& value, CSSValueID id)
{
if (is<CSSValueList>(value)) {
auto& valueList = downcast<CSSValueList>(value);
if (valueList.size() != 1)
return false;
auto* item = valueList.item(0);
return item && isValueID(*item, id);
}
return isValueID(value, id);
}
static bool isValueIDIncludingList(const RefPtr<CSSValue>& value, CSSValueID id)
{
return value && isValueIDIncludingList(*value, id);
}
Ref<ImmutableStyleProperties> ImmutableStyleProperties::create(const CSSProperty* properties, unsigned count, CSSParserMode cssParserMode)
{
void* slot = ImmutableStylePropertiesMalloc::malloc(sizeForImmutableStylePropertiesWithPropertyCount(count));
return adoptRef(*new (NotNull, slot) ImmutableStyleProperties(properties, count, cssParserMode));
}
Ref<ImmutableStyleProperties> StyleProperties::immutableCopyIfNeeded() const
{
if (is<ImmutableStyleProperties>(*this))
return downcast<ImmutableStyleProperties>(const_cast<StyleProperties&>(*this));
const MutableStyleProperties& mutableThis = downcast<MutableStyleProperties>(*this);
return ImmutableStyleProperties::create(mutableThis.m_propertyVector.data(), mutableThis.m_propertyVector.size(), cssParserMode());
}
MutableStyleProperties::MutableStyleProperties(CSSParserMode cssParserMode)
: StyleProperties(cssParserMode, MutablePropertiesType)
{
}
MutableStyleProperties::MutableStyleProperties(Vector<CSSProperty>&& properties)
: StyleProperties(HTMLStandardMode, MutablePropertiesType)
, m_propertyVector(WTFMove(properties))
{
}
MutableStyleProperties::~MutableStyleProperties() = default;
ImmutableStyleProperties::ImmutableStyleProperties(const CSSProperty* properties, unsigned length, CSSParserMode cssParserMode)
: StyleProperties(cssParserMode, length)
{
StylePropertyMetadata* metadataArray = const_cast<StylePropertyMetadata*>(this->metadataArray());
PackedPtr<CSSValue>* valueArray = bitwise_cast<PackedPtr<CSSValue>*>(this->valueArray());
for (unsigned i = 0; i < length; ++i) {
metadataArray[i] = properties[i].metadata();
auto* value = properties[i].value();
valueArray[i] = value;
value->ref();
}
}
ImmutableStyleProperties::~ImmutableStyleProperties()
{
PackedPtr<CSSValue>* valueArray = bitwise_cast<PackedPtr<CSSValue>*>(this->valueArray());
for (unsigned i = 0; i < m_arraySize; ++i)
valueArray[i]->deref();
}
MutableStyleProperties::MutableStyleProperties(const StyleProperties& other)
: StyleProperties(other.cssParserMode(), MutablePropertiesType)
{
if (is<MutableStyleProperties>(other))
m_propertyVector = downcast<MutableStyleProperties>(other).m_propertyVector;
else {
const auto& immutableOther = downcast<ImmutableStyleProperties>(other);
unsigned propertyCount = immutableOther.propertyCount();
m_propertyVector.reserveInitialCapacity(propertyCount);
for (unsigned i = 0; i < propertyCount; ++i)
m_propertyVector.uncheckedAppend(immutableOther.propertyAt(i).toCSSProperty());
}
}
String StyleProperties::commonShorthandChecks(const StylePropertyShorthand& shorthand) const
{
std::optional<bool> importance;
size_t numSetFromShorthand = 0;
for (size_t i = 0; i < shorthand.length(); i++) {
// FIXME: Shouldn't serialize the shorthand if some longhand is missing.
int propertyIndex = findPropertyIndex(shorthand.properties()[i]);
if (propertyIndex == -1)
continue;
auto property = propertyAt(propertyIndex);
// Don't serialize the shorthand if longhands have different importance.
bool isImportant = property.isImportant();
if (importance.value_or(isImportant) != isImportant)
return emptyString();
importance = isImportant;
auto value = property.value();
auto hasBeenSetFromLonghand = is<CSSVariableReferenceValue>(value);
auto hasBeenSetFromShorthand = is<CSSPendingSubstitutionValue>(value);
auto hasNotBeenSetFromRequestedShorthand = hasBeenSetFromShorthand && downcast<CSSPendingSubstitutionValue>(*value).shorthandPropertyId() != shorthand.id();
// Request for shorthand value should return empty string if any longhand values have been
// set to a variable or if they were set to a variable by a different shorthand.
if (hasBeenSetFromLonghand || hasNotBeenSetFromRequestedShorthand)
return emptyString();
if (hasBeenSetFromShorthand)
numSetFromShorthand += 1;
}
if (numSetFromShorthand) {
if (numSetFromShorthand != shorthand.length())
return emptyString();
return downcast<CSSPendingSubstitutionValue>(* getPropertyCSSValue(shorthand.properties()[0])).shorthandValue().cssText();
}
return nullString();
}
String StyleProperties::getPropertyValue(CSSPropertyID propertyID) const
{
if (auto value = getPropertyCSSValue(propertyID)) {
switch (propertyID) {
case CSSPropertyFillOpacity:
case CSSPropertyFloodOpacity:
case CSSPropertyOpacity:
case CSSPropertyStopOpacity:
case CSSPropertyStrokeOpacity:
// Opacity percentage values serialize as a fraction in the range 0-1, not "%".
if (is<CSSPrimitiveValue>(*value) && downcast<CSSPrimitiveValue>(*value).isPercentage())
return makeString(downcast<CSSPrimitiveValue>(*value).doubleValue() / 100);
FALLTHROUGH;
default:
return value->cssText();
}
}
auto shorthand = shorthandForProperty(propertyID);
if (!shorthand.length())
return nullString();
if (auto result = commonShorthandChecks(shorthand); !result.isNull())
return result.isEmpty() ? nullString() : result;
switch (propertyID) {
case CSSPropertyAll:
return getCommonValue(shorthand);
case CSSPropertyAnimation:
case CSSPropertyBackground:
case CSSPropertyBackgroundPosition:
case CSSPropertyMask:
case CSSPropertyMaskPosition:
case CSSPropertyTransition:
case CSSPropertyWebkitMask:
case CSSPropertyWebkitMaskPosition:
return getLayeredShorthandValue(shorthand);
case CSSPropertyBorderBlockEnd:
case CSSPropertyBorderBlockStart:
case CSSPropertyBorderBottom:
case CSSPropertyBorderInlineEnd:
case CSSPropertyBorderInlineStart:
case CSSPropertyBorderLeft:
case CSSPropertyBorderRight:
case CSSPropertyBorderTop:
case CSSPropertyColumnRule:
case CSSPropertyColumns:
case CSSPropertyFlex:
case CSSPropertyFlexFlow:
case CSSPropertyListStyle:
case CSSPropertyOutline:
case CSSPropertyPerspectiveOrigin:
case CSSPropertyTextEmphasis:
case CSSPropertyTransformOrigin:
case CSSPropertyWebkitTextDecoration:
case CSSPropertyWebkitTextStroke:
return getShorthandValue(shorthand);
case CSSPropertyBorderBlockColor:
case CSSPropertyBorderBlockStyle:
case CSSPropertyBorderBlockWidth:
case CSSPropertyBorderInlineColor:
case CSSPropertyBorderInlineStyle:
case CSSPropertyBorderInlineWidth:
case CSSPropertyContainIntrinsicSize:
case CSSPropertyGap:
case CSSPropertyInsetBlock:
case CSSPropertyInsetInline:
case CSSPropertyMarginBlock:
case CSSPropertyMarginInline:
case CSSPropertyOverflow:
case CSSPropertyOverscrollBehavior:
case CSSPropertyPaddingBlock:
case CSSPropertyPaddingInline:
case CSSPropertyScrollMarginBlock:
case CSSPropertyScrollMarginInline:
case CSSPropertyScrollPaddingBlock:
case CSSPropertyScrollPaddingInline:
return get2Values(shorthand);
case CSSPropertyBorderColor:
case CSSPropertyBorderStyle:
case CSSPropertyBorderWidth:
case CSSPropertyInset:
case CSSPropertyMargin:
case CSSPropertyPadding:
case CSSPropertyScrollMargin:
case CSSPropertyScrollPadding:
return get4Values(shorthand);
case CSSPropertyBorderSpacing:
return borderSpacingValue(shorthand);
case CSSPropertyBorder:
return borderPropertyValue(borderWidthShorthand(), borderStyleShorthand(), borderColorShorthand());
case CSSPropertyBorderBlock:
return borderPropertyValue(borderBlockWidthShorthand(), borderBlockStyleShorthand(), borderBlockColorShorthand());
case CSSPropertyBorderInline:
return borderPropertyValue(borderInlineWidthShorthand(), borderInlineStyleShorthand(), borderInlineColorShorthand());
case CSSPropertyBorderImage:
case CSSPropertyWebkitBorderImage:
return borderImagePropertyValue(shorthand);
case CSSPropertyBorderRadius:
case CSSPropertyWebkitBorderRadius:
return borderRadiusShorthandValue(shorthand);
case CSSPropertyOffset:
return offsetValue();
case CSSPropertyContainer:
if (auto type = getPropertyCSSValue(CSSPropertyContainerType)) {
if (isValueID(type, CSSValueNormal)) {
if (auto name = getPropertyCSSValue(CSSPropertyContainerName))
return name->cssText();
return { };
}
}
return getShorthandValue(shorthand, " / ");
case CSSPropertyGridArea:
return getGridAreaShorthandValue();
case CSSPropertyGridTemplate:
return getGridTemplateValue();
case CSSPropertyGrid:
return getGridValue();
case CSSPropertyGridColumn:
case CSSPropertyGridRow:
return getGridRowColumnShorthandValue(shorthand);
case CSSPropertyPageBreakInside:
case CSSPropertyWebkitColumnBreakInside:
return breakInsideShorthandValue(shorthand);
case CSSPropertyPageBreakAfter:
case CSSPropertyPageBreakBefore:
return pageBreakValue(shorthand);
case CSSPropertyWebkitColumnBreakAfter:
case CSSPropertyWebkitColumnBreakBefore:
return webkitColumnBreakValue(shorthand);
case CSSPropertyPlaceContent:
case CSSPropertyPlaceItems:
case CSSPropertyPlaceSelf:
return getAlignmentShorthandValue(shorthand);
case CSSPropertyFont:
return fontValue(shorthand);
case CSSPropertyFontVariant:
return fontVariantValue(shorthand);
case CSSPropertyFontSynthesis:
return fontSynthesisValue();
case CSSPropertyTextDecorationSkip:
case CSSPropertyTextDecoration:
case CSSPropertyWebkitBackgroundSize:
case CSSPropertyWebkitPerspective:
case CSSPropertyWebkitTextOrientation:
ASSERT(shorthand.length() == 1);
if (auto value = getPropertyCSSValue(shorthand.properties()[0]))
return value->cssText();
return String();
case CSSPropertyMarker:
ASSERT(shorthand.length() == 3);
// FIXME: Stop ignoring marker-mid and marker-end (http://webkit.org/b/248308).
if (auto value = getPropertyCSSValue(CSSPropertyMarkerStart))
return value->cssText();
return String();
default:
ASSERT_NOT_REACHED();
return String();
}
}
std::optional<Color> StyleProperties::propertyAsColor(CSSPropertyID property) const
{
auto colorValue = getPropertyCSSValue(property);
if (!is<CSSPrimitiveValue>(colorValue))
return std::nullopt;
auto& primitiveColor = downcast<CSSPrimitiveValue>(*colorValue);
return primitiveColor.isRGBColor() ? primitiveColor.color() : CSSParser::parseColorWithoutContext(colorValue->cssText());
}
std::optional<CSSValueID> StyleProperties::propertyAsValueID(CSSPropertyID property) const
{
auto value = getPropertyCSSValue(property);
if (!value)
return std::nullopt;
return valueID(value.get());
}
String StyleProperties::getCustomPropertyValue(const String& propertyName) const
{
RefPtr<CSSValue> value = getCustomPropertyCSSValue(propertyName);
if (value)
return value->cssText();
return String();
}
String StyleProperties::borderSpacingValue(const StylePropertyShorthand& shorthand) const
{
ASSERT(shorthand.length() == 2);
auto horizontalValue = getPropertyCSSValue(shorthand.properties()[0]);
auto verticalValue = getPropertyCSSValue(shorthand.properties()[1]);
// While standard border-spacing property does not allow specifying border-spacing-vertical without
// specifying border-spacing-horizontal <http://www.w3.org/TR/CSS21/tables.html#separated-borders>,
// -webkit-border-spacing-vertical can be set without -webkit-border-spacing-horizontal.
if (!horizontalValue || !verticalValue)
return String();
String horizontalValueCSSText = horizontalValue->cssText();
String verticalValueCSSText = verticalValue->cssText();
if (horizontalValueCSSText == verticalValueCSSText)
return horizontalValueCSSText;
return horizontalValueCSSText + ' ' + verticalValueCSSText;
}
static std::optional<CSSValueID> fontStretchKeyword(double value)
{
// If the numeric value does not fit in the fixed point FontSelectionValue, don't convert it to a keyword even if it rounds to a keyword value.
float valueAsFloat = value;
FontSelectionValue valueAsFontSelectionValue { valueAsFloat };
float valueAsFloatAfterRoundTrip = valueAsFontSelectionValue;
if (value != valueAsFloatAfterRoundTrip)
return std::nullopt;
return fontStretchKeyword(valueAsFontSelectionValue);
}
String StyleProperties::fontValue(const StylePropertyShorthand& shorthand) const
{
ASSERT(shorthand.id() == CSSPropertyFont);
// If all properties are set to the same special keyword, serialize as that.
// If some but not all properties are, the font shorthand can't represent that, serialize as empty string.
std::optional<CSSValueID> specialKeyword;
bool allSpecialKeywords = true;
for (auto property : shorthand) {
// Can't call propertyAsValueID here because we need to bypass the isSystemFontShorthand check in getPropertyCSSValue.
int index = findPropertyIndex(property);
auto keyword = index == -1 ? CSSValueInvalid : valueID(propertyAt(index).value());
if (!CSSPropertyParserHelpers::isSystemFontShorthand(keyword) && !isCSSWideKeyword(keyword))
allSpecialKeywords = false;
else {
if (specialKeyword.value_or(keyword) != keyword)
return emptyString();
specialKeyword = keyword;
}
}
if (specialKeyword)
return allSpecialKeywords ? nameString(*specialKeyword) : emptyString();
// If a subproperty is not set to the initial value, the font shorthand can't represent that, serialize as empty string.
for (auto [property, initialValue] : fontShorthandSubpropertiesResetToInitialValues) {
auto keyword = propertyAsValueID(property);
if (keyword && *keyword != initialValue)
return emptyString();
}
// These properties are the mandatory ones. If either is missing, serialize as empty string.
auto size = getPropertyCSSValue(CSSPropertyFontSize);
auto family = getPropertyCSSValue(CSSPropertyFontFamily);
if (!size || !family)
return emptyString();
// Only two values of variant-caps can be serialized in the font shorthand, if the value is anything else serialize as empty string.
auto variantCaps = propertyAsValueID(CSSPropertyFontVariantCaps);
if (variantCaps && *variantCaps != CSSValueNormal && *variantCaps != CSSValueSmallCaps)
return emptyString();
// Font stretch values can only be serialized in the font shorthand as keywords, since percentages are also valid font sizes.
// If a font stretch percentage can be expressed as a keyword, then do that.
std::optional<CSSValueID> stretchKeyword;
if (auto stretchBase = getPropertyCSSValue(CSSPropertyFontStretch)) {
auto stretch = downcast<CSSPrimitiveValue>(stretchBase.get());
if (!stretch->isPercentage())
stretchKeyword = stretch->valueID();
else {
stretchKeyword = fontStretchKeyword(stretch->doubleValue());
if (!stretchKeyword)
return emptyString();
}
}
StringBuilder result;
auto appendOptionalValue = [this, &result](CSSPropertyID property) {
int foundPropertyIndex = findPropertyIndex(property);
if (foundPropertyIndex == -1)
return; // All longhands must have at least implicit values if "font" is specified.
// Omit default normal values.
if (propertyAsValueID(property) == CSSValueNormal)
return;
auto prefix = property == CSSPropertyLineHeight ? " / " : " ";
result.append(result.isEmpty() ? "" : prefix, propertyAt(foundPropertyIndex).value()->cssText());
};
appendOptionalValue(CSSPropertyFontStyle);
appendOptionalValue(CSSPropertyFontVariantCaps);
appendOptionalValue(CSSPropertyFontWeight);
if (stretchKeyword && *stretchKeyword != CSSValueNormal)
result.append(result.isEmpty() ? "" : " ", nameString(*stretchKeyword));
result.append(result.isEmpty() ? "" : " ", size->cssText());
appendOptionalValue(CSSPropertyLineHeight);
result.append(result.isEmpty() ? "" : " ", family->cssText());
return result.toString();
}
String StyleProperties::offsetValue() const
{
ASSERT(offsetShorthand().length() == 5);
StringBuilder result;
auto offsetPositionIndex = findPropertyIndex(CSSPropertyOffsetPosition);
auto offsetPathIndex = findPropertyIndex(CSSPropertyOffsetPath);
// Either offset-position and offset-path must be specified.
if (offsetPositionIndex == -1 && offsetPathIndex == -1)
return String();
if (offsetPositionIndex != -1) {
auto offsetPosition = propertyAt(offsetPositionIndex);
if (!offsetPosition.isImplicit()) {
if (!offsetPosition.value())
return String();
result.append(offsetPosition.value()->cssText());
}
}
if (offsetPathIndex != -1) {
auto offsetPath = propertyAt(offsetPathIndex);
if (!offsetPath.isImplicit()) {
if (!offsetPath.value())
return String();
if (!result.isEmpty())
result.append(' ');
result.append(offsetPath.value()->cssText());
}
}
// At this point, result is not empty because either offset-position or offset-path
// must be present.
auto offsetDistanceIndex = findPropertyIndex(CSSPropertyOffsetDistance);
if (offsetDistanceIndex != -1) {
auto offsetDistance = propertyAt(offsetDistanceIndex);
if (!offsetDistance.isImplicit()) {
auto offsetDistanceValue = offsetDistance.value();
if (!offsetDistanceValue || !is<CSSPrimitiveValue>(offsetDistanceValue))
return String();
// Only include offset-distance if the distance is non-zero.
// isZero() returns std::nullopt if offsetDistanceValue is a calculated value, in which case
// we use value_or() to override to false.
if (!(downcast<CSSPrimitiveValue>(offsetDistanceValue)->isZero().value_or(false))) {
result.append(' ');
result.append(downcast<CSSPrimitiveValue>(offsetDistanceValue)->cssText());
}
}
}
auto offsetRotateIndex = findPropertyIndex(CSSPropertyOffsetRotate);
if (offsetRotateIndex != -1) {
auto offsetRotate = propertyAt(offsetRotateIndex);
if (!offsetRotate.isImplicit()) {
auto offsetRotateValue = offsetRotate.value();
if (!offsetRotateValue || !is<CSSOffsetRotateValue>(offsetRotateValue))
return String();
if (!(downcast<CSSOffsetRotateValue>(offsetRotateValue)->isInitialValue())) {
result.append(' ');
result.append(downcast<CSSOffsetRotateValue>(offsetRotateValue)->cssText());
}
}
}
auto offsetAnchorIndex = findPropertyIndex(CSSPropertyOffsetAnchor);
if (offsetAnchorIndex != -1) {
auto offsetAnchor = propertyAt(offsetAnchorIndex);
if (!offsetAnchor.isImplicit()) {
auto offsetAnchorValue = offsetAnchor.value();
if (!offsetAnchorValue)
return String();
if (!is<CSSPrimitiveValue>(offsetAnchorValue) || !downcast<CSSPrimitiveValue>(offsetAnchorValue)->isValueID()
|| downcast<CSSPrimitiveValue>(offsetAnchorValue)->valueID() != CSSValueAuto) {
result.append(" / ");
result.append(offsetAnchorValue->cssText());
}
}
}
return result.toString();
}
String StyleProperties::fontVariantValue(const StylePropertyShorthand& shorthand) const
{
ASSERT(shorthand.id() == CSSPropertyFontVariant);
StringBuilder result;
std::optional<CSSValueID> commonCSSWideKeyword;
bool isAllNormal = true;
auto ligaturesKeyword = propertyAsValueID(CSSPropertyFontVariantLigatures);
for (auto property : shorthand) {
int foundPropertyIndex = findPropertyIndex(property);
if (foundPropertyIndex == -1)
return emptyString(); // All longhands must have at least implicit values.
// Bypass getPropertyCSSValue which will return an empty string for system keywords.
auto value = propertyAt(foundPropertyIndex).value();
auto keyword = valueID(value);
// If all properties are set to the same special keyword, serialize as that.
// If some but not all properties are, the shorthand can't represent that, serialize as empty string.
if (isCSSWideKeyword(keyword)) {
if (commonCSSWideKeyword.value_or(keyword) != keyword)
return emptyString();
commonCSSWideKeyword = keyword;
continue;
}
if (commonCSSWideKeyword)
return emptyString();
// Skip normal for brevity.
if (keyword == CSSValueNormal)
continue;
isAllNormal = false;
// System keywords are not representable by font-variant.
if (CSSPropertyParserHelpers::isSystemFontShorthand(keyword))
return emptyString();
// font-variant cannot represent font-variant-ligatures: none along with other non-normal longhands.
if (ligaturesKeyword.value_or(CSSValueNormal) == CSSValueNone && property != CSSPropertyFontVariantLigatures)
return emptyString();
result.append(result.isEmpty() ? "" : " ", value->cssText());
}
if (commonCSSWideKeyword)
return nameString(*commonCSSWideKeyword);
if (result.isEmpty() && isAllNormal)
return nameString(CSSValueNormal);
return result.toString();
}
String StyleProperties::fontSynthesisValue() const
{
// font-synthesis: none | [ weight || style || small-caps ]
ASSERT(fontSynthesisShorthand().length() == 3);
auto weight = propertyAsValueID(CSSPropertyFontSynthesisWeight).value_or(CSSValueInvalid);
auto style = propertyAsValueID(CSSPropertyFontSynthesisStyle).value_or(CSSValueInvalid);
auto caps = propertyAsValueID(CSSPropertyFontSynthesisSmallCaps).value_or(CSSValueInvalid);
// Handle `none` or CSS wide-keywords that are common to all longhands.
if ((isCSSWideKeyword(weight) || weight == CSSValueNone) && weight == style && weight == caps)
return nameString(weight);
// If one of the longhands is a CSS-wide keyword but not all of them are, this is not a valid shorthand.
if (isCSSWideKeyword(weight) || isCSSWideKeyword(style) || isCSSWideKeyword(caps))
return emptyString();
StringBuilder result;
if (weight == CSSValueAuto)
result.append("weight"_s);
if (style == CSSValueAuto)
result.append(result.isEmpty() ? "" : " ", "style"_s);
if (caps == CSSValueAuto)
result.append(result.isEmpty() ? "" : " ", "small-caps"_s);
return result.toString();
}
String StyleProperties::get2Values(const StylePropertyShorthand& shorthand) const
{
// Assume the properties are in the usual order start, end.
ASSERT(shorthand.length() == 2);
int startValueIndex = findPropertyIndex(shorthand.properties()[0]);
int endValueIndex = findPropertyIndex(shorthand.properties()[1]);
if (startValueIndex == -1 || endValueIndex == -1)
return { };
auto start = propertyAt(startValueIndex);
auto end = propertyAt(endValueIndex);
// All 2 properties must be specified.
if (!start.value() || !end.value())
return { };
if (start.isInherited() && end.isInherited())
return nameString(CSSValueInherit);
if (start.value()->isInitialValue() || end.value()->isInitialValue()) {
if (start.value()->isInitialValue() && end.value()->isInitialValue() && !start.isImplicit())
return nameString(CSSValueInitial);
return { };
}
StringBuilder result;
result.append(start.value()->cssText());
if (!start.value()->equals(*end.value())) {
result.append(' ');
result.append(end.value()->cssText());
}
return result.toString();
}
String StyleProperties::get4Values(const StylePropertyShorthand& shorthand) const
{
// Assume the properties are in the usual order top, right, bottom, left.
ASSERT(shorthand.length() == 4);
int topValueIndex = findPropertyIndex(shorthand.properties()[0]);
int rightValueIndex = findPropertyIndex(shorthand.properties()[1]);
int bottomValueIndex = findPropertyIndex(shorthand.properties()[2]);
int leftValueIndex = findPropertyIndex(shorthand.properties()[3]);
if (topValueIndex == -1 || rightValueIndex == -1 || bottomValueIndex == -1 || leftValueIndex == -1)
return String();
PropertyReference top = propertyAt(topValueIndex);
PropertyReference right = propertyAt(rightValueIndex);
PropertyReference bottom = propertyAt(bottomValueIndex);
PropertyReference left = propertyAt(leftValueIndex);
// All 4 properties must be specified.
if (!top.value() || !right.value() || !bottom.value() || !left.value())
return String();
if (top.isInherited() && right.isInherited() && bottom.isInherited() && left.isInherited())
return nameString(CSSValueInherit);
if (top.value()->isInitialValue() || right.value()->isInitialValue() || bottom.value()->isInitialValue() || left.value()->isInitialValue()) {
if (top.value()->isInitialValue() && right.value()->isInitialValue() && bottom.value()->isInitialValue() && left.value()->isInitialValue() && !top.isImplicit()) {
// All components are "initial" and "top" is not implicit.
return nameString(CSSValueInitial);
}
return String();
}
bool showLeft = !right.value()->equals(*left.value());
bool showBottom = !top.value()->equals(*bottom.value()) || showLeft;
bool showRight = !top.value()->equals(*right.value()) || showBottom;
StringBuilder result;
result.append(top.value()->cssText());
if (showRight) {
result.append(' ');
result.append(right.value()->cssText());
}
if (showBottom) {
result.append(' ');
result.append(bottom.value()->cssText());
}
if (showLeft) {
result.append(' ');
result.append(left.value()->cssText());
}
return result.toString();
}
String StyleProperties::getLayeredShorthandValue(const StylePropertyShorthand& shorthand) const
{
StringBuilder result;
const unsigned size = shorthand.length();
Vector<RefPtr<CSSValue>> values(size);
size_t numLayers = 0;
for (unsigned i = 0; i < size; ++i) {
values[i] = getPropertyCSSValue(shorthand.properties()[i]);
if (!values[i]) {
// We don't have all longhand properties defined as required for the shorthand
// property and thus should not serialize to a shorthand value. See spec at
// https://www.w3.org/TR/cssom-1/#serialize-a-css-declaration-block
return String();
}
if (values[i]->isBaseValueList())
numLayers = std::max(downcast<CSSValueList>(*values[i]).length(), numLayers);
else
numLayers = std::max<size_t>(1U, numLayers);
}
String commonValue;
// Now stitch the properties together.
// Implicit initial values are flagged as such and can safely be omitted.
for (size_t i = 0; i < numLayers; i++) {
StringBuilder layerResult;
bool useRepeatXShorthand = false;
bool useRepeatYShorthand = false;
bool useSingleWordShorthand = false;
bool foundPositionYCSSProperty = false;
for (unsigned j = 0; j < size; j++) {
auto property = shorthand.properties()[j];
auto value = values[j];
if (value) {
if (value->isBaseValueList())
value = downcast<CSSValueList>(*value).item(i);
else {
// Color only belongs in the last layer.
if (property == CSSPropertyBackgroundColor) {
if (i != numLayers - 1)
value = nullptr;
} else if (i) // Other singletons only belong in the first layer.
value = nullptr;
}
}
auto canOmitValue = [&]() {
if (shorthand.id() == CSSPropertyMask) {
if (property == CSSPropertyMaskClip) {
// If the mask-clip value is the same as the value for mask-origin (the previous value),
// then we can skip serializing it, as one value sets both properties.
ASSERT(j > 0);
ASSERT(shorthand.properties()[j - 1] == CSSPropertyMaskOrigin);
auto originValue = values[j - 1];
if (is<CSSValueList>(*originValue))
originValue = downcast<CSSValueList>(*originValue).item(i);
if (!is<CSSPrimitiveValue>(*value) || (originValue && !is<CSSPrimitiveValue>(*originValue)))
return false;
auto maskId = downcast<CSSPrimitiveValue>(*value).valueID();
auto originId = originValue ? downcast<CSSPrimitiveValue>(*originValue).valueID() : CSSValueInitial;
return maskId == originId && (!isCSSWideValueKeyword(StringView { nameLiteral(maskId) }) || value->isImplicitInitialValue());
}
if (property == CSSPropertyMaskOrigin) {
// We can skip serializing mask-origin if it's the initial value, but only if we're also going to skip serializing
// the mask-clip as well (otherwise the single value for mask-clip would be assumed to be setting the value for both).
ASSERT(j + 1 < size);
ASSERT(shorthand.properties()[j + 1] == CSSPropertyMaskClip);
auto clipValue = values[j + 1];
if (is<CSSValueList>(*clipValue))
clipValue = downcast<CSSValueList>(*clipValue).item(i);
return value->isImplicitInitialValue() && (!clipValue || clipValue->isImplicitInitialValue());
}
}
return value->isImplicitInitialValue();
};
String valueText;
if (!value && shorthand.id() == CSSPropertyMask)
value = CSSValuePool::singleton().createImplicitInitialValue();
if (value && !canOmitValue()) {
if (!layerResult.isEmpty())
layerResult.append(' ');
if (property == CSSPropertyBackgroundSize || property == CSSPropertyMaskSize) {
if (!foundPositionYCSSProperty)
continue;
layerResult.append("/ ");
}
if (useRepeatXShorthand) {
useRepeatXShorthand = false;
layerResult.append(nameLiteral(CSSValueRepeatX));
} else if (useRepeatYShorthand) {
useRepeatYShorthand = false;
layerResult.append(nameLiteral(CSSValueRepeatY));
} else if (shorthand.id() == CSSPropertyMask && property == CSSPropertyMaskOrigin && value->isImplicitInitialValue()) {
// If we're about to write the value for mask-origin, but it's an implicit initial value that's just a placeholder
// for a 'real' mask-clip value, then write the actual value not 'initial'.
layerResult.append(nameLiteral(CSSValueBorderBox));
} else {
if (useSingleWordShorthand)
useSingleWordShorthand = false;
valueText = value->cssText();
layerResult.append(valueText);
}
if (property == CSSPropertyBackgroundPositionY || property == CSSPropertyWebkitMaskPositionY)
foundPositionYCSSProperty = true;
}
if (commonValue.isNull())
commonValue = valueText;
else if (commonValue != valueText)
commonValue = emptyString(); // Could use value here other than a CSS-wide value keyword or the null string.
}
if (shorthand.id() == CSSPropertyMask && layerResult.isEmpty())
layerResult.append(nameLiteral(CSSValueNone));
if (!layerResult.isEmpty())
result.append(result.isEmpty() ? "" : ", ", layerResult.toString());
}
if (isCSSWideValueKeyword(commonValue))
return commonValue;
return result.isEmpty() ? String() : result.toString();
}
String StyleProperties::getGridTemplateValue() const
{
ASSERT(gridTemplateShorthand().length() == 3);
StringBuilder result;
int areasIndex = findPropertyIndex(CSSPropertyGridTemplateAreas);
if (areasIndex == -1)
return String();
auto rows = getPropertyCSSValue(CSSPropertyGridTemplateRows);
if (!rows)
return String();
auto columns = getPropertyCSSValue(CSSPropertyGridTemplateColumns);
if (!columns)
return String();
auto areas = propertyAt(areasIndex);
if (!is<CSSGridTemplateAreasValue>(areas.value())) {
auto rowsText = rows->cssText();
result.append(rowsText);
auto columnsText = columns->cssText();
// If the values are identical, and either a css wide keyword
// or 'none', then we can just output it once.
if (columnsText != rowsText || (!isCSSWideValueKeyword(columnsText) && !isValueID(columns, CSSValueNone)))
result.append(" / ", columnsText);
return result.toString();
}
// We only want to try serializing the interleaved areas/templates
// format if it was set from this shorthand, since that automatically
// excludes values that can't be represented in this format (subgrid,
// and the repeat() function).
if (!areas.toCSSProperty().isSetFromShorthand())
return String();
ASSERT(is<CSSValueList>(rows));
ASSERT(is<CSSGridTemplateAreasValue>(areas.value()));
auto& areasValue = downcast<CSSGridTemplateAreasValue>(*areas.value());
bool first = true;
unsigned row = 0;
for (auto& currentValue : downcast<CSSValueList>(*rows)) {
if (!first)
result.append(' ');
first = false;
if (is<CSSGridLineNamesValue>(currentValue))
result.append(currentValue->cssText());
else {
result.append('"', areasValue.stringForRow(row), '"');
if (!isValueID(currentValue, CSSValueAuto))
result.append(' ', currentValue->cssText());
row++;
}
}
if (!isValueID(columns, CSSValueNone))
result.append(" / ", columns->cssText());
return result.toString();
}
static bool gridAutoFlowContains(const RefPtr<CSSValue>& autoFlow, CSSValueID id)
{
if (is<CSSValueList>(autoFlow)) {
for (auto& currentValue : downcast<CSSValueList>(*autoFlow)) {
if (isValueID(currentValue, id))
return true;
}
return false;
}
return isValueID(autoFlow, id);
}
String StyleProperties::getGridValue() const
{
ASSERT(gridShorthand().length() == 6);
auto autoColumns = getPropertyCSSValue(CSSPropertyGridAutoColumns);
auto autoRows = getPropertyCSSValue(CSSPropertyGridAutoRows);
auto autoFlow = getPropertyCSSValue(CSSPropertyGridAutoFlow);
if (!autoColumns || !autoRows || !autoFlow)
return String();
if (isValueIDIncludingList(autoColumns, CSSValueAuto) && isValueIDIncludingList(autoRows, CSSValueAuto) && isValueIDIncludingList(autoFlow, CSSValueRow))
return getGridTemplateValue();
if (!isValueID(getPropertyCSSValue(CSSPropertyGridTemplateAreas), CSSValueNone))
return String();
auto rows = getPropertyCSSValue(CSSPropertyGridTemplateRows);
auto columns = getPropertyCSSValue(CSSPropertyGridTemplateColumns);
if (!rows || !columns)
return String();
StringBuilder result;
if (gridAutoFlowContains(autoFlow, CSSValueColumn)) {
if (!isValueIDIncludingList(autoRows, CSSValueAuto) || !isValueIDIncludingList(columns, CSSValueNone))
return String();
result.append(rows->cssText());
result.append(" / auto-flow");
if (gridAutoFlowContains(autoFlow, CSSValueDense))
result.append(" dense");
if (!isValueIDIncludingList(autoColumns, CSSValueAuto))
result.append(' ', autoColumns->cssText());
return result.toString();
}
if (!gridAutoFlowContains(autoFlow, CSSValueRow) && !gridAutoFlowContains(autoFlow, CSSValueDense))
return String();
if (!isValueIDIncludingList(autoColumns, CSSValueAuto) || !isValueIDIncludingList(rows, CSSValueNone))
return String();
result.append("auto-flow");
if (gridAutoFlowContains(autoFlow, CSSValueDense))
result.append(" dense");
if (!isValueIDIncludingList(autoRows, CSSValueAuto)) {
result.append(" ");
result.append(autoRows->cssText());
}
result.append(" / ");
result.append(columns->cssText());