forked from SerenityOS/serenity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StyleComputer.cpp
2401 lines (2093 loc) Β· 113 KB
/
StyleComputer.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) 2018-2023, Andreas Kling <[email protected]>
* Copyright (c) 2021, the SerenityOS developers.
* Copyright (c) 2021-2023, Sam Atkins <[email protected]>
* Copyright (c) 2024, Matthew Olsson <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/BinarySearch.h>
#include <AK/Debug.h>
#include <AK/Error.h>
#include <AK/Find.h>
#include <AK/Function.h>
#include <AK/HashMap.h>
#include <AK/Math.h>
#include <AK/QuickSort.h>
#include <AK/TemporaryChange.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/FontStyleMapping.h>
#include <LibGfx/Font/OpenType/Font.h>
#include <LibGfx/Font/ScaledFont.h>
#include <LibGfx/Font/VectorFont.h>
#include <LibGfx/Font/WOFF/Font.h>
#include <LibGfx/Font/WOFF2/Font.h>
#include <LibWeb/Animations/AnimationEffect.h>
#include <LibWeb/Animations/DocumentTimeline.h>
#include <LibWeb/Animations/TimingFunction.h>
#include <LibWeb/CSS/AnimationEvent.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSFontFaceRule.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/SelectorEngine.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleSheet.h>
#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
#include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
#include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
#include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
#include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
#include <LibWeb/CSS/StyleValues/RectStyleValue.h>
#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/StringStyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
#include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/HTMLBRElement.h>
#include <LibWeb/HTML/HTMLHtmlElement.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Painting/PaintableBox.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/ReferrerPolicy/AbstractOperations.h>
#include <math.h>
#include <stdio.h>
namespace AK {
// traits for FontFaceKey
template<>
struct Traits<Web::CSS::FontFaceKey> : public DefaultTraits<Web::CSS::FontFaceKey> {
static unsigned hash(Web::CSS::FontFaceKey const& key) { return pair_int_hash(key.family_name.hash(), pair_int_hash(key.weight, key.slope)); }
};
}
namespace Web::CSS {
static DOM::Element const* element_to_inherit_style_from(DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>);
static NonnullRefPtr<StyleValue const> get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>);
StyleComputer::StyleComputer(DOM::Document& document)
: m_document(document)
, m_default_font_metrics(16, Gfx::FontDatabase::default_font().pixel_metrics())
, m_root_element_font_metrics(m_default_font_metrics)
{
}
StyleComputer::~StyleComputer() = default;
class StyleComputer::FontLoader : public ResourceClient {
public:
explicit FontLoader(StyleComputer& style_computer, FlyString family_name, Vector<Gfx::UnicodeRange> unicode_ranges, Vector<URL> urls)
: m_style_computer(style_computer)
, m_family_name(move(family_name))
, m_unicode_ranges(move(unicode_ranges))
, m_urls(move(urls))
{
}
virtual ~FontLoader() override { }
Vector<Gfx::UnicodeRange> const& unicode_ranges() const { return m_unicode_ranges; }
virtual void resource_did_load() override
{
auto result = try_load_font();
if (result.is_error())
return start_loading_next_url();
m_vector_font = result.release_value();
m_style_computer.did_load_font(m_family_name);
}
virtual void resource_did_fail() override
{
}
RefPtr<Gfx::Font> font_with_point_size(float point_size)
{
if (!m_vector_font) {
start_loading_next_url();
return nullptr;
}
return m_vector_font->scaled_font(point_size);
}
private:
void start_loading_next_url()
{
if (resource() && resource()->is_pending())
return;
if (m_urls.is_empty())
return;
LoadRequest request;
request.set_url(m_urls.take_first());
// HACK: We're crudely computing the referer value and shoving it into the
// request until fetch infrastructure is used here.
auto referrer_url = ReferrerPolicy::strip_url_for_use_as_referrer(m_style_computer.document().url());
if (referrer_url.has_value() && !request.headers().contains("Referer"))
request.set_header("Referer", referrer_url->serialize());
set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
}
ErrorOr<NonnullRefPtr<Gfx::VectorFont>> try_load_font()
{
// FIXME: This could maybe use the format() provided in @font-face as well, since often the mime type is just application/octet-stream and we have to try every format
auto mime_type = resource()->mime_type();
if (mime_type == "font/ttf"sv || mime_type == "application/x-font-ttf"sv)
return TRY(OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
if (mime_type == "font/woff"sv || mime_type == "application/font-woff"sv)
return TRY(WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
if (mime_type == "font/woff2"sv || mime_type == "application/font-woff2"sv) {
auto woff2 = WOFF2::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
if (woff2.is_error()) {
dbgln("WOFF2 error: {}", woff2.error());
return woff2.release_error();
}
return woff2.release_value();
}
auto ttf = OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
if (!ttf.is_error())
return ttf.release_value();
auto woff = WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
if (!woff.is_error())
return woff.release_value();
auto woff2 = WOFF2::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
if (!woff2.is_error())
return woff2.release_value();
return woff2.release_error();
}
StyleComputer& m_style_computer;
FlyString m_family_name;
Vector<Gfx::UnicodeRange> m_unicode_ranges;
RefPtr<Gfx::VectorFont> m_vector_font;
Vector<URL> m_urls;
};
struct StyleComputer::MatchingFontCandidate {
FontFaceKey key;
Variant<FontLoaderList*, Gfx::Typeface const*> loader_or_typeface;
[[nodiscard]] RefPtr<Gfx::FontCascadeList const> font_with_point_size(float point_size) const
{
RefPtr<Gfx::FontCascadeList> font_list = Gfx::FontCascadeList::create();
if (auto* loader_list = loader_or_typeface.get_pointer<FontLoaderList*>(); loader_list) {
for (auto const& loader : **loader_list) {
if (auto font = loader->font_with_point_size(point_size); font)
font_list->add(*font, loader->unicode_ranges());
}
return font_list;
}
if (auto font = loader_or_typeface.get<Gfx::Typeface const*>()->get_font(point_size))
font_list->add(*font);
return font_list;
}
};
static CSSStyleSheet& default_stylesheet(DOM::Document const& document)
{
static JS::Handle<CSSStyleSheet> sheet;
if (!sheet.cell()) {
extern StringView default_stylesheet_source;
sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), default_stylesheet_source));
}
return *sheet;
}
static CSSStyleSheet& quirks_mode_stylesheet(DOM::Document const& document)
{
static JS::Handle<CSSStyleSheet> sheet;
if (!sheet.cell()) {
extern StringView quirks_mode_stylesheet_source;
sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), quirks_mode_stylesheet_source));
}
return *sheet;
}
static CSSStyleSheet& mathml_stylesheet(DOM::Document const& document)
{
static JS::Handle<CSSStyleSheet> sheet;
if (!sheet.cell()) {
extern StringView mathml_stylesheet_source;
sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), mathml_stylesheet_source));
}
return *sheet;
}
static CSSStyleSheet& svg_stylesheet(DOM::Document const& document)
{
static JS::Handle<CSSStyleSheet> sheet;
if (!sheet.cell()) {
extern StringView svg_stylesheet_source;
sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), svg_stylesheet_source));
}
return *sheet;
}
template<typename Callback>
void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const
{
if (cascade_origin == CascadeOrigin::UserAgent) {
callback(default_stylesheet(document()));
if (document().in_quirks_mode())
callback(quirks_mode_stylesheet(document()));
callback(mathml_stylesheet(document()));
callback(svg_stylesheet(document()));
}
if (cascade_origin == CascadeOrigin::User) {
if (m_user_style_sheet)
callback(*m_user_style_sheet);
}
if (cascade_origin == CascadeOrigin::Author) {
for (auto const& sheet : document().style_sheets().sheets())
callback(*sheet);
}
}
StyleComputer::RuleCache const& StyleComputer::rule_cache_for_cascade_origin(CascadeOrigin cascade_origin) const
{
switch (cascade_origin) {
case CascadeOrigin::Author:
return *m_author_rule_cache;
case CascadeOrigin::User:
return *m_user_rule_cache;
case CascadeOrigin::UserAgent:
return *m_user_agent_rule_cache;
default:
TODO();
}
}
[[nodiscard]] static bool filter_namespace_rule(DOM::Element const& element, MatchingRule const& rule)
{
// FIXME: Filter out non-default namespace using prefixes
auto namespace_uri = rule.sheet->default_namespace();
if (namespace_uri.has_value() && namespace_uri.value() != element.namespace_uri()) {
return false;
}
return true;
}
Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin cascade_origin, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
{
auto const& rule_cache = rule_cache_for_cascade_origin(cascade_origin);
Vector<MatchingRule> rules_to_run;
auto add_rules_to_run = [&](Vector<MatchingRule> const& rules) {
rules_to_run.grow_capacity(rules_to_run.size() + rules.size());
if (pseudo_element.has_value()) {
for (auto const& rule : rules) {
if (rule.contains_pseudo_element && filter_namespace_rule(element, rule))
rules_to_run.append(rule);
}
} else {
for (auto const& rule : rules) {
if (filter_namespace_rule(element, rule))
rules_to_run.append(rule);
}
}
};
for (auto const& class_name : element.class_names()) {
if (auto it = rule_cache.rules_by_class.find(class_name); it != rule_cache.rules_by_class.end())
add_rules_to_run(it->value);
}
if (auto id = element.id(); id.has_value()) {
if (auto it = rule_cache.rules_by_id.find(id.value()); it != rule_cache.rules_by_id.end())
add_rules_to_run(it->value);
}
if (auto it = rule_cache.rules_by_tag_name.find(element.local_name()); it != rule_cache.rules_by_tag_name.end())
add_rules_to_run(it->value);
add_rules_to_run(rule_cache.other_rules);
Vector<MatchingRule> matching_rules;
matching_rules.ensure_capacity(rules_to_run.size());
for (auto const& rule_to_run : rules_to_run) {
auto const& selector = rule_to_run.rule->selectors()[rule_to_run.selector_index];
if (SelectorEngine::matches(selector, *rule_to_run.sheet, element, pseudo_element))
matching_rules.append(rule_to_run);
}
return matching_rules;
}
static void sort_matching_rules(Vector<MatchingRule>& matching_rules)
{
quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) {
auto const& a_selector = a.rule->selectors()[a.selector_index];
auto const& b_selector = b.rule->selectors()[b.selector_index];
auto a_specificity = a_selector->specificity();
auto b_specificity = b_selector->specificity();
if (a_selector->specificity() == b_selector->specificity()) {
if (a.style_sheet_index == b.style_sheet_index)
return a.rule_index < b.rule_index;
return a.style_sheet_index < b.style_sheet_index;
}
return a_specificity < b_specificity;
});
}
void StyleComputer::for_each_property_expanding_shorthands(PropertyID property_id, StyleValue const& value, Function<void(PropertyID, StyleValue const&)> const& set_longhand_property)
{
auto map_logical_property_to_real_property = [](PropertyID property_id) -> Optional<PropertyID> {
// FIXME: Honor writing-mode, direction and text-orientation.
switch (property_id) {
case PropertyID::MarginBlockStart:
return PropertyID::MarginTop;
case PropertyID::MarginBlockEnd:
return PropertyID::MarginBottom;
case PropertyID::MarginInlineStart:
return PropertyID::MarginLeft;
case PropertyID::MarginInlineEnd:
return PropertyID::MarginRight;
case PropertyID::PaddingBlockStart:
return PropertyID::PaddingTop;
case PropertyID::PaddingBlockEnd:
return PropertyID::PaddingBottom;
case PropertyID::PaddingInlineStart:
return PropertyID::PaddingLeft;
case PropertyID::PaddingInlineEnd:
return PropertyID::PaddingRight;
case PropertyID::InsetBlockStart:
return PropertyID::Top;
case PropertyID::InsetBlockEnd:
return PropertyID::Bottom;
case PropertyID::InsetInlineStart:
return PropertyID::Left;
case PropertyID::InsetInlineEnd:
return PropertyID::Right;
case PropertyID::WebkitAppearance:
return PropertyID::Appearance;
default:
return {};
}
};
struct StartAndEndPropertyIDs {
PropertyID start;
PropertyID end;
};
auto map_logical_property_to_real_properties = [](PropertyID property_id) -> Optional<StartAndEndPropertyIDs> {
// FIXME: Honor writing-mode, direction and text-orientation.
switch (property_id) {
case PropertyID::MarginBlock:
return StartAndEndPropertyIDs { PropertyID::MarginTop, PropertyID::MarginBottom };
case PropertyID::MarginInline:
return StartAndEndPropertyIDs { PropertyID::MarginLeft, PropertyID::MarginRight };
case PropertyID::PaddingBlock:
return StartAndEndPropertyIDs { PropertyID::PaddingTop, PropertyID::PaddingBottom };
case PropertyID::PaddingInline:
return StartAndEndPropertyIDs { PropertyID::PaddingLeft, PropertyID::PaddingRight };
case PropertyID::InsetBlock:
return StartAndEndPropertyIDs { PropertyID::Top, PropertyID::Bottom };
case PropertyID::InsetInline:
return StartAndEndPropertyIDs { PropertyID::Left, PropertyID::Right };
default:
return {};
}
};
if (auto real_property_id = map_logical_property_to_real_property(property_id); real_property_id.has_value()) {
for_each_property_expanding_shorthands(real_property_id.value(), value, set_longhand_property);
return;
}
if (auto real_property_ids = map_logical_property_to_real_properties(property_id); real_property_ids.has_value()) {
if (value.is_value_list() && value.as_value_list().size() == 2) {
auto const& start = value.as_value_list().values()[0];
auto const& end = value.as_value_list().values()[1];
for_each_property_expanding_shorthands(real_property_ids->start, start, set_longhand_property);
for_each_property_expanding_shorthands(real_property_ids->end, end, set_longhand_property);
return;
}
for_each_property_expanding_shorthands(real_property_ids->start, value, set_longhand_property);
for_each_property_expanding_shorthands(real_property_ids->end, value, set_longhand_property);
return;
}
if (value.is_shorthand()) {
auto& shorthand_value = value.as_shorthand();
auto& properties = shorthand_value.sub_properties();
auto& values = shorthand_value.values();
for (size_t i = 0; i < properties.size(); ++i)
for_each_property_expanding_shorthands(properties[i], values[i], set_longhand_property);
return;
}
auto assign_edge_values = [&](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
if (values.size() == 4) {
set_longhand_property(top_property, values[0]);
set_longhand_property(right_property, values[1]);
set_longhand_property(bottom_property, values[2]);
set_longhand_property(left_property, values[3]);
} else if (values.size() == 3) {
set_longhand_property(top_property, values[0]);
set_longhand_property(right_property, values[1]);
set_longhand_property(bottom_property, values[2]);
set_longhand_property(left_property, values[1]);
} else if (values.size() == 2) {
set_longhand_property(top_property, values[0]);
set_longhand_property(right_property, values[1]);
set_longhand_property(bottom_property, values[0]);
set_longhand_property(left_property, values[1]);
} else if (values.size() == 1) {
set_longhand_property(top_property, values[0]);
set_longhand_property(right_property, values[0]);
set_longhand_property(bottom_property, values[0]);
set_longhand_property(left_property, values[0]);
}
};
if (property_id == CSS::PropertyID::Border) {
for_each_property_expanding_shorthands(CSS::PropertyID::BorderTop, value, set_longhand_property);
for_each_property_expanding_shorthands(CSS::PropertyID::BorderRight, value, set_longhand_property);
for_each_property_expanding_shorthands(CSS::PropertyID::BorderBottom, value, set_longhand_property);
for_each_property_expanding_shorthands(CSS::PropertyID::BorderLeft, value, set_longhand_property);
// FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands
return;
}
if (property_id == CSS::PropertyID::BorderStyle) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::BorderTopStyle, value);
set_longhand_property(CSS::PropertyID::BorderRightStyle, value);
set_longhand_property(CSS::PropertyID::BorderBottomStyle, value);
set_longhand_property(CSS::PropertyID::BorderLeftStyle, value);
return;
}
if (property_id == CSS::PropertyID::BorderWidth) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::BorderTopWidth, value);
set_longhand_property(CSS::PropertyID::BorderRightWidth, value);
set_longhand_property(CSS::PropertyID::BorderBottomWidth, value);
set_longhand_property(CSS::PropertyID::BorderLeftWidth, value);
return;
}
if (property_id == CSS::PropertyID::BorderColor) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::BorderTopColor, value);
set_longhand_property(CSS::PropertyID::BorderRightColor, value);
set_longhand_property(CSS::PropertyID::BorderBottomColor, value);
set_longhand_property(CSS::PropertyID::BorderLeftColor, value);
return;
}
if (property_id == CSS::PropertyID::BackgroundPosition) {
if (value.is_position()) {
auto const& position = value.as_position();
set_longhand_property(CSS::PropertyID::BackgroundPositionX, position.edge_x());
set_longhand_property(CSS::PropertyID::BackgroundPositionY, position.edge_y());
} else if (value.is_value_list()) {
// Expand background-position layer list into separate lists for x and y positions:
auto const& values_list = value.as_value_list();
StyleValueVector x_positions {};
StyleValueVector y_positions {};
x_positions.ensure_capacity(values_list.size());
y_positions.ensure_capacity(values_list.size());
for (auto& layer : values_list.values()) {
if (layer->is_position()) {
auto const& position = layer->as_position();
x_positions.unchecked_append(position.edge_x());
y_positions.unchecked_append(position.edge_y());
} else {
x_positions.unchecked_append(layer);
y_positions.unchecked_append(layer);
}
}
set_longhand_property(CSS::PropertyID::BackgroundPositionX, StyleValueList::create(move(x_positions), values_list.separator()));
set_longhand_property(CSS::PropertyID::BackgroundPositionY, StyleValueList::create(move(y_positions), values_list.separator()));
} else {
set_longhand_property(CSS::PropertyID::BackgroundPositionX, value);
set_longhand_property(CSS::PropertyID::BackgroundPositionY, value);
}
return;
}
if (property_id == CSS::PropertyID::Inset) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::Top, PropertyID::Right, PropertyID::Bottom, PropertyID::Left, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::Top, value);
set_longhand_property(CSS::PropertyID::Right, value);
set_longhand_property(CSS::PropertyID::Bottom, value);
set_longhand_property(CSS::PropertyID::Left, value);
return;
}
if (property_id == CSS::PropertyID::Margin) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::MarginTop, value);
set_longhand_property(CSS::PropertyID::MarginRight, value);
set_longhand_property(CSS::PropertyID::MarginBottom, value);
set_longhand_property(CSS::PropertyID::MarginLeft, value);
return;
}
if (property_id == CSS::PropertyID::Padding) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values());
return;
}
set_longhand_property(CSS::PropertyID::PaddingTop, value);
set_longhand_property(CSS::PropertyID::PaddingRight, value);
set_longhand_property(CSS::PropertyID::PaddingBottom, value);
set_longhand_property(CSS::PropertyID::PaddingLeft, value);
return;
}
if (property_id == CSS::PropertyID::Gap || property_id == CSS::PropertyID::GridGap) {
if (value.is_value_list()) {
auto const& values_list = value.as_value_list();
set_longhand_property(CSS::PropertyID::RowGap, values_list.values()[0]);
set_longhand_property(CSS::PropertyID::ColumnGap, values_list.values()[1]);
return;
}
set_longhand_property(CSS::PropertyID::RowGap, value);
set_longhand_property(CSS::PropertyID::ColumnGap, value);
return;
}
if (property_id == CSS::PropertyID::RowGap || property_id == CSS::PropertyID::GridRowGap) {
set_longhand_property(CSS::PropertyID::RowGap, value);
return;
}
if (property_id == CSS::PropertyID::ColumnGap || property_id == CSS::PropertyID::GridColumnGap) {
set_longhand_property(CSS::PropertyID::ColumnGap, value);
return;
}
if (property_id == CSS::PropertyID::MaxInlineSize || property_id == CSS::PropertyID::MinInlineSize) {
// FIXME: Use writing-mode to determine if we should set width or height.
bool is_horizontal = true;
if (is_horizontal) {
if (property_id == CSS::PropertyID::MaxInlineSize) {
set_longhand_property(CSS::PropertyID::MaxWidth, value);
} else {
set_longhand_property(CSS::PropertyID::MinWidth, value);
}
} else {
if (property_id == CSS::PropertyID::MaxInlineSize) {
set_longhand_property(CSS::PropertyID::MaxHeight, value);
} else {
set_longhand_property(CSS::PropertyID::MinHeight, value);
}
}
return;
}
if (property_is_shorthand(property_id)) {
// ShorthandStyleValue was handled already.
// That means if we got here, that `value` must be a CSS-wide keyword, which we should apply to our longhand properties.
// We don't directly call `set_longhand_property()` because the longhands might have longhands of their own.
// (eg `grid` -> `grid-template` -> `grid-template-areas` & `grid-template-rows` & `grid-template-columns`)
VERIFY(value.is_css_wide_keyword());
for (auto longhand : longhands_for_shorthand(property_id))
for_each_property_expanding_shorthands(longhand, value, set_longhand_property);
return;
}
set_longhand_property(property_id, value);
}
void StyleComputer::set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert)
{
for_each_property_expanding_shorthands(property_id, value, [&](PropertyID shorthand_id, StyleValue const& shorthand_value) {
if (shorthand_value.is_revert()) {
auto& property_in_previous_cascade_origin = properties_for_revert[to_underlying(shorthand_id)];
if (property_in_previous_cascade_origin.has_value())
style.set_property(shorthand_id, property_in_previous_cascade_origin->style, property_in_previous_cascade_origin->declaration);
} else {
style.set_property(shorthand_id, shorthand_value, declaration);
}
});
}
void StyleComputer::set_all_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, StyleProperties& style, StyleValue const& value, DOM::Document& document, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert) const
{
for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
auto property_id = (CSS::PropertyID)i;
if (value.is_revert()) {
style.m_property_values[to_underlying(property_id)] = properties_for_revert[to_underlying(property_id)];
continue;
}
if (value.is_unset()) {
if (is_inherited_property(property_id))
style.m_property_values[to_underlying(property_id)] = { { get_inherit_value(document.realm(), property_id, &element, pseudo_element), nullptr } };
else
style.m_property_values[to_underlying(property_id)] = { { property_initial_value(document.realm(), property_id), nullptr } };
continue;
}
NonnullRefPtr<StyleValue> property_value = value;
if (property_value->is_unresolved())
property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document }, element, pseudo_element, property_id, property_value->as_unresolved());
if (!property_value->is_unresolved())
set_property_expanding_shorthands(style, property_id, property_value, declaration, properties_for_revert);
set_property_expanding_shorthands(style, property_id, value, declaration, properties_for_revert);
}
}
void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, Important important) const
{
auto properties_for_revert = style.properties();
for (auto const& match : matching_rules) {
for (auto const& property : verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).properties()) {
if (important != property.important)
continue;
if (property.property_id == CSS::PropertyID::All) {
set_all_properties(element, pseudo_element, style, property.value, m_document, &match.rule->declaration(), properties_for_revert);
continue;
}
auto property_value = property.value;
if (property.value->is_unresolved())
property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
if (!property_value->is_unresolved())
set_property_expanding_shorthands(style, property.property_id, property_value, &match.rule->declaration(), properties_for_revert);
}
}
if (cascade_origin == CascadeOrigin::Author && !pseudo_element.has_value()) {
if (auto const* inline_style = verify_cast<ElementInlineCSSStyleDeclaration>(element.inline_style())) {
for (auto const& property : inline_style->properties()) {
if (important != property.important)
continue;
if (property.property_id == CSS::PropertyID::All) {
set_all_properties(element, pseudo_element, style, property.value, m_document, inline_style, properties_for_revert);
continue;
}
auto property_value = property.value;
if (property.value->is_unresolved())
property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
if (!property_value->is_unresolved())
set_property_expanding_shorthands(style, property.property_id, property_value, inline_style, properties_for_revert);
}
}
}
}
static ErrorOr<void> cascade_custom_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, Vector<MatchingRule> const& matching_rules)
{
size_t needed_capacity = 0;
for (auto const& matching_rule : matching_rules)
needed_capacity += verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties().size();
if (!pseudo_element.has_value()) {
if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style()))
needed_capacity += inline_style->custom_properties().size();
}
HashMap<FlyString, StyleProperty> custom_properties;
TRY(custom_properties.try_ensure_capacity(needed_capacity));
for (auto const& matching_rule : matching_rules) {
for (auto const& it : verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties())
custom_properties.set(it.key, it.value);
}
if (!pseudo_element.has_value()) {
if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style())) {
for (auto const& it : inline_style->custom_properties())
custom_properties.set(it.key, it.value);
}
}
element.set_custom_properties(pseudo_element, move(custom_properties));
return {};
}
template<typename T>
static T interpolate_raw(T from, T to, float delta)
{
if constexpr (IsSame<T, double>) {
return from + (to - from) * static_cast<double>(delta);
} else {
return static_cast<RemoveCVReference<T>>(from + (to - from) * delta);
}
}
static ErrorOr<NonnullRefPtr<StyleValue const>> interpolate_transform(DOM::Element& element, StyleValue const& from, StyleValue const& to, float delta)
{
// Note that the spec uses column-major notation, so all the matrix indexing is reversed.
static constexpr auto make_transformation = [](TransformationStyleValue const& transformation) -> ErrorOr<Transformation> {
Vector<TransformValue> values;
for (auto const& value : transformation.values()) {
switch (value->type()) {
case StyleValue::Type::Angle:
values.append(AngleOrCalculated { value->as_angle().angle() });
break;
case StyleValue::Type::Calculated:
values.append(AngleOrCalculated { value->as_calculated() });
break;
case StyleValue::Type::Length:
values.append(LengthPercentage { value->as_length().length() });
break;
case StyleValue::Type::Percentage:
values.append(LengthPercentage { value->as_percentage().percentage() });
break;
case StyleValue::Type::Number:
values.append(NumberPercentage { Number(Number::Type::Number, value->as_number().number()) });
break;
default:
return Error::from_string_literal("Transform contains unsupported style value");
}
}
return Transformation { transformation.transform_function(), move(values) };
};
static constexpr auto transformation_style_value_to_matrix = [](DOM::Element& element, TransformationStyleValue const& value) -> ErrorOr<FloatMatrix4x4> {
auto transformation = TRY(make_transformation(value.as_transformation()));
Optional<Painting::PaintableBox const&> paintable_box;
if (auto layout_node = element.layout_node()) {
if (auto paintable = layout_node->paintable(); paintable && is<Painting::PaintableBox>(paintable))
paintable_box = *static_cast<Painting::PaintableBox*>(paintable);
}
return transformation.to_matrix(paintable_box);
};
static constexpr auto style_value_to_matrix = [](DOM::Element& element, StyleValue const& value) -> ErrorOr<FloatMatrix4x4> {
if (value.to_identifier() == ValueID::None)
return FloatMatrix4x4::identity();
if (value.is_transformation())
return transformation_style_value_to_matrix(element, value.as_transformation());
VERIFY(value.is_value_list());
auto matrix = FloatMatrix4x4::identity();
for (auto const& value_element : value.as_value_list().values()) {
if (value_element->is_transformation())
matrix = matrix * TRY(transformation_style_value_to_matrix(element, value_element->as_transformation()));
}
return matrix;
};
struct DecomposedValues {
FloatVector3 translation;
FloatVector3 scale;
FloatVector3 skew;
FloatVector4 rotation;
FloatVector4 perspective;
};
// https://drafts.csswg.org/css-transforms-2/#decomposing-a-3d-matrix
static constexpr auto decompose = [](FloatMatrix4x4 matrix) -> ErrorOr<DecomposedValues> {
// https://drafts.csswg.org/css-transforms-1/#supporting-functions
static constexpr auto combine = [](auto a, auto b, float ascl, float bscl) {
return FloatVector3 {
ascl * a[0] + bscl * b[0],
ascl * a[1] + bscl * b[1],
ascl * a[2] + bscl * b[2],
};
};
// Normalize the matrix.
if (matrix(3, 3) == 0.f)
return Error::from_string_literal("Cannot interpolate non-invertible matrix");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
matrix(i, j) /= matrix(3, 3);
// perspectiveMatrix is used to solve for perspective, but it also provides
// an easy way to test for singularity of the upper 3x3 component.
auto perspective_matrix = matrix;
for (int i = 0; i < 3; i++)
perspective_matrix(3, i) = 0.f;
perspective_matrix(3, 3) = 1.f;
if (!perspective_matrix.is_invertible())
return Error::from_string_literal("Cannot interpolate non-invertible matrix");
DecomposedValues values;
// First, isolate perspective.
if (matrix(3, 0) != 0.f || matrix(3, 1) != 0.f || matrix(3, 2) != 0.f) {
// rightHandSide is the right hand side of the equation.
// Note: It is the bottom side in a row-major matrix
FloatVector4 bottom_side = {
matrix(3, 0),
matrix(3, 1),
matrix(3, 2),
matrix(3, 3),
};
// Solve the equation by inverting perspectiveMatrix and multiplying
// rightHandSide by the inverse.
auto inverse_perspective_matrix = perspective_matrix.inverse();
auto transposed_inverse_perspective_matrix = inverse_perspective_matrix.transpose();
values.perspective = transposed_inverse_perspective_matrix * bottom_side;
} else {
// No perspective.
values.perspective = { 0.0, 0.0, 0.0, 1.0 };
}
// Next take care of translation
for (int i = 0; i < 3; i++)
values.translation[i] = matrix(i, 3);
// Now get scale and shear. 'row' is a 3 element array of 3 component vectors
FloatVector3 row[3];
for (int i = 0; i < 3; i++)
row[i] = { matrix(0, i), matrix(1, i), matrix(2, i) };
// Compute X scale factor and normalize first row.
values.scale[0] = row[0].length();
row[0].normalize();
// Compute XY shear factor and make 2nd row orthogonal to 1st.
values.skew[0] = row[0].dot(row[1]);
row[1] = combine(row[1], row[0], 1.f, -values.skew[0]);
// Now, compute Y scale and normalize 2nd row.
values.scale[1] = row[1].length();
row[1].normalize();
values.skew[0] /= values.scale[1];
// Compute XZ and YZ shears, orthogonalize 3rd row
values.skew[1] = row[0].dot(row[2]);
row[2] = combine(row[2], row[0], 1.f, -values.skew[1]);
values.skew[2] = row[1].dot(row[2]);
row[2] = combine(row[2], row[1], 1.f, -values.skew[2]);
// Next, get Z scale and normalize 3rd row.
values.scale[2] = row[2].length();
row[2].normalize();
values.skew[1] /= values.scale[2];
values.skew[2] /= values.scale[2];
// At this point, the matrix (in rows) is orthonormal.
// Check for a coordinate system flip. If the determinant
// is -1, then negate the matrix and the scaling factors.
auto pdum3 = row[1].cross(row[2]);
if (row[0].dot(pdum3) < 0.f) {
for (int i = 0; i < 3; i++) {
values.scale[i] *= -1.f;
row[i][0] *= -1.f;
row[i][1] *= -1.f;
row[i][2] *= -1.f;
}
}
// Now, get the rotations out
values.rotation[0] = 0.5f * sqrt(max(1.f + row[0][0] - row[1][1] - row[2][2], 0.f));
values.rotation[1] = 0.5f * sqrt(max(1.f - row[0][0] + row[1][1] - row[2][2], 0.f));
values.rotation[2] = 0.5f * sqrt(max(1.f - row[0][0] - row[1][1] + row[2][2], 0.f));
values.rotation[3] = 0.5f * sqrt(max(1.f + row[0][0] + row[1][1] + row[2][2], 0.f));
if (row[2][1] > row[1][2])
values.rotation[0] = -values.rotation[0];
if (row[0][2] > row[2][0])
values.rotation[1] = -values.rotation[1];
if (row[1][0] > row[0][1])
values.rotation[2] = -values.rotation[2];
// FIXME: This accounts for the fact that the browser coordinate system is left-handed instead of right-handed.
// The reason for this is that the positive Y-axis direction points down instead of up. To fix this, we
// invert the Y axis. However, it feels like the spec pseudo-code above should have taken something like
// this into account, so we're probably doing something else wrong.
values.rotation[2] *= -1;
return values;
};
// https://drafts.csswg.org/css-transforms-2/#recomposing-to-a-3d-matrix
static constexpr auto recompose = [](DecomposedValues const& values) -> FloatMatrix4x4 {
auto matrix = FloatMatrix4x4::identity();
// apply perspective
for (int i = 0; i < 4; i++)
matrix(3, i) = values.perspective[i];
// apply translation
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++)
matrix(i, 3) += values.translation[j] * matrix(i, j);
}
// apply rotation
auto x = values.rotation[0];
auto y = values.rotation[1];
auto z = values.rotation[2];
auto w = values.rotation[3];
// Construct a composite rotation matrix from the quaternion values
// rotationMatrix is a identity 4x4 matrix initially
auto rotation_matrix = FloatMatrix4x4::identity();
rotation_matrix(0, 0) = 1.f - 2.f * (y * y + z * z);
rotation_matrix(1, 0) = 2.f * (x * y - z * w);
rotation_matrix(2, 0) = 2.f * (x * z + y * w);
rotation_matrix(0, 1) = 2.f * (x * y + z * w);
rotation_matrix(1, 1) = 1.f - 2.f * (x * x + z * z);
rotation_matrix(2, 1) = 2.f * (y * z - x * w);
rotation_matrix(0, 2) = 2.f * (x * z - y * w);
rotation_matrix(1, 2) = 2.f * (y * z + x * w);
rotation_matrix(2, 2) = 1.f - 2.f * (x * x + y * y);
matrix = matrix * rotation_matrix;
// apply skew
// temp is a identity 4x4 matrix initially
auto temp = FloatMatrix4x4::identity();
if (values.skew[2] != 0.f) {
temp(1, 2) = values.skew[2];
matrix = matrix * temp;
}