StyleComputer.h 13 KB

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