StyleComputer.h 10 KB

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