StyleComputer.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/HashMap.h>
  9. #include <AK/Optional.h>
  10. #include <AK/OwnPtr.h>
  11. #include <LibGfx/Font/Typeface.h>
  12. #include <LibWeb/Animations/KeyframeEffect.h>
  13. #include <LibWeb/CSS/CSSFontFaceRule.h>
  14. #include <LibWeb/CSS/CSSKeyframesRule.h>
  15. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  16. #include <LibWeb/CSS/Selector.h>
  17. #include <LibWeb/CSS/StyleProperties.h>
  18. #include <LibWeb/Forward.h>
  19. #include <LibWeb/Loader/ResourceLoader.h>
  20. namespace Web::CSS {
  21. // A counting bloom filter with 2 hash functions.
  22. // NOTE: If a counter overflows, it's kept maxed-out until the whole filter is cleared.
  23. template<typename CounterType, size_t key_bits>
  24. class CountingBloomFilter {
  25. public:
  26. CountingBloomFilter() { }
  27. void clear() { __builtin_memset(m_buckets, 0, sizeof(m_buckets)); }
  28. void increment(u32 key)
  29. {
  30. auto& first = bucket1(key);
  31. if (first < NumericLimits<CounterType>::max())
  32. ++first;
  33. auto& second = bucket2(key);
  34. if (second < NumericLimits<CounterType>::max())
  35. ++second;
  36. }
  37. void decrement(u32 key)
  38. {
  39. auto& first = bucket1(key);
  40. if (first < NumericLimits<CounterType>::max())
  41. --first;
  42. auto& second = bucket2(key);
  43. if (second < NumericLimits<CounterType>::max())
  44. --second;
  45. }
  46. [[nodiscard]] bool may_contain(u32 hash) const
  47. {
  48. return bucket1(hash) && bucket2(hash);
  49. }
  50. private:
  51. static constexpr u32 bucket_count = 1 << key_bits;
  52. static constexpr u32 key_mask = bucket_count - 1;
  53. [[nodiscard]] u32 hash1(u32 key) const { return key & key_mask; }
  54. [[nodiscard]] u32 hash2(u32 key) const { return (key >> 16) & key_mask; }
  55. [[nodiscard]] CounterType& bucket1(u32 key) { return m_buckets[hash1(key)]; }
  56. [[nodiscard]] CounterType& bucket2(u32 key) { return m_buckets[hash2(key)]; }
  57. [[nodiscard]] CounterType bucket1(u32 key) const { return m_buckets[hash1(key)]; }
  58. [[nodiscard]] CounterType bucket2(u32 key) const { return m_buckets[hash2(key)]; }
  59. CounterType m_buckets[bucket_count];
  60. };
  61. // https://www.w3.org/TR/css-cascade/#origin
  62. enum class CascadeOrigin : u8 {
  63. Author,
  64. User,
  65. UserAgent,
  66. Animation,
  67. Transition,
  68. };
  69. struct MatchingRule {
  70. GC::Ptr<DOM::ShadowRoot const> shadow_root;
  71. GC::Ptr<CSSRule const> rule; // Either CSSStyleRule or CSSNestedDeclarations
  72. GC::Ptr<CSSStyleSheet const> sheet;
  73. size_t style_sheet_index { 0 };
  74. size_t rule_index { 0 };
  75. size_t selector_index { 0 };
  76. u32 specificity { 0 };
  77. CascadeOrigin cascade_origin;
  78. bool contains_pseudo_element { false };
  79. bool can_use_fast_matches { false };
  80. bool must_be_hovered { false };
  81. bool skip { false };
  82. // Helpers to deal with the fact that `rule` might be a CSSStyleRule or a CSSNestedDeclarations
  83. PropertyOwningCSSStyleDeclaration const& declaration() const;
  84. SelectorList const& absolutized_selectors() const;
  85. FlyString const& qualified_layer_name() const;
  86. };
  87. struct FontFaceKey;
  88. struct OwnFontFaceKey {
  89. explicit OwnFontFaceKey(FontFaceKey const& other);
  90. operator FontFaceKey() const;
  91. [[nodiscard]] u32 hash() const { return pair_int_hash(family_name.hash(), pair_int_hash(weight, slope)); }
  92. [[nodiscard]] bool operator==(OwnFontFaceKey const& other) const = default;
  93. [[nodiscard]] bool operator==(FontFaceKey const& other) const;
  94. FlyString family_name;
  95. int weight { 0 };
  96. int slope { 0 };
  97. };
  98. class FontLoader;
  99. class StyleComputer {
  100. public:
  101. enum class AllowUnresolved {
  102. Yes,
  103. No,
  104. };
  105. static void for_each_property_expanding_shorthands(PropertyID, CSSStyleValue const&, AllowUnresolved, Function<void(PropertyID, CSSStyleValue const&)> const& set_longhand_property);
  106. static void set_property_expanding_shorthands(StyleProperties&, PropertyID, CSSStyleValue const&, CSS::CSSStyleDeclaration const*, StyleProperties const& style_for_revert, StyleProperties const& style_for_revert_layer, Important = Important::No);
  107. static NonnullRefPtr<CSSStyleValue const> get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type> = {});
  108. static Optional<String> user_agent_style_sheet_source(StringView name);
  109. explicit StyleComputer(DOM::Document&);
  110. ~StyleComputer();
  111. DOM::Document& document() { return m_document; }
  112. DOM::Document const& document() const { return m_document; }
  113. void reset_ancestor_filter();
  114. void push_ancestor(DOM::Element const&);
  115. void pop_ancestor(DOM::Element const&);
  116. StyleProperties create_document_style() const;
  117. StyleProperties compute_style(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type> = {}) const;
  118. Optional<StyleProperties> compute_pseudo_element_style_if_needed(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>) const;
  119. Vector<MatchingRule> collect_matching_rules(DOM::Element const&, CascadeOrigin, Optional<CSS::Selector::PseudoElement::Type>, FlyString const& qualified_layer_name = {}) const;
  120. void invalidate_rule_cache();
  121. Gfx::Font const& initial_font() const;
  122. void did_load_font(FlyString const& family_name);
  123. Optional<FontLoader&> load_font_face(ParsedFontFace const&, ESCAPING Function<void(FontLoader const&)> on_load = {}, ESCAPING Function<void()> on_fail = {});
  124. void load_fonts_from_sheet(CSSStyleSheet&);
  125. void unload_fonts_from_sheet(CSSStyleSheet&);
  126. RefPtr<Gfx::FontCascadeList const> compute_font_for_style_values(DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, CSSStyleValue const& font_family, CSSStyleValue const& font_size, CSSStyleValue const& font_style, CSSStyleValue const& font_weight, CSSStyleValue const& font_stretch, int math_depth = 0) const;
  127. void set_viewport_rect(Badge<DOM::Document>, CSSPixelRect const& viewport_rect) { m_viewport_rect = viewport_rect; }
  128. enum class AnimationRefresh {
  129. No,
  130. Yes,
  131. };
  132. void collect_animation_into(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, GC::Ref<Animations::KeyframeEffect> animation, StyleProperties& style_properties, AnimationRefresh = AnimationRefresh::No) const;
  133. [[nodiscard]] bool has_has_selectors() const { return m_has_has_selectors; }
  134. size_t number_of_css_font_faces_with_loading_in_progress() const;
  135. private:
  136. enum class ComputeStyleMode {
  137. Normal,
  138. CreatePseudoElementStyleIfNeeded,
  139. };
  140. struct MatchingFontCandidate;
  141. [[nodiscard]] bool should_reject_with_ancestor_filter(Selector const&) const;
  142. Optional<StyleProperties> compute_style_impl(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, ComputeStyleMode) const;
  143. void compute_cascaded_values(StyleProperties&, DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, bool& did_match_any_pseudo_element_rules, ComputeStyleMode) const;
  144. static RefPtr<Gfx::FontCascadeList const> find_matching_font_weight_ascending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive);
  145. static RefPtr<Gfx::FontCascadeList const> find_matching_font_weight_descending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive);
  146. RefPtr<Gfx::FontCascadeList const> font_matching_algorithm(FlyString const& family_name, int weight, int slope, float font_size_in_pt) const;
  147. void compute_font(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  148. void compute_math_depth(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  149. void compute_defaulted_values(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  150. void start_needed_transitions(StyleProperties const& old_style, StyleProperties& new_style, DOM::Element&, Optional<Selector::PseudoElement::Type>) const;
  151. void absolutize_values(StyleProperties&) const;
  152. void resolve_effective_overflow_values(StyleProperties&) const;
  153. void transform_box_type_if_needed(StyleProperties&, DOM::Element const&, Optional<CSS::Selector::PseudoElement::Type>) const;
  154. void compute_defaulted_property_value(StyleProperties&, DOM::Element const*, CSS::PropertyID, Optional<CSS::Selector::PseudoElement::Type>) const;
  155. void set_all_properties(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, StyleProperties&, CSSStyleValue const&, DOM::Document&, CSS::CSSStyleDeclaration const*, StyleProperties const& style_for_revert, StyleProperties const& style_for_revert_layer, Important = Important::No) const;
  156. template<typename Callback>
  157. void for_each_stylesheet(CascadeOrigin, Callback) const;
  158. [[nodiscard]] CSSPixelRect viewport_rect() const { return m_viewport_rect; }
  159. [[nodiscard]] Length::FontMetrics calculate_root_element_font_metrics(StyleProperties const&) const;
  160. Vector<FlyString> m_qualified_layer_names_in_order;
  161. void build_qualified_layer_names_cache();
  162. struct LayerMatchingRules {
  163. FlyString qualified_layer_name;
  164. Vector<MatchingRule> rules;
  165. };
  166. struct MatchingRuleSet {
  167. Vector<MatchingRule> user_agent_rules;
  168. Vector<MatchingRule> user_rules;
  169. Vector<LayerMatchingRules> author_rules;
  170. };
  171. void cascade_declarations(StyleProperties&, DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, Vector<MatchingRule> const&, CascadeOrigin, Important, StyleProperties const& style_for_revert, StyleProperties const& style_for_revert_layer) const;
  172. void build_rule_cache();
  173. void build_rule_cache_if_needed() const;
  174. GC::Ref<DOM::Document> m_document;
  175. struct RuleCache {
  176. HashMap<FlyString, Vector<MatchingRule>> rules_by_id;
  177. HashMap<FlyString, Vector<MatchingRule>> rules_by_class;
  178. HashMap<FlyString, Vector<MatchingRule>> rules_by_tag_name;
  179. HashMap<FlyString, Vector<MatchingRule>, AK::ASCIICaseInsensitiveFlyStringTraits> rules_by_attribute_name;
  180. Array<Vector<MatchingRule>, to_underlying(CSS::Selector::PseudoElement::Type::KnownPseudoElementCount)> rules_by_pseudo_element;
  181. Vector<MatchingRule> root_rules;
  182. Vector<MatchingRule> other_rules;
  183. HashMap<FlyString, NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet>> rules_by_animation_keyframes;
  184. bool has_has_selectors { false };
  185. };
  186. NonnullOwnPtr<RuleCache> make_rule_cache_for_cascade_origin(CascadeOrigin);
  187. RuleCache const& rule_cache_for_cascade_origin(CascadeOrigin) const;
  188. bool m_has_has_selectors { false };
  189. OwnPtr<RuleCache> m_author_rule_cache;
  190. OwnPtr<RuleCache> m_user_rule_cache;
  191. OwnPtr<RuleCache> m_user_agent_rule_cache;
  192. GC::Root<CSSStyleSheet> m_user_style_sheet;
  193. using FontLoaderList = Vector<NonnullOwnPtr<FontLoader>>;
  194. HashMap<OwnFontFaceKey, FontLoaderList> m_loaded_fonts;
  195. Length::FontMetrics m_default_font_metrics;
  196. Length::FontMetrics m_root_element_font_metrics;
  197. CSSPixelRect m_viewport_rect;
  198. CountingBloomFilter<u8, 14> m_ancestor_filter;
  199. };
  200. class FontLoader : public ResourceClient {
  201. public:
  202. FontLoader(StyleComputer& style_computer, FlyString family_name, Vector<Gfx::UnicodeRange> unicode_ranges, Vector<URL::URL> urls, ESCAPING Function<void(FontLoader const&)> on_load = {}, ESCAPING Function<void()> on_fail = {});
  203. virtual ~FontLoader() override;
  204. Vector<Gfx::UnicodeRange> const& unicode_ranges() const { return m_unicode_ranges; }
  205. RefPtr<Gfx::Typeface> vector_font() const { return m_vector_font; }
  206. RefPtr<Gfx::Font> font_with_point_size(float point_size);
  207. void start_loading_next_url();
  208. bool is_loading() const { return resource() && resource()->is_pending(); }
  209. private:
  210. // ^ResourceClient
  211. virtual void resource_did_load() override;
  212. virtual void resource_did_fail() override;
  213. void resource_did_load_or_fail();
  214. ErrorOr<NonnullRefPtr<Gfx::Typeface>> try_load_font();
  215. StyleComputer& m_style_computer;
  216. FlyString m_family_name;
  217. Vector<Gfx::UnicodeRange> m_unicode_ranges;
  218. RefPtr<Gfx::Typeface> m_vector_font;
  219. Vector<URL::URL> m_urls;
  220. Function<void(FontLoader const&)> m_on_load;
  221. Function<void()> m_on_fail;
  222. };
  223. }