StyleComputer.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.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 <AK/RedBlackTree.h>
  12. #include <LibWeb/CSS/CSSFontFaceRule.h>
  13. #include <LibWeb/CSS/CSSKeyframesRule.h>
  14. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  15. #include <LibWeb/CSS/Selector.h>
  16. #include <LibWeb/CSS/StyleProperties.h>
  17. #include <LibWeb/Forward.h>
  18. namespace Web::CSS {
  19. struct MatchingRule {
  20. JS::GCPtr<CSSStyleRule const> rule;
  21. JS::GCPtr<CSSStyleSheet const> sheet;
  22. size_t style_sheet_index { 0 };
  23. size_t rule_index { 0 };
  24. size_t selector_index { 0 };
  25. u32 specificity { 0 };
  26. bool contains_pseudo_element { false };
  27. };
  28. struct FontFaceKey {
  29. FlyString family_name;
  30. int weight { 0 };
  31. int slope { 0 };
  32. [[nodiscard]] u32 hash() const { return pair_int_hash(family_name.hash(), pair_int_hash(weight, slope)); }
  33. [[nodiscard]] bool operator==(FontFaceKey const&) const = default;
  34. };
  35. class StyleComputer {
  36. public:
  37. explicit StyleComputer(DOM::Document&);
  38. ~StyleComputer();
  39. DOM::Document& document() { return m_document; }
  40. DOM::Document const& document() const { return m_document; }
  41. NonnullRefPtr<StyleProperties> create_document_style() const;
  42. ErrorOr<NonnullRefPtr<StyleProperties>> compute_style(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type> = {}) const;
  43. ErrorOr<RefPtr<StyleProperties>> compute_pseudo_element_style_if_needed(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>) const;
  44. // https://www.w3.org/TR/css-cascade/#origin
  45. enum class CascadeOrigin {
  46. Author,
  47. User,
  48. UserAgent,
  49. Animation,
  50. Transition,
  51. };
  52. Vector<MatchingRule> collect_matching_rules(DOM::Element const&, CascadeOrigin, Optional<CSS::Selector::PseudoElement::Type>) const;
  53. void invalidate_rule_cache();
  54. Gfx::Font const& initial_font() const;
  55. void did_load_font(FlyString const& family_name);
  56. void load_fonts_from_sheet(CSSStyleSheet const&);
  57. RefPtr<Gfx::FontCascadeList const> compute_font_for_style_values(DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, StyleValue const& font_family, StyleValue const& font_size, StyleValue const& font_style, StyleValue const& font_weight, StyleValue const& font_stretch, int math_depth = 0) const;
  58. struct AnimationKey {
  59. CSS::CSSStyleDeclaration const* source_declaration;
  60. DOM::Element const* element;
  61. };
  62. struct AnimationTiming {
  63. struct Linear { };
  64. struct CubicBezier {
  65. // Regular parameters
  66. double x1;
  67. double y1;
  68. double x2;
  69. double y2;
  70. struct CachedSample {
  71. double x;
  72. double y;
  73. double t;
  74. };
  75. mutable Vector<CachedSample, 64> m_cached_x_samples = {};
  76. CachedSample sample_around(double x) const;
  77. bool operator==(CubicBezier const& other) const
  78. {
  79. return x1 == other.x1 && y1 == other.y1 && x2 == other.x2 && y2 == other.y2;
  80. }
  81. };
  82. struct Steps {
  83. size_t number_of_steps;
  84. bool jump_at_start;
  85. bool jump_at_end;
  86. };
  87. Variant<Linear, CubicBezier, Steps> timing_function;
  88. };
  89. void set_viewport_rect(Badge<DOM::Document>, CSSPixelRect const& viewport_rect) { m_viewport_rect = viewport_rect; }
  90. private:
  91. enum class ComputeStyleMode {
  92. Normal,
  93. CreatePseudoElementStyleIfNeeded,
  94. };
  95. class FontLoader;
  96. struct MatchingFontCandidate;
  97. ErrorOr<RefPtr<StyleProperties>> compute_style_impl(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, ComputeStyleMode) const;
  98. ErrorOr<void> compute_cascaded_values(StyleProperties&, DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, bool& did_match_any_pseudo_element_rules, ComputeStyleMode) const;
  99. static RefPtr<Gfx::FontCascadeList const> find_matching_font_weight_ascending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive);
  100. static RefPtr<Gfx::FontCascadeList const> find_matching_font_weight_descending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive);
  101. RefPtr<Gfx::FontCascadeList const> font_matching_algorithm(FontFaceKey const& key, float font_size_in_pt) const;
  102. void compute_font(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  103. void compute_math_depth(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  104. void compute_defaulted_values(StyleProperties&, DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>) const;
  105. void absolutize_values(StyleProperties&) const;
  106. void resolve_effective_overflow_values(StyleProperties&) const;
  107. void transform_box_type_if_needed(StyleProperties&, DOM::Element const&, Optional<CSS::Selector::PseudoElement::Type>) const;
  108. void compute_defaulted_property_value(StyleProperties&, DOM::Element const*, CSS::PropertyID, Optional<CSS::Selector::PseudoElement::Type>) const;
  109. void set_all_properties(DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, StyleProperties&, StyleValue const&, DOM::Document&, CSS::CSSStyleDeclaration const*, StyleProperties::PropertyValues const& properties_for_revert) const;
  110. template<typename Callback>
  111. void for_each_stylesheet(CascadeOrigin, Callback) const;
  112. [[nodiscard]] CSSPixelRect viewport_rect() const { return m_viewport_rect; }
  113. [[nodiscard]] Length::FontMetrics calculate_root_element_font_metrics(StyleProperties const&) const;
  114. struct MatchingRuleSet {
  115. Vector<MatchingRule> user_agent_rules;
  116. Vector<MatchingRule> user_rules;
  117. Vector<MatchingRule> author_rules;
  118. };
  119. void cascade_declarations(StyleProperties&, DOM::Element&, Optional<CSS::Selector::PseudoElement::Type>, Vector<MatchingRule> const&, CascadeOrigin, Important) const;
  120. void build_rule_cache();
  121. void build_rule_cache_if_needed() const;
  122. JS::NonnullGCPtr<DOM::Document> m_document;
  123. struct AnimationKeyFrameSet {
  124. struct ResolvedKeyFrame {
  125. struct UseInitial { };
  126. Array<Variant<Empty, UseInitial, NonnullRefPtr<StyleValue const>>, to_underlying(last_property_id) + 1> resolved_properties {};
  127. };
  128. RedBlackTree<u64, ResolvedKeyFrame> keyframes_by_key;
  129. };
  130. struct RuleCache {
  131. HashMap<FlyString, Vector<MatchingRule>> rules_by_id;
  132. HashMap<FlyString, Vector<MatchingRule>> rules_by_class;
  133. HashMap<FlyString, Vector<MatchingRule>> rules_by_tag_name;
  134. Vector<MatchingRule> other_rules;
  135. HashMap<FlyString, NonnullOwnPtr<AnimationKeyFrameSet>> rules_by_animation_keyframes;
  136. };
  137. NonnullOwnPtr<RuleCache> make_rule_cache_for_cascade_origin(CascadeOrigin);
  138. RuleCache const& rule_cache_for_cascade_origin(CascadeOrigin) const;
  139. void ensure_animation_timer() const;
  140. OwnPtr<RuleCache> m_author_rule_cache;
  141. OwnPtr<RuleCache> m_user_rule_cache;
  142. OwnPtr<RuleCache> m_user_agent_rule_cache;
  143. JS::Handle<CSSStyleSheet> m_user_style_sheet;
  144. using FontLoaderList = Vector<NonnullOwnPtr<FontLoader>>;
  145. HashMap<FontFaceKey, FontLoaderList> m_loaded_fonts;
  146. Length::FontMetrics m_default_font_metrics;
  147. Length::FontMetrics m_root_element_font_metrics;
  148. constexpr static u64 AnimationKeyFrameKeyScaleFactor = 1000; // 0..100000
  149. enum class AnimationStepTransition {
  150. NoTransition,
  151. IdleOrBeforeToActive,
  152. IdleOrBeforeToAfter,
  153. ActiveToBefore,
  154. ActiveToActiveChangingTheIteration,
  155. ActiveToAfter,
  156. AfterToActive,
  157. AfterToBefore,
  158. Cancelled,
  159. };
  160. enum class AnimationState {
  161. Before,
  162. After,
  163. Idle,
  164. Active,
  165. };
  166. struct AnimationStateSnapshot {
  167. Array<RefPtr<StyleValue const>, to_underlying(last_property_id) + 1> state;
  168. };
  169. struct Animation {
  170. String name;
  171. Optional<CSS::Time> duration; // "auto" if not set.
  172. CSS::Time delay;
  173. Optional<size_t> iteration_count; // Infinite if not set.
  174. AnimationTiming timing_function;
  175. CSS::AnimationDirection direction;
  176. CSS::AnimationFillMode fill_mode;
  177. WeakPtr<DOM::Element> owning_element;
  178. CSS::Percentage progress { 0 };
  179. CSS::Time remaining_delay { 0, CSS::Time::Type::Ms };
  180. AnimationState current_state { AnimationState::Before };
  181. size_t current_iteration { 1 };
  182. mutable AnimationStateSnapshot initial_state {};
  183. mutable OwnPtr<AnimationStateSnapshot> active_state_if_fill_forward {};
  184. AnimationStepTransition step(CSS::Time const& time_step);
  185. ErrorOr<void> collect_into(StyleProperties&, RuleCache const&) const;
  186. bool is_done() const;
  187. private:
  188. float compute_output_progress(float input_progress) const;
  189. bool is_animating_backwards() const;
  190. };
  191. mutable HashMap<AnimationKey, NonnullOwnPtr<Animation>> m_active_animations;
  192. mutable HashMap<AnimationKey, OwnPtr<AnimationStateSnapshot>> m_finished_animations; // If fill-mode is forward/both, this is non-null and contains the final state.
  193. mutable RefPtr<Platform::Timer> m_animation_driver_timer;
  194. CSSPixelRect m_viewport_rect;
  195. };
  196. }
  197. template<>
  198. struct AK::Traits<Web::CSS::StyleComputer::AnimationKey> : public AK::DefaultTraits<Web::CSS::StyleComputer::AnimationKey> {
  199. static unsigned hash(Web::CSS::StyleComputer::AnimationKey const& k) { return pair_int_hash(ptr_hash(k.source_declaration), ptr_hash(k.element)); }
  200. static bool equals(Web::CSS::StyleComputer::AnimationKey const& a, Web::CSS::StyleComputer::AnimationKey const& b)
  201. {
  202. return a.element == b.element && a.source_declaration == b.source_declaration;
  203. }
  204. };