StyleComputer.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/BinarySearch.h>
  9. #include <AK/Debug.h>
  10. #include <AK/Error.h>
  11. #include <AK/Find.h>
  12. #include <AK/Function.h>
  13. #include <AK/HashMap.h>
  14. #include <AK/QuickSort.h>
  15. #include <AK/TemporaryChange.h>
  16. #include <LibGfx/Font/Font.h>
  17. #include <LibGfx/Font/FontDatabase.h>
  18. #include <LibGfx/Font/FontStyleMapping.h>
  19. #include <LibGfx/Font/OpenType/Font.h>
  20. #include <LibGfx/Font/ScaledFont.h>
  21. #include <LibGfx/Font/VectorFont.h>
  22. #include <LibGfx/Font/WOFF/Font.h>
  23. #include <LibGfx/Font/WOFF2/Font.h>
  24. #include <LibWeb/CSS/CSSFontFaceRule.h>
  25. #include <LibWeb/CSS/CSSImportRule.h>
  26. #include <LibWeb/CSS/CSSStyleRule.h>
  27. #include <LibWeb/CSS/Parser/Parser.h>
  28. #include <LibWeb/CSS/SelectorEngine.h>
  29. #include <LibWeb/CSS/StyleComputer.h>
  30. #include <LibWeb/CSS/StyleSheet.h>
  31. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  32. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  33. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  34. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  35. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  36. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  37. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  45. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  46. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  47. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  48. #include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
  49. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  50. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  51. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
  55. #include <LibWeb/DOM/Document.h>
  56. #include <LibWeb/DOM/Element.h>
  57. #include <LibWeb/FontCache.h>
  58. #include <LibWeb/HTML/HTMLBRElement.h>
  59. #include <LibWeb/HTML/HTMLHtmlElement.h>
  60. #include <LibWeb/Layout/Node.h>
  61. #include <LibWeb/Loader/ResourceLoader.h>
  62. #include <LibWeb/Namespace.h>
  63. #include <LibWeb/Platform/FontPlugin.h>
  64. #include <LibWeb/ReferrerPolicy/AbstractOperations.h>
  65. #include <stdio.h>
  66. namespace AK {
  67. // traits for FontFaceKey
  68. template<>
  69. struct Traits<Web::CSS::FontFaceKey> : public GenericTraits<Web::CSS::FontFaceKey> {
  70. static unsigned hash(Web::CSS::FontFaceKey const& key) { return pair_int_hash(key.family_name.hash(), pair_int_hash(key.weight, key.slope)); }
  71. };
  72. }
  73. namespace Web::CSS {
  74. static DOM::Element const* element_to_inherit_style_from(DOM::Element const*, Optional<CSS::Selector::PseudoElement>);
  75. static NonnullRefPtr<StyleValue const> get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID, DOM::Element const*, Optional<CSS::Selector::PseudoElement>);
  76. StyleComputer::StyleComputer(DOM::Document& document)
  77. : m_document(document)
  78. , m_default_font_metrics(16, Gfx::FontDatabase::default_font().pixel_metrics(), 16)
  79. , m_root_element_font_metrics(m_default_font_metrics)
  80. {
  81. }
  82. StyleComputer::~StyleComputer() = default;
  83. class StyleComputer::FontLoader : public ResourceClient {
  84. public:
  85. explicit FontLoader(StyleComputer& style_computer, FlyString family_name, Vector<AK::URL> urls)
  86. : m_style_computer(style_computer)
  87. , m_family_name(move(family_name))
  88. , m_urls(move(urls))
  89. {
  90. start_loading_next_url();
  91. }
  92. virtual ~FontLoader() override { }
  93. virtual void resource_did_load() override
  94. {
  95. auto result = try_load_font();
  96. if (result.is_error())
  97. return start_loading_next_url();
  98. m_vector_font = result.release_value();
  99. m_style_computer.did_load_font(m_family_name);
  100. }
  101. virtual void resource_did_fail() override
  102. {
  103. }
  104. RefPtr<Gfx::Font> font_with_point_size(float point_size) const
  105. {
  106. if (!m_vector_font)
  107. return nullptr;
  108. if (auto it = m_cached_fonts.find(point_size); it != m_cached_fonts.end())
  109. return it->value;
  110. // FIXME: It might be nicer to have a global cap on the number of fonts we cache
  111. // instead of doing it at the per-font level like this.
  112. constexpr size_t max_cached_font_size_count = 64;
  113. if (m_cached_fonts.size() > max_cached_font_size_count)
  114. m_cached_fonts.remove(m_cached_fonts.begin());
  115. auto font = adopt_ref(*new Gfx::ScaledFont(*m_vector_font, point_size, point_size));
  116. m_cached_fonts.set(point_size, font);
  117. return font;
  118. }
  119. private:
  120. void start_loading_next_url()
  121. {
  122. if (m_urls.is_empty())
  123. return;
  124. LoadRequest request;
  125. request.set_url(m_urls.take_first());
  126. // HACK: We're crudely computing the referer value and shoving it into the
  127. // request until fetch infrastructure is used here.
  128. auto referrer_url = ReferrerPolicy::strip_url_for_use_as_referrer(m_style_computer.document().url());
  129. if (referrer_url.has_value() && !request.headers().contains("Referer"))
  130. request.set_header("Referer", referrer_url->serialize());
  131. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  132. }
  133. ErrorOr<NonnullRefPtr<Gfx::VectorFont>> try_load_font()
  134. {
  135. // 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
  136. auto mime_type = resource()->mime_type();
  137. if (mime_type == "font/ttf"sv || mime_type == "application/x-font-ttf"sv)
  138. return TRY(OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
  139. if (mime_type == "font/woff"sv || mime_type == "application/font-woff"sv)
  140. return TRY(WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
  141. if (mime_type == "font/woff2"sv || mime_type == "application/font-woff2"sv) {
  142. auto woff2 = WOFF2::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  143. if (woff2.is_error()) {
  144. dbgln("WOFF2 error: {}", woff2.error());
  145. return woff2.release_error();
  146. }
  147. return woff2.release_value();
  148. }
  149. auto ttf = OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  150. if (!ttf.is_error())
  151. return ttf.release_value();
  152. auto woff = WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  153. if (!woff.is_error())
  154. return woff.release_value();
  155. auto woff2 = WOFF2::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  156. if (!woff2.is_error())
  157. return woff2.release_value();
  158. return woff2.release_error();
  159. }
  160. StyleComputer& m_style_computer;
  161. FlyString m_family_name;
  162. RefPtr<Gfx::VectorFont> m_vector_font;
  163. Vector<AK::URL> m_urls;
  164. HashMap<float, NonnullRefPtr<Gfx::ScaledFont>> mutable m_cached_fonts;
  165. };
  166. struct StyleComputer::MatchingFontCandidate {
  167. FontFaceKey key;
  168. Variant<FontLoader*, Gfx::Typeface const*> loader_or_typeface;
  169. [[nodiscard]] RefPtr<Gfx::Font const> font_with_point_size(float point_size) const
  170. {
  171. if (auto* loader = loader_or_typeface.get_pointer<FontLoader*>(); loader) {
  172. return (*loader)->font_with_point_size(point_size);
  173. }
  174. return loader_or_typeface.get<Gfx::Typeface const*>()->get_font(point_size);
  175. }
  176. };
  177. static CSSStyleSheet& default_stylesheet(DOM::Document const& document)
  178. {
  179. static JS::Handle<CSSStyleSheet> sheet;
  180. if (!sheet.cell()) {
  181. extern StringView default_stylesheet_source;
  182. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), default_stylesheet_source));
  183. }
  184. return *sheet;
  185. }
  186. static CSSStyleSheet& quirks_mode_stylesheet(DOM::Document const& document)
  187. {
  188. static JS::Handle<CSSStyleSheet> sheet;
  189. if (!sheet.cell()) {
  190. extern StringView quirks_mode_stylesheet_source;
  191. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), quirks_mode_stylesheet_source));
  192. }
  193. return *sheet;
  194. }
  195. static CSSStyleSheet& mathml_stylesheet(DOM::Document const& document)
  196. {
  197. static JS::Handle<CSSStyleSheet> sheet;
  198. if (!sheet.cell()) {
  199. extern StringView mathml_stylesheet_source;
  200. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), mathml_stylesheet_source));
  201. }
  202. return *sheet;
  203. }
  204. static CSSStyleSheet& svg_stylesheet(DOM::Document const& document)
  205. {
  206. static JS::Handle<CSSStyleSheet> sheet;
  207. if (!sheet.cell()) {
  208. extern StringView svg_stylesheet_source;
  209. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), svg_stylesheet_source));
  210. }
  211. return *sheet;
  212. }
  213. template<typename Callback>
  214. void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const
  215. {
  216. if (cascade_origin == CascadeOrigin::UserAgent) {
  217. callback(default_stylesheet(document()));
  218. if (document().in_quirks_mode())
  219. callback(quirks_mode_stylesheet(document()));
  220. callback(mathml_stylesheet(document()));
  221. callback(svg_stylesheet(document()));
  222. }
  223. if (cascade_origin == CascadeOrigin::User) {
  224. if (m_user_style_sheet)
  225. callback(*m_user_style_sheet);
  226. }
  227. if (cascade_origin == CascadeOrigin::Author) {
  228. for (auto const& sheet : document().style_sheets().sheets())
  229. callback(*sheet);
  230. }
  231. }
  232. StyleComputer::RuleCache const& StyleComputer::rule_cache_for_cascade_origin(CascadeOrigin cascade_origin) const
  233. {
  234. switch (cascade_origin) {
  235. case CascadeOrigin::Author:
  236. return *m_author_rule_cache;
  237. case CascadeOrigin::User:
  238. return *m_user_rule_cache;
  239. case CascadeOrigin::UserAgent:
  240. return *m_user_agent_rule_cache;
  241. default:
  242. TODO();
  243. }
  244. }
  245. [[nodiscard]] static bool filter_namespace_rule(DOM::Element const& element, MatchingRule const& rule)
  246. {
  247. // FIXME: Filter out non-default namespace using prefixes
  248. auto namespace_uri = rule.sheet->default_namespace();
  249. if (namespace_uri.has_value() && namespace_uri.value() != element.namespace_()) {
  250. return false;
  251. }
  252. return true;
  253. }
  254. Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin cascade_origin, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  255. {
  256. auto const& rule_cache = rule_cache_for_cascade_origin(cascade_origin);
  257. Vector<MatchingRule> rules_to_run;
  258. auto add_rules_to_run = [&](Vector<MatchingRule> const& rules) {
  259. rules_to_run.grow_capacity(rules_to_run.size() + rules.size());
  260. if (pseudo_element.has_value()) {
  261. for (auto const& rule : rules) {
  262. if (rule.contains_pseudo_element && filter_namespace_rule(element, rule))
  263. rules_to_run.append(rule);
  264. }
  265. } else {
  266. for (auto const& rule : rules) {
  267. if (filter_namespace_rule(element, rule))
  268. rules_to_run.append(rule);
  269. }
  270. }
  271. };
  272. for (auto const& class_name : element.class_names()) {
  273. if (auto it = rule_cache.rules_by_class.find(class_name); it != rule_cache.rules_by_class.end())
  274. add_rules_to_run(it->value);
  275. }
  276. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null()) {
  277. if (auto it = rule_cache.rules_by_id.find(FlyString::from_deprecated_fly_string(id).release_value_but_fixme_should_propagate_errors()); it != rule_cache.rules_by_id.end())
  278. add_rules_to_run(it->value);
  279. }
  280. if (auto it = rule_cache.rules_by_tag_name.find(FlyString::from_deprecated_fly_string(element.local_name()).release_value_but_fixme_should_propagate_errors()); it != rule_cache.rules_by_tag_name.end())
  281. add_rules_to_run(it->value);
  282. add_rules_to_run(rule_cache.other_rules);
  283. Vector<MatchingRule> matching_rules;
  284. matching_rules.ensure_capacity(rules_to_run.size());
  285. for (auto const& rule_to_run : rules_to_run) {
  286. auto const& selector = rule_to_run.rule->selectors()[rule_to_run.selector_index];
  287. if (SelectorEngine::matches(selector, *rule_to_run.sheet, element, pseudo_element))
  288. matching_rules.append(rule_to_run);
  289. }
  290. return matching_rules;
  291. }
  292. static void sort_matching_rules(Vector<MatchingRule>& matching_rules)
  293. {
  294. quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) {
  295. auto const& a_selector = a.rule->selectors()[a.selector_index];
  296. auto const& b_selector = b.rule->selectors()[b.selector_index];
  297. auto a_specificity = a_selector->specificity();
  298. auto b_specificity = b_selector->specificity();
  299. if (a_selector->specificity() == b_selector->specificity()) {
  300. if (a.style_sheet_index == b.style_sheet_index)
  301. return a.rule_index < b.rule_index;
  302. return a.style_sheet_index < b.style_sheet_index;
  303. }
  304. return a_specificity < b_specificity;
  305. });
  306. }
  307. static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert)
  308. {
  309. auto set_longhand_property = [&](CSS::PropertyID property_id, StyleValue const& value) {
  310. if (value.is_revert()) {
  311. auto& property_in_previous_cascade_origin = properties_for_revert[to_underlying(property_id)];
  312. if (property_in_previous_cascade_origin.has_value())
  313. style.set_property(property_id, property_in_previous_cascade_origin->style, property_in_previous_cascade_origin->declaration);
  314. } else {
  315. style.set_property(property_id, value, declaration);
  316. }
  317. };
  318. auto map_logical_property_to_real_property = [](PropertyID property_id) -> Optional<PropertyID> {
  319. // FIXME: Honor writing-mode, direction and text-orientation.
  320. switch (property_id) {
  321. case PropertyID::MarginBlockStart:
  322. return PropertyID::MarginTop;
  323. case PropertyID::MarginBlockEnd:
  324. return PropertyID::MarginBottom;
  325. case PropertyID::MarginInlineStart:
  326. return PropertyID::MarginLeft;
  327. case PropertyID::MarginInlineEnd:
  328. return PropertyID::MarginRight;
  329. case PropertyID::PaddingBlockStart:
  330. return PropertyID::PaddingTop;
  331. case PropertyID::PaddingBlockEnd:
  332. return PropertyID::PaddingBottom;
  333. case PropertyID::PaddingInlineStart:
  334. return PropertyID::PaddingLeft;
  335. case PropertyID::PaddingInlineEnd:
  336. return PropertyID::PaddingRight;
  337. case PropertyID::InsetBlockStart:
  338. return PropertyID::Top;
  339. case PropertyID::InsetBlockEnd:
  340. return PropertyID::Bottom;
  341. case PropertyID::InsetInlineStart:
  342. return PropertyID::Left;
  343. case PropertyID::InsetInlineEnd:
  344. return PropertyID::Right;
  345. default:
  346. return {};
  347. }
  348. };
  349. struct StartAndEndPropertyIDs {
  350. PropertyID start;
  351. PropertyID end;
  352. };
  353. auto map_logical_property_to_real_properties = [](PropertyID property_id) -> Optional<StartAndEndPropertyIDs> {
  354. // FIXME: Honor writing-mode, direction and text-orientation.
  355. switch (property_id) {
  356. case PropertyID::MarginBlock:
  357. return StartAndEndPropertyIDs { PropertyID::MarginTop, PropertyID::MarginBottom };
  358. case PropertyID::MarginInline:
  359. return StartAndEndPropertyIDs { PropertyID::MarginLeft, PropertyID::MarginRight };
  360. case PropertyID::PaddingBlock:
  361. return StartAndEndPropertyIDs { PropertyID::PaddingTop, PropertyID::PaddingBottom };
  362. case PropertyID::PaddingInline:
  363. return StartAndEndPropertyIDs { PropertyID::PaddingLeft, PropertyID::PaddingRight };
  364. case PropertyID::InsetBlock:
  365. return StartAndEndPropertyIDs { PropertyID::Top, PropertyID::Bottom };
  366. case PropertyID::InsetInline:
  367. return StartAndEndPropertyIDs { PropertyID::Left, PropertyID::Right };
  368. default:
  369. return {};
  370. }
  371. };
  372. if (auto real_property_id = map_logical_property_to_real_property(property_id); real_property_id.has_value())
  373. return set_property_expanding_shorthands(style, real_property_id.value(), value, document, declaration, properties_for_revert);
  374. if (auto real_property_ids = map_logical_property_to_real_properties(property_id); real_property_ids.has_value()) {
  375. if (value.is_value_list() && value.as_value_list().size() == 2) {
  376. auto const& start = value.as_value_list().values()[0];
  377. auto const& end = value.as_value_list().values()[1];
  378. set_property_expanding_shorthands(style, real_property_ids->start, start, document, declaration, properties_for_revert);
  379. set_property_expanding_shorthands(style, real_property_ids->end, end, document, declaration, properties_for_revert);
  380. return;
  381. }
  382. set_property_expanding_shorthands(style, real_property_ids->start, value, document, declaration, properties_for_revert);
  383. set_property_expanding_shorthands(style, real_property_ids->end, value, document, declaration, properties_for_revert);
  384. return;
  385. }
  386. if (value.is_shorthand()) {
  387. auto& shorthand_value = value.as_shorthand();
  388. auto& properties = shorthand_value.sub_properties();
  389. auto& values = shorthand_value.values();
  390. for (size_t i = 0; i < properties.size(); ++i)
  391. set_property_expanding_shorthands(style, properties[i], values[i], document, declaration, properties_for_revert);
  392. return;
  393. }
  394. auto assign_edge_values = [&](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
  395. if (values.size() == 4) {
  396. set_longhand_property(top_property, values[0]);
  397. set_longhand_property(right_property, values[1]);
  398. set_longhand_property(bottom_property, values[2]);
  399. set_longhand_property(left_property, values[3]);
  400. } else if (values.size() == 3) {
  401. set_longhand_property(top_property, values[0]);
  402. set_longhand_property(right_property, values[1]);
  403. set_longhand_property(bottom_property, values[2]);
  404. set_longhand_property(left_property, values[1]);
  405. } else if (values.size() == 2) {
  406. set_longhand_property(top_property, values[0]);
  407. set_longhand_property(right_property, values[1]);
  408. set_longhand_property(bottom_property, values[0]);
  409. set_longhand_property(left_property, values[1]);
  410. } else if (values.size() == 1) {
  411. set_longhand_property(top_property, values[0]);
  412. set_longhand_property(right_property, values[0]);
  413. set_longhand_property(bottom_property, values[0]);
  414. set_longhand_property(left_property, values[0]);
  415. }
  416. };
  417. if (property_id == CSS::PropertyID::Border) {
  418. set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document, declaration, properties_for_revert);
  419. set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document, declaration, properties_for_revert);
  420. set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document, declaration, properties_for_revert);
  421. set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document, declaration, properties_for_revert);
  422. // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands
  423. return;
  424. }
  425. if (property_id == CSS::PropertyID::BorderStyle) {
  426. if (value.is_value_list()) {
  427. auto const& values_list = value.as_value_list();
  428. assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values());
  429. return;
  430. }
  431. set_longhand_property(CSS::PropertyID::BorderTopStyle, value);
  432. set_longhand_property(CSS::PropertyID::BorderRightStyle, value);
  433. set_longhand_property(CSS::PropertyID::BorderBottomStyle, value);
  434. set_longhand_property(CSS::PropertyID::BorderLeftStyle, value);
  435. return;
  436. }
  437. if (property_id == CSS::PropertyID::BorderWidth) {
  438. if (value.is_value_list()) {
  439. auto const& values_list = value.as_value_list();
  440. assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values());
  441. return;
  442. }
  443. set_longhand_property(CSS::PropertyID::BorderTopWidth, value);
  444. set_longhand_property(CSS::PropertyID::BorderRightWidth, value);
  445. set_longhand_property(CSS::PropertyID::BorderBottomWidth, value);
  446. set_longhand_property(CSS::PropertyID::BorderLeftWidth, value);
  447. return;
  448. }
  449. if (property_id == CSS::PropertyID::BorderColor) {
  450. if (value.is_value_list()) {
  451. auto const& values_list = value.as_value_list();
  452. assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values());
  453. return;
  454. }
  455. set_longhand_property(CSS::PropertyID::BorderTopColor, value);
  456. set_longhand_property(CSS::PropertyID::BorderRightColor, value);
  457. set_longhand_property(CSS::PropertyID::BorderBottomColor, value);
  458. set_longhand_property(CSS::PropertyID::BorderLeftColor, value);
  459. return;
  460. }
  461. if (property_id == CSS::PropertyID::BackgroundPosition) {
  462. if (value.is_position()) {
  463. auto const& position = value.as_position();
  464. set_longhand_property(CSS::PropertyID::BackgroundPositionX, position.edge_x());
  465. set_longhand_property(CSS::PropertyID::BackgroundPositionY, position.edge_y());
  466. } else if (value.is_value_list()) {
  467. // Expand background-position layer list into separate lists for x and y positions:
  468. auto const& values_list = value.as_value_list();
  469. StyleValueVector x_positions {};
  470. StyleValueVector y_positions {};
  471. x_positions.ensure_capacity(values_list.size());
  472. y_positions.ensure_capacity(values_list.size());
  473. for (auto& layer : values_list.values()) {
  474. if (layer->is_position()) {
  475. auto const& position = layer->as_position();
  476. x_positions.unchecked_append(position.edge_x());
  477. y_positions.unchecked_append(position.edge_y());
  478. } else {
  479. x_positions.unchecked_append(layer);
  480. y_positions.unchecked_append(layer);
  481. }
  482. }
  483. set_longhand_property(CSS::PropertyID::BackgroundPositionX, StyleValueList::create(move(x_positions), values_list.separator()));
  484. set_longhand_property(CSS::PropertyID::BackgroundPositionY, StyleValueList::create(move(y_positions), values_list.separator()));
  485. } else {
  486. set_longhand_property(CSS::PropertyID::BackgroundPositionX, value);
  487. set_longhand_property(CSS::PropertyID::BackgroundPositionY, value);
  488. }
  489. return;
  490. }
  491. if (property_id == CSS::PropertyID::Inset) {
  492. if (value.is_value_list()) {
  493. auto const& values_list = value.as_value_list();
  494. assign_edge_values(PropertyID::Top, PropertyID::Right, PropertyID::Bottom, PropertyID::Left, values_list.values());
  495. return;
  496. }
  497. set_longhand_property(CSS::PropertyID::Top, value);
  498. set_longhand_property(CSS::PropertyID::Right, value);
  499. set_longhand_property(CSS::PropertyID::Bottom, value);
  500. set_longhand_property(CSS::PropertyID::Left, value);
  501. return;
  502. }
  503. if (property_id == CSS::PropertyID::Margin) {
  504. if (value.is_value_list()) {
  505. auto const& values_list = value.as_value_list();
  506. assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values());
  507. return;
  508. }
  509. set_longhand_property(CSS::PropertyID::MarginTop, value);
  510. set_longhand_property(CSS::PropertyID::MarginRight, value);
  511. set_longhand_property(CSS::PropertyID::MarginBottom, value);
  512. set_longhand_property(CSS::PropertyID::MarginLeft, value);
  513. return;
  514. }
  515. if (property_id == CSS::PropertyID::Padding) {
  516. if (value.is_value_list()) {
  517. auto const& values_list = value.as_value_list();
  518. assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values());
  519. return;
  520. }
  521. set_longhand_property(CSS::PropertyID::PaddingTop, value);
  522. set_longhand_property(CSS::PropertyID::PaddingRight, value);
  523. set_longhand_property(CSS::PropertyID::PaddingBottom, value);
  524. set_longhand_property(CSS::PropertyID::PaddingLeft, value);
  525. return;
  526. }
  527. if (property_id == CSS::PropertyID::Gap || property_id == CSS::PropertyID::GridGap) {
  528. if (value.is_value_list()) {
  529. auto const& values_list = value.as_value_list();
  530. set_longhand_property(CSS::PropertyID::RowGap, values_list.values()[0]);
  531. set_longhand_property(CSS::PropertyID::ColumnGap, values_list.values()[1]);
  532. return;
  533. }
  534. set_longhand_property(CSS::PropertyID::RowGap, value);
  535. set_longhand_property(CSS::PropertyID::ColumnGap, value);
  536. return;
  537. }
  538. if (property_id == CSS::PropertyID::RowGap || property_id == CSS::PropertyID::GridRowGap) {
  539. set_longhand_property(CSS::PropertyID::RowGap, value);
  540. return;
  541. }
  542. if (property_id == CSS::PropertyID::ColumnGap || property_id == CSS::PropertyID::GridColumnGap) {
  543. set_longhand_property(CSS::PropertyID::ColumnGap, value);
  544. return;
  545. }
  546. if (property_id == CSS::PropertyID::MaxInlineSize || property_id == CSS::PropertyID::MinInlineSize) {
  547. // FIXME: Use writing-mode to determine if we should set width or height.
  548. bool is_horizontal = true;
  549. if (is_horizontal) {
  550. if (property_id == CSS::PropertyID::MaxInlineSize) {
  551. set_longhand_property(CSS::PropertyID::MaxWidth, value);
  552. } else {
  553. set_longhand_property(CSS::PropertyID::MinWidth, value);
  554. }
  555. } else {
  556. if (property_id == CSS::PropertyID::MaxInlineSize) {
  557. set_longhand_property(CSS::PropertyID::MaxHeight, value);
  558. } else {
  559. set_longhand_property(CSS::PropertyID::MinHeight, value);
  560. }
  561. }
  562. return;
  563. }
  564. if (property_is_shorthand(property_id)) {
  565. // ShorthandStyleValue was handled already.
  566. // That means if we got here, that `value` must be a CSS-wide keyword, which we should apply to our longhand properties.
  567. // We don't directly call `set_longhand_property()` because the longhands might have longhands of their own.
  568. // (eg `grid` -> `grid-template` -> `grid-template-areas` & `grid-template-rows` & `grid-template-columns`)
  569. VERIFY(value.is_css_wide_keyword());
  570. for (auto longhand : longhands_for_shorthand(property_id))
  571. set_property_expanding_shorthands(style, longhand, value, document, declaration, properties_for_revert);
  572. return;
  573. }
  574. set_longhand_property(property_id, value);
  575. }
  576. void StyleComputer::set_all_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, StyleProperties& style, StyleValue const& value, DOM::Document& document, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert) const
  577. {
  578. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  579. auto property_id = (CSS::PropertyID)i;
  580. if (value.is_revert()) {
  581. style.m_property_values[to_underlying(property_id)] = properties_for_revert[to_underlying(property_id)];
  582. continue;
  583. }
  584. if (value.is_unset()) {
  585. if (is_inherited_property(property_id))
  586. style.m_property_values[to_underlying(property_id)] = { { get_inherit_value(document.realm(), property_id, &element, pseudo_element), nullptr } };
  587. else
  588. style.m_property_values[to_underlying(property_id)] = { { property_initial_value(document.realm(), property_id), nullptr } };
  589. continue;
  590. }
  591. NonnullRefPtr<StyleValue> property_value = value;
  592. if (property_value->is_unresolved())
  593. property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document }, element, pseudo_element, property_id, property_value->as_unresolved());
  594. if (!property_value->is_unresolved())
  595. set_property_expanding_shorthands(style, property_id, property_value, document, declaration, properties_for_revert);
  596. set_property_expanding_shorthands(style, property_id, value, document, declaration, properties_for_revert);
  597. }
  598. }
  599. void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, Important important) const
  600. {
  601. auto properties_for_revert = style.properties();
  602. for (auto const& match : matching_rules) {
  603. for (auto const& property : verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).properties()) {
  604. if (important != property.important)
  605. continue;
  606. if (property.property_id == CSS::PropertyID::All) {
  607. set_all_properties(element, pseudo_element, style, property.value, m_document, &match.rule->declaration(), properties_for_revert);
  608. continue;
  609. }
  610. auto property_value = property.value;
  611. if (property.value->is_unresolved())
  612. property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
  613. if (!property_value->is_unresolved())
  614. set_property_expanding_shorthands(style, property.property_id, property_value, m_document, &match.rule->declaration(), properties_for_revert);
  615. }
  616. }
  617. if (cascade_origin == CascadeOrigin::Author && !pseudo_element.has_value()) {
  618. if (auto const* inline_style = verify_cast<ElementInlineCSSStyleDeclaration>(element.inline_style())) {
  619. for (auto const& property : inline_style->properties()) {
  620. if (important != property.important)
  621. continue;
  622. if (property.property_id == CSS::PropertyID::All) {
  623. set_all_properties(element, pseudo_element, style, property.value, m_document, inline_style, properties_for_revert);
  624. continue;
  625. }
  626. auto property_value = property.value;
  627. if (property.value->is_unresolved())
  628. property_value = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
  629. if (!property_value->is_unresolved())
  630. set_property_expanding_shorthands(style, property.property_id, property_value, m_document, inline_style, properties_for_revert);
  631. }
  632. }
  633. }
  634. }
  635. static ErrorOr<void> cascade_custom_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, Vector<MatchingRule> const& matching_rules)
  636. {
  637. size_t needed_capacity = 0;
  638. for (auto const& matching_rule : matching_rules)
  639. needed_capacity += verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties().size();
  640. if (!pseudo_element.has_value()) {
  641. if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style()))
  642. needed_capacity += inline_style->custom_properties().size();
  643. }
  644. HashMap<DeprecatedFlyString, StyleProperty> custom_properties;
  645. TRY(custom_properties.try_ensure_capacity(needed_capacity));
  646. for (auto const& matching_rule : matching_rules) {
  647. for (auto const& it : verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties())
  648. custom_properties.set(it.key, it.value);
  649. }
  650. if (!pseudo_element.has_value()) {
  651. if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style())) {
  652. for (auto const& it : inline_style->custom_properties())
  653. custom_properties.set(it.key, it.value);
  654. }
  655. }
  656. element.set_custom_properties(pseudo_element, move(custom_properties));
  657. return {};
  658. }
  659. StyleComputer::AnimationStepTransition StyleComputer::Animation::step(CSS::Time const& time_step)
  660. {
  661. auto delay_ms = remaining_delay.to_milliseconds();
  662. auto time_step_ms = time_step.to_milliseconds();
  663. if (delay_ms > time_step_ms) {
  664. remaining_delay = CSS::Time { static_cast<float>(delay_ms - time_step_ms), CSS::Time::Type::Ms };
  665. return AnimationStepTransition::NoTransition;
  666. }
  667. remaining_delay = CSS::Time { 0, CSS::Time::Type::Ms };
  668. time_step_ms -= delay_ms;
  669. // "auto": For time-driven animations, equivalent to 0s.
  670. // https://www.w3.org/TR/2023/WD-css-animations-2-20230602/#valdef-animation-duration-auto
  671. auto used_duration = duration.value_or(CSS::Time { 0, CSS::Time::Type::S });
  672. auto added_progress = time_step_ms / used_duration.to_milliseconds();
  673. auto new_progress = progress.as_fraction() + added_progress;
  674. auto changed_iteration = false;
  675. if (new_progress >= 1) {
  676. if (iteration_count.has_value()) {
  677. if (iteration_count.value() <= 1) {
  678. progress = CSS::Percentage(100);
  679. return AnimationStepTransition::ActiveToAfter;
  680. }
  681. --iteration_count.value();
  682. changed_iteration = true;
  683. }
  684. ++current_iteration;
  685. new_progress = 0;
  686. }
  687. progress = CSS::Percentage(new_progress * 100);
  688. if (changed_iteration)
  689. return AnimationStepTransition::ActiveToActiveChangingTheIteration;
  690. return AnimationStepTransition::AfterToActive;
  691. }
  692. static ErrorOr<NonnullRefPtr<StyleValue>> interpolate_property(StyleValue const& from, StyleValue const& to, float delta)
  693. {
  694. if (from.type() != to.type()) {
  695. if (delta > 0.999f)
  696. return to;
  697. return from;
  698. }
  699. auto interpolate_raw = [delta = static_cast<double>(delta)](auto from, auto to) {
  700. return static_cast<RemoveCVReference<decltype(from)>>(static_cast<double>(from) + static_cast<double>(to - from) * delta);
  701. };
  702. switch (from.type()) {
  703. case StyleValue::Type::Angle:
  704. return AngleStyleValue::create(Angle::make_degrees(interpolate_raw(from.as_angle().angle().to_degrees(), to.as_angle().angle().to_degrees())));
  705. case StyleValue::Type::Color: {
  706. auto from_color = from.as_color().color();
  707. auto to_color = to.as_color().color();
  708. auto from_hsv = from_color.to_hsv();
  709. auto to_hsv = to_color.to_hsv();
  710. auto color = Color::from_hsv(
  711. interpolate_raw(from_hsv.hue, to_hsv.hue),
  712. interpolate_raw(from_hsv.saturation, to_hsv.saturation),
  713. interpolate_raw(from_hsv.value, to_hsv.value));
  714. color.set_alpha(interpolate_raw(from_color.alpha(), to_color.alpha()));
  715. return ColorStyleValue::create(color);
  716. }
  717. case StyleValue::Type::Integer:
  718. return IntegerStyleValue::create(interpolate_raw(from.as_integer().integer(), to.as_integer().integer()));
  719. case StyleValue::Type::Length: {
  720. auto& from_length = from.as_length().length();
  721. auto& to_length = to.as_length().length();
  722. return LengthStyleValue::create(Length(interpolate_raw(from_length.raw_value(), to_length.raw_value()), from_length.type()));
  723. }
  724. case StyleValue::Type::Number:
  725. return NumberStyleValue::create(interpolate_raw(from.as_number().number(), to.as_number().number()));
  726. case StyleValue::Type::Percentage:
  727. return PercentageStyleValue::create(Percentage(interpolate_raw(from.as_percentage().percentage().value(), to.as_percentage().percentage().value())));
  728. case StyleValue::Type::Position: {
  729. auto& from_position = from.as_position();
  730. auto& to_position = to.as_position();
  731. return PositionStyleValue::create(
  732. TRY(interpolate_property(from_position.edge_x(), to_position.edge_x(), delta)),
  733. TRY(interpolate_property(from_position.edge_y(), to_position.edge_y(), delta)));
  734. }
  735. case StyleValue::Type::Rect: {
  736. auto from_rect = from.as_rect().rect();
  737. auto to_rect = to.as_rect().rect();
  738. return RectStyleValue::create({
  739. Length(interpolate_raw(from_rect.top_edge.raw_value(), to_rect.top_edge.raw_value()), from_rect.top_edge.type()),
  740. Length(interpolate_raw(from_rect.right_edge.raw_value(), to_rect.right_edge.raw_value()), from_rect.right_edge.type()),
  741. Length(interpolate_raw(from_rect.bottom_edge.raw_value(), to_rect.bottom_edge.raw_value()), from_rect.bottom_edge.type()),
  742. Length(interpolate_raw(from_rect.left_edge.raw_value(), to_rect.left_edge.raw_value()), from_rect.left_edge.type()),
  743. });
  744. }
  745. case StyleValue::Type::Transformation: {
  746. auto& from_transform = from.as_transformation();
  747. auto& to_transform = to.as_transformation();
  748. if (from_transform.transform_function() != to_transform.transform_function())
  749. return from;
  750. auto from_input_values = from_transform.values();
  751. auto to_input_values = to_transform.values();
  752. if (from_input_values.size() != to_input_values.size())
  753. return from;
  754. StyleValueVector interpolated_values;
  755. interpolated_values.ensure_capacity(from_input_values.size());
  756. for (size_t i = 0; i < from_input_values.size(); ++i)
  757. interpolated_values.append(TRY(interpolate_property(*from_input_values[i], *to_input_values[i], delta)));
  758. return TransformationStyleValue::create(from_transform.transform_function(), move(interpolated_values));
  759. }
  760. case StyleValue::Type::ValueList: {
  761. auto& from_list = from.as_value_list();
  762. auto& to_list = to.as_value_list();
  763. if (from_list.size() != to_list.size())
  764. return from;
  765. StyleValueVector interpolated_values;
  766. interpolated_values.ensure_capacity(from_list.size());
  767. for (size_t i = 0; i < from_list.size(); ++i)
  768. interpolated_values.append(TRY(interpolate_property(from_list.values()[i], to_list.values()[i], delta)));
  769. return StyleValueList::create(move(interpolated_values), from_list.separator());
  770. }
  771. default:
  772. return from;
  773. }
  774. }
  775. bool StyleComputer::Animation::is_animating_backwards() const
  776. {
  777. return (direction == CSS::AnimationDirection::AlternateReverse && current_iteration % 2 == 1)
  778. || (direction == CSS::AnimationDirection::Alternate && current_iteration % 2 == 0)
  779. || direction == CSS::AnimationDirection::Reverse;
  780. }
  781. ErrorOr<void> StyleComputer::Animation::collect_into(StyleProperties& style_properties, RuleCache const& rule_cache) const
  782. {
  783. if (remaining_delay.to_milliseconds() != 0) {
  784. // If the fill mode is backwards or both, we'll pretend that the animation is started, but stuck at progress 0
  785. if (fill_mode != CSS::AnimationFillMode::Backwards && fill_mode != CSS::AnimationFillMode::Both)
  786. return {};
  787. }
  788. auto matching_keyframes = rule_cache.rules_by_animation_keyframes.get(name);
  789. if (!matching_keyframes.has_value())
  790. return {};
  791. auto& keyframes = matching_keyframes.value()->keyframes_by_key;
  792. auto output_progress = compute_output_progress(progress.as_fraction()) * 100.f;
  793. auto is_backwards = is_animating_backwards();
  794. auto key = static_cast<u64>(output_progress * AnimationKeyFrameKeyScaleFactor);
  795. auto matching_keyframe_it = is_backwards ? keyframes.find_smallest_not_below_iterator(key) : keyframes.find_largest_not_above_iterator(key);
  796. if (matching_keyframe_it.is_end()) {
  797. if constexpr (LIBWEB_CSS_ANIMATION_DEBUG) {
  798. dbgln(" Did not find any start keyframe for the current state ({}) :(", key);
  799. dbgln(" (have {} keyframes)", keyframes.size());
  800. for (auto it = keyframes.begin(); it != keyframes.end(); ++it)
  801. dbgln(" - {}", it.key());
  802. }
  803. return {};
  804. }
  805. auto keyframe_start = matching_keyframe_it.key();
  806. auto keyframe_values = *matching_keyframe_it;
  807. auto initial_keyframe_it = matching_keyframe_it;
  808. auto keyframe_end_it = is_backwards ? --matching_keyframe_it : ++matching_keyframe_it;
  809. if (keyframe_end_it.is_end())
  810. keyframe_end_it = initial_keyframe_it;
  811. auto keyframe_end = keyframe_end_it.key();
  812. auto keyframe_end_values = *keyframe_end_it;
  813. auto progress_in_keyframe = [&] {
  814. if (keyframe_start == keyframe_end)
  815. return is_backwards ? 1.f : 0.f;
  816. return is_backwards
  817. ? static_cast<float>(keyframe_start - key) / static_cast<float>(keyframe_start - keyframe_end)
  818. : static_cast<float>(key - keyframe_start) / static_cast<float>(keyframe_end - keyframe_start);
  819. }();
  820. auto valid_properties = 0;
  821. for (auto const& property : keyframe_values.resolved_properties) {
  822. if (property.has<Empty>())
  823. continue;
  824. valid_properties++;
  825. }
  826. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "Animation {} contains {} properties to interpolate, progress = {}%", name, valid_properties, progress_in_keyframe * 100);
  827. if (fill_mode == CSS::AnimationFillMode::Forwards || fill_mode == CSS::AnimationFillMode::Both) {
  828. if (!active_state_if_fill_forward)
  829. active_state_if_fill_forward = make<AnimationStateSnapshot>();
  830. }
  831. UnderlyingType<PropertyID> property_id_value = 0;
  832. for (auto const& property : keyframe_values.resolved_properties) {
  833. auto property_id = static_cast<PropertyID>(property_id_value++);
  834. if (property.has<Empty>())
  835. continue;
  836. auto resolve_property = [&](auto& property) {
  837. return property.visit(
  838. [](Empty) -> RefPtr<StyleValue const> { VERIFY_NOT_REACHED(); },
  839. [&](AnimationKeyFrameSet::ResolvedKeyFrame::UseInitial) {
  840. if (auto value = initial_state.state[to_underlying(property_id)])
  841. return value;
  842. auto value = style_properties.maybe_null_property(property_id);
  843. initial_state.state[to_underlying(property_id)] = value;
  844. return value;
  845. },
  846. [&](RefPtr<StyleValue const> value) { return value; });
  847. };
  848. auto resolved_start_property = resolve_property(property);
  849. auto const& end_property = keyframe_end_values.resolved_properties[to_underlying(property_id)];
  850. if (end_property.has<Empty>()) {
  851. if (resolved_start_property) {
  852. style_properties.set_property(property_id, resolved_start_property.release_nonnull());
  853. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "No end property for property {}, using {}", string_from_property_id(property_id), resolved_start_property->to_string());
  854. }
  855. continue;
  856. }
  857. auto resolved_end_property = resolve_property(end_property);
  858. if (!resolved_start_property || !resolved_end_property)
  859. continue;
  860. auto start = resolved_start_property.release_nonnull();
  861. auto end = resolved_end_property.release_nonnull();
  862. auto next_value = TRY(interpolate_property(*start, *end, progress_in_keyframe));
  863. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "Interpolated value for property {} at {}: {} -> {} = {}", string_from_property_id(property_id), progress_in_keyframe, start->to_string(), end->to_string(), next_value->to_string());
  864. style_properties.set_property(property_id, next_value);
  865. if (active_state_if_fill_forward)
  866. active_state_if_fill_forward->state[to_underlying(property_id)] = next_value;
  867. }
  868. return {};
  869. }
  870. bool StyleComputer::Animation::is_done() const
  871. {
  872. return progress.as_fraction() >= 0.9999 && iteration_count.has_value() && iteration_count.value() == 0;
  873. }
  874. // NOTE: Magic values from <https://www.w3.org/TR/css-easing-1/#valdef-cubic-bezier-easing-function-ease>
  875. static auto ease_timing_function = StyleComputer::AnimationTiming::CubicBezier { 0.25, 0.1, 0.25, 1.0 };
  876. static auto ease_in_timing_function = StyleComputer::AnimationTiming::CubicBezier { 0.42, 0.0, 1.0, 1.0 };
  877. static auto ease_out_timing_function = StyleComputer::AnimationTiming::CubicBezier { 0.0, 0.0, 0.58, 1.0 };
  878. static auto ease_in_out_timing_function = StyleComputer::AnimationTiming::CubicBezier { 0.42, 0.0, 0.58, 1.0 };
  879. float StyleComputer::Animation::compute_output_progress(float input_progress) const
  880. {
  881. auto output_progress = input_progress;
  882. auto going_forwards = true;
  883. switch (direction) {
  884. case AnimationDirection::Alternate:
  885. if (current_iteration % 2 == 0) {
  886. output_progress = 1.0f - output_progress;
  887. going_forwards = false;
  888. }
  889. break;
  890. case AnimationDirection::AlternateReverse:
  891. if (current_iteration % 2 == 1) {
  892. output_progress = 1.0f - output_progress;
  893. going_forwards = false;
  894. }
  895. break;
  896. case AnimationDirection::Normal:
  897. break;
  898. case AnimationDirection::Reverse:
  899. output_progress = 1.0f - output_progress;
  900. going_forwards = false;
  901. break;
  902. }
  903. if (remaining_delay.to_milliseconds() != 0)
  904. return output_progress;
  905. return timing_function.timing_function.visit(
  906. [&](AnimationTiming::Linear) { return output_progress; },
  907. [&](AnimationTiming::Steps const& steps) {
  908. auto before_flag = (current_state == AnimationState::Before && going_forwards) || (current_state == AnimationState::After && !going_forwards);
  909. auto progress_step = output_progress * static_cast<float>(steps.number_of_steps);
  910. auto current_step = floorf(progress_step);
  911. if (steps.jump_at_start)
  912. current_step += 1;
  913. if (before_flag && truncf(progress_step) == progress_step)
  914. current_step -= 1;
  915. if (output_progress >= 0 && current_step < 0)
  916. current_step = 0;
  917. size_t jumps;
  918. if (steps.jump_at_start ^ steps.jump_at_end)
  919. jumps = steps.number_of_steps;
  920. else if (steps.jump_at_start && steps.jump_at_end)
  921. jumps = steps.number_of_steps + 1;
  922. else
  923. jumps = steps.number_of_steps - 1;
  924. if (output_progress <= 1 && current_step > static_cast<float>(jumps))
  925. current_step = static_cast<float>(jumps);
  926. return current_step / static_cast<float>(steps.number_of_steps);
  927. },
  928. [&](AnimationTiming::CubicBezier const& bezier) {
  929. // Special cases first:
  930. if (bezier == AnimationTiming::CubicBezier { 0.0, 0.0, 1.0, 1.0 })
  931. return output_progress;
  932. // FIXME: This is quite inefficient on memory and CPU, find a better way to do this.
  933. auto sample = bezier.sample_around(static_cast<double>(output_progress));
  934. return static_cast<float>(sample.y);
  935. });
  936. }
  937. static double cubic_bezier_at(double x1, double x2, double t)
  938. {
  939. auto a = 1.0 - 3.0 * x2 + 3.0 * x1;
  940. auto b = 3.0 * x2 - 6.0 * x1;
  941. auto c = 3.0 * x1;
  942. auto t2 = t * t;
  943. auto t3 = t2 * t;
  944. return (a * t3) + (b * t2) + (c * t);
  945. }
  946. StyleComputer::AnimationTiming::CubicBezier::CachedSample StyleComputer::AnimationTiming::CubicBezier::sample_around(double x) const
  947. {
  948. x = clamp(x, 0, 1);
  949. auto solve = [&](auto t) {
  950. auto x = cubic_bezier_at(x1, x2, t);
  951. auto y = cubic_bezier_at(y1, y2, t);
  952. return CachedSample { x, y, t };
  953. };
  954. if (m_cached_x_samples.is_empty())
  955. m_cached_x_samples.append(solve(0.));
  956. size_t nearby_index = 0;
  957. if (auto found = binary_search(m_cached_x_samples, x, &nearby_index, [](auto x, auto& sample) {
  958. if (x > sample.x)
  959. return 1;
  960. if (x < sample.x)
  961. return -1;
  962. return 0;
  963. }))
  964. return *found;
  965. if (nearby_index == m_cached_x_samples.size() || nearby_index + 1 == m_cached_x_samples.size()) {
  966. // Produce more samples until we have enough.
  967. auto last_t = m_cached_x_samples.is_empty() ? 0 : m_cached_x_samples.last().t;
  968. auto last_x = m_cached_x_samples.is_empty() ? 0 : m_cached_x_samples.last().x;
  969. while (last_x <= x) {
  970. last_t += 1. / 60.;
  971. auto solution = solve(last_t);
  972. m_cached_x_samples.append(solution);
  973. last_x = solution.x;
  974. }
  975. if (auto found = binary_search(m_cached_x_samples, x, &nearby_index, [](auto x, auto& sample) {
  976. if (x > sample.x)
  977. return 1;
  978. if (x < sample.x)
  979. return -1;
  980. return 0;
  981. }))
  982. return *found;
  983. }
  984. // We have two samples on either side of the x value we want, so we can linearly interpolate between them.
  985. auto& sample1 = m_cached_x_samples[nearby_index];
  986. auto& sample2 = m_cached_x_samples[nearby_index + 1];
  987. auto factor = (x - sample1.x) / (sample2.x - sample1.x);
  988. return CachedSample {
  989. x,
  990. clamp(sample1.y + factor * (sample2.y - sample1.y), 0, 1),
  991. sample1.t + factor * (sample2.t - sample1.t),
  992. };
  993. }
  994. void StyleComputer::ensure_animation_timer() const
  995. {
  996. constexpr static auto timer_delay_ms = 1000 / 60;
  997. if (!m_animation_driver_timer) {
  998. m_animation_driver_timer = Platform::Timer::create_repeating(timer_delay_ms, [this] {
  999. // If we run out of animations, stop the timer - it'll turn back on the next time we have an active animation.
  1000. if (m_active_animations.is_empty()) {
  1001. m_animation_driver_timer->stop();
  1002. return;
  1003. }
  1004. HashTable<AnimationKey> animations_to_remove;
  1005. HashTable<DOM::Element*> owning_elements_to_invalidate;
  1006. for (auto& it : m_active_animations) {
  1007. if (!it.value->owning_element) {
  1008. // The element disappeared since we last ran, just discard the animation.
  1009. animations_to_remove.set(it.key);
  1010. continue;
  1011. }
  1012. auto transition = it.value->step(CSS::Time { timer_delay_ms, CSS::Time::Type::Ms });
  1013. owning_elements_to_invalidate.set(it.value->owning_element);
  1014. switch (transition) {
  1015. case AnimationStepTransition::NoTransition:
  1016. break;
  1017. case AnimationStepTransition::IdleOrBeforeToActive:
  1018. // FIXME: Dispatch `animationstart`.
  1019. break;
  1020. case AnimationStepTransition::IdleOrBeforeToAfter:
  1021. // FIXME: Dispatch `animationstart` then `animationend`.
  1022. m_finished_animations.set(it.key, move(it.value->active_state_if_fill_forward));
  1023. break;
  1024. case AnimationStepTransition::ActiveToBefore:
  1025. // FIXME: Dispatch `animationend`.
  1026. m_finished_animations.set(it.key, move(it.value->active_state_if_fill_forward));
  1027. break;
  1028. case AnimationStepTransition::ActiveToActiveChangingTheIteration:
  1029. // FIXME: Dispatch `animationiteration`.
  1030. break;
  1031. case AnimationStepTransition::ActiveToAfter:
  1032. // FIXME: Dispatch `animationend`.
  1033. m_finished_animations.set(it.key, move(it.value->active_state_if_fill_forward));
  1034. break;
  1035. case AnimationStepTransition::AfterToActive:
  1036. // FIXME: Dispatch `animationstart`.
  1037. break;
  1038. case AnimationStepTransition::AfterToBefore:
  1039. // FIXME: Dispatch `animationstart` then `animationend`.
  1040. m_finished_animations.set(it.key, move(it.value->active_state_if_fill_forward));
  1041. break;
  1042. case AnimationStepTransition::Cancelled:
  1043. // FIXME: Dispatch `animationcancel`.
  1044. m_finished_animations.set(it.key, nullptr);
  1045. break;
  1046. }
  1047. if (it.value->is_done())
  1048. animations_to_remove.set(it.key);
  1049. }
  1050. for (auto key : animations_to_remove)
  1051. m_active_animations.remove(key);
  1052. for (auto* element : owning_elements_to_invalidate)
  1053. element->set_needs_style_update(true);
  1054. });
  1055. }
  1056. m_animation_driver_timer->start();
  1057. }
  1058. // https://www.w3.org/TR/css-cascade/#cascading
  1059. ErrorOr<void> StyleComputer::compute_cascaded_values(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, bool& did_match_any_pseudo_element_rules, ComputeStyleMode mode) const
  1060. {
  1061. // First, we collect all the CSS rules whose selectors match `element`:
  1062. MatchingRuleSet matching_rule_set;
  1063. matching_rule_set.user_agent_rules = collect_matching_rules(element, CascadeOrigin::UserAgent, pseudo_element);
  1064. sort_matching_rules(matching_rule_set.user_agent_rules);
  1065. matching_rule_set.user_rules = collect_matching_rules(element, CascadeOrigin::User, pseudo_element);
  1066. sort_matching_rules(matching_rule_set.user_rules);
  1067. matching_rule_set.author_rules = collect_matching_rules(element, CascadeOrigin::Author, pseudo_element);
  1068. sort_matching_rules(matching_rule_set.author_rules);
  1069. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded) {
  1070. VERIFY(pseudo_element.has_value());
  1071. if (matching_rule_set.author_rules.is_empty() && matching_rule_set.user_rules.is_empty() && matching_rule_set.user_agent_rules.is_empty()) {
  1072. did_match_any_pseudo_element_rules = false;
  1073. return {};
  1074. }
  1075. did_match_any_pseudo_element_rules = true;
  1076. }
  1077. // Then we resolve all the CSS custom pr`operties ("variables") for this element:
  1078. TRY(cascade_custom_properties(element, pseudo_element, matching_rule_set.author_rules));
  1079. // Then we apply the declarations from the matched rules in cascade order:
  1080. // Normal user agent declarations
  1081. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::No);
  1082. // Normal user declarations
  1083. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_rules, CascadeOrigin::User, Important::No);
  1084. // Author presentational hints (NOTE: The spec doesn't say exactly how to prioritize these.)
  1085. if (!pseudo_element.has_value()) {
  1086. element.apply_presentational_hints(style);
  1087. // SVG presentation attributes are parsed as CSS values, so we need to handle potential custom properties here.
  1088. if (element.is_svg_element()) {
  1089. // FIXME: This is not very efficient, we should only resolve the custom properties that are actually used.
  1090. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  1091. auto property_id = (CSS::PropertyID)i;
  1092. auto& property = style.m_property_values[i];
  1093. if (property.has_value() && property->style->is_unresolved())
  1094. property->style = Parser::Parser::resolve_unresolved_style_value({}, Parser::ParsingContext { document() }, element, pseudo_element, property_id, property->style->as_unresolved());
  1095. }
  1096. }
  1097. }
  1098. // Normal author declarations
  1099. cascade_declarations(style, element, pseudo_element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::No);
  1100. // Animation declarations [css-animations-2]
  1101. auto get_animation_name = [&]() -> Optional<String> {
  1102. auto animation_name = style.maybe_null_property(PropertyID::AnimationName);
  1103. if (animation_name.is_null())
  1104. return OptionalNone {};
  1105. if (animation_name->is_string())
  1106. return animation_name->as_string().string_value();
  1107. return animation_name->to_string();
  1108. };
  1109. if (auto animation_name = get_animation_name(); animation_name.has_value()) {
  1110. if (auto source_declaration = style.property_source_declaration(PropertyID::AnimationName)) {
  1111. AnimationKey animation_key {
  1112. .source_declaration = source_declaration,
  1113. .element = &element,
  1114. };
  1115. if (auto finished_state = m_finished_animations.get(animation_key); finished_state.has_value()) {
  1116. // We've already finished going through this animation, so drop it from the active animations.
  1117. m_active_animations.remove(animation_key);
  1118. // If the animation's fill mode was set to forwards/both, we need to collect and use the final frame's styles.
  1119. if (*finished_state) {
  1120. auto& state = (*finished_state)->state;
  1121. for (size_t property_id_value = 0; property_id_value < state.size(); ++property_id_value) {
  1122. if (auto& property_value = state[property_id_value])
  1123. style.set_property(static_cast<PropertyID>(property_id_value), *property_value);
  1124. }
  1125. }
  1126. } else if (!animation_name->is_empty()) {
  1127. auto active_animation = m_active_animations.get(animation_key);
  1128. if (!active_animation.has_value()) {
  1129. // New animation!
  1130. Optional<CSS::Time> duration;
  1131. if (auto duration_value = style.maybe_null_property(PropertyID::AnimationDuration); duration_value) {
  1132. if (duration_value->is_time()) {
  1133. duration = duration_value->as_time().time();
  1134. } else if (duration_value->is_identifier() && duration_value->as_identifier().id() == ValueID::Auto) {
  1135. // We use empty optional to represent "auto".
  1136. duration = {};
  1137. }
  1138. }
  1139. CSS::Time delay { 0, CSS::Time::Type::S };
  1140. if (auto delay_value = style.maybe_null_property(PropertyID::AnimationDelay); delay_value && delay_value->is_time())
  1141. delay = delay_value->as_time().time();
  1142. Optional<size_t> iteration_count = 1;
  1143. if (auto iteration_count_value = style.maybe_null_property(PropertyID::AnimationIterationCount); iteration_count_value) {
  1144. if (iteration_count_value->is_identifier() && iteration_count_value->to_identifier() == ValueID::Infinite)
  1145. iteration_count = {};
  1146. else if (iteration_count_value->is_number())
  1147. iteration_count = static_cast<size_t>(iteration_count_value->as_number().number());
  1148. }
  1149. CSS::AnimationFillMode fill_mode { CSS::AnimationFillMode::None };
  1150. if (auto fill_mode_property = style.maybe_null_property(PropertyID::AnimationFillMode); fill_mode_property && fill_mode_property->is_identifier()) {
  1151. if (auto fill_mode_value = value_id_to_animation_fill_mode(fill_mode_property->to_identifier()); fill_mode_value.has_value())
  1152. fill_mode = *fill_mode_value;
  1153. }
  1154. CSS::AnimationDirection direction { CSS::AnimationDirection::Normal };
  1155. if (auto direction_property = style.maybe_null_property(PropertyID::AnimationDirection); direction_property && direction_property->is_identifier()) {
  1156. if (auto direction_value = value_id_to_animation_direction(direction_property->to_identifier()); direction_value.has_value())
  1157. direction = *direction_value;
  1158. }
  1159. AnimationTiming timing_function { ease_timing_function };
  1160. if (auto timing_property = style.maybe_null_property(PropertyID::AnimationTimingFunction); timing_property && timing_property->is_easing()) {
  1161. auto& easing_value = timing_property->as_easing();
  1162. switch (easing_value.easing_function()) {
  1163. case EasingFunction::Linear:
  1164. timing_function = AnimationTiming { AnimationTiming::Linear {} };
  1165. break;
  1166. case EasingFunction::Ease:
  1167. timing_function = AnimationTiming { ease_timing_function };
  1168. break;
  1169. case EasingFunction::EaseIn:
  1170. timing_function = AnimationTiming { ease_in_timing_function };
  1171. break;
  1172. case EasingFunction::EaseOut:
  1173. timing_function = AnimationTiming { ease_out_timing_function };
  1174. break;
  1175. case EasingFunction::EaseInOut:
  1176. timing_function = AnimationTiming { ease_in_out_timing_function };
  1177. break;
  1178. case EasingFunction::CubicBezier: {
  1179. auto values = easing_value.values();
  1180. timing_function = AnimationTiming {
  1181. AnimationTiming::CubicBezier {
  1182. values[0]->as_number().number(),
  1183. values[1]->as_number().number(),
  1184. values[2]->as_number().number(),
  1185. values[3]->as_number().number(),
  1186. },
  1187. };
  1188. break;
  1189. }
  1190. case EasingFunction::Steps: {
  1191. auto values = easing_value.values();
  1192. auto jump_at_start = false;
  1193. auto jump_at_end = true;
  1194. if (values.size() > 1) {
  1195. auto identifier = values[1]->to_identifier();
  1196. switch (identifier) {
  1197. case ValueID::JumpStart:
  1198. case ValueID::Start:
  1199. jump_at_start = true;
  1200. jump_at_end = false;
  1201. break;
  1202. case ValueID::JumpEnd:
  1203. case ValueID::End:
  1204. jump_at_start = false;
  1205. jump_at_end = true;
  1206. break;
  1207. case ValueID::JumpNone:
  1208. jump_at_start = false;
  1209. jump_at_end = false;
  1210. break;
  1211. default:
  1212. break;
  1213. }
  1214. }
  1215. timing_function = AnimationTiming { AnimationTiming::Steps {
  1216. .number_of_steps = static_cast<size_t>(max(values[0]->as_integer().integer(), !(jump_at_end && jump_at_start) ? 1 : 0)),
  1217. .jump_at_start = jump_at_start,
  1218. .jump_at_end = jump_at_end,
  1219. } };
  1220. break;
  1221. }
  1222. case EasingFunction::StepEnd:
  1223. timing_function = AnimationTiming { AnimationTiming::Steps {
  1224. .number_of_steps = 1,
  1225. .jump_at_start = false,
  1226. .jump_at_end = true,
  1227. } };
  1228. break;
  1229. case EasingFunction::StepStart:
  1230. timing_function = AnimationTiming { AnimationTiming::Steps {
  1231. .number_of_steps = 1,
  1232. .jump_at_start = true,
  1233. .jump_at_end = false,
  1234. } };
  1235. break;
  1236. }
  1237. }
  1238. auto animation = make<Animation>(Animation {
  1239. .name = animation_name.release_value(),
  1240. .duration = duration,
  1241. .delay = delay,
  1242. .iteration_count = iteration_count,
  1243. .timing_function = timing_function,
  1244. .direction = direction,
  1245. .fill_mode = fill_mode,
  1246. .owning_element = TRY(element.try_make_weak_ptr<DOM::Element>()),
  1247. .progress = CSS::Percentage(0),
  1248. .remaining_delay = delay,
  1249. });
  1250. active_animation = animation;
  1251. m_active_animations.set(animation_key, move(animation));
  1252. }
  1253. TRY((*active_animation)->collect_into(style, rule_cache_for_cascade_origin(CascadeOrigin::Author)));
  1254. } else {
  1255. m_active_animations.remove(animation_key);
  1256. }
  1257. }
  1258. if (!m_active_animations.is_empty())
  1259. ensure_animation_timer();
  1260. }
  1261. // Important author declarations
  1262. cascade_declarations(style, element, pseudo_element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::Yes);
  1263. // Important user declarations
  1264. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_rules, CascadeOrigin::User, Important::Yes);
  1265. // Important user agent declarations
  1266. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::Yes);
  1267. // FIXME: Transition declarations [css-transitions-1]
  1268. return {};
  1269. }
  1270. DOM::Element const* element_to_inherit_style_from(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  1271. {
  1272. // Pseudo-elements treat their originating element as their parent.
  1273. DOM::Element const* parent_element = nullptr;
  1274. if (pseudo_element.has_value()) {
  1275. parent_element = element;
  1276. } else if (element) {
  1277. parent_element = element->parent_or_shadow_host_element();
  1278. }
  1279. return parent_element;
  1280. }
  1281. NonnullRefPtr<StyleValue const> get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID property_id, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  1282. {
  1283. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1284. if (!parent_element || !parent_element->computed_css_values())
  1285. return property_initial_value(initial_value_context_realm, property_id);
  1286. return parent_element->computed_css_values()->property(property_id);
  1287. }
  1288. void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM::Element const* element, CSS::PropertyID property_id, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1289. {
  1290. // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue.
  1291. auto& value_slot = style.m_property_values[to_underlying(property_id)];
  1292. if (!value_slot.has_value()) {
  1293. if (is_inherited_property(property_id))
  1294. style.m_property_values[to_underlying(property_id)] = { { get_inherit_value(document().realm(), property_id, element, pseudo_element), nullptr } };
  1295. else
  1296. style.m_property_values[to_underlying(property_id)] = { { property_initial_value(document().realm(), property_id), nullptr } };
  1297. return;
  1298. }
  1299. if (value_slot->style->is_initial()) {
  1300. value_slot->style = property_initial_value(document().realm(), property_id);
  1301. return;
  1302. }
  1303. if (value_slot->style->is_inherit()) {
  1304. value_slot->style = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  1305. return;
  1306. }
  1307. // https://www.w3.org/TR/css-cascade-4/#inherit-initial
  1308. // If the cascaded value of a property is the unset keyword,
  1309. if (value_slot->style->is_unset()) {
  1310. if (is_inherited_property(property_id)) {
  1311. // then if it is an inherited property, this is treated as inherit,
  1312. value_slot->style = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  1313. } else {
  1314. // and if it is not, this is treated as initial.
  1315. value_slot->style = property_initial_value(document().realm(), property_id);
  1316. }
  1317. }
  1318. }
  1319. // https://www.w3.org/TR/css-cascade/#defaulting
  1320. void StyleComputer::compute_defaulted_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1321. {
  1322. // Walk the list of all known CSS properties and:
  1323. // - Add them to `style` if they are missing.
  1324. // - Resolve `inherit` and `initial` as needed.
  1325. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  1326. auto property_id = (CSS::PropertyID)i;
  1327. compute_defaulted_property_value(style, element, property_id, pseudo_element);
  1328. }
  1329. // https://www.w3.org/TR/css-color-4/#resolving-other-colors
  1330. // In the color property, the used value of currentcolor is the inherited value.
  1331. auto color = style.property(CSS::PropertyID::Color);
  1332. if (color->to_identifier() == CSS::ValueID::Currentcolor) {
  1333. color = get_inherit_value(document().realm(), CSS::PropertyID::Color, element, pseudo_element);
  1334. style.set_property(CSS::PropertyID::Color, color);
  1335. }
  1336. }
  1337. Length::FontMetrics StyleComputer::calculate_root_element_font_metrics(StyleProperties const& style) const
  1338. {
  1339. auto root_value = style.property(CSS::PropertyID::FontSize);
  1340. auto font_pixel_metrics = style.computed_font().pixel_metrics();
  1341. Length::FontMetrics font_metrics { m_default_font_metrics.font_size, font_pixel_metrics, CSSPixels::nearest_value_for(font_pixel_metrics.line_spacing()) };
  1342. font_metrics.font_size = root_value->as_length().length().to_px(viewport_rect(), font_metrics, font_metrics);
  1343. font_metrics.line_height = style.line_height(viewport_rect(), font_metrics, font_metrics);
  1344. return font_metrics;
  1345. }
  1346. RefPtr<Gfx::Font const> StyleComputer::find_matching_font_weight_ascending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive)
  1347. {
  1348. using Fn = AK::Function<bool(MatchingFontCandidate const&)>;
  1349. auto pred = inclusive ? Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight >= target_weight; })
  1350. : Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight > target_weight; });
  1351. auto it = find_if(candidates.begin(), candidates.end(), pred);
  1352. for (; it != candidates.end(); ++it) {
  1353. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1354. return found_font;
  1355. }
  1356. return {};
  1357. }
  1358. RefPtr<Gfx::Font const> StyleComputer::find_matching_font_weight_descending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive)
  1359. {
  1360. using Fn = AK::Function<bool(MatchingFontCandidate const&)>;
  1361. auto pred = inclusive ? Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight <= target_weight; })
  1362. : Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight < target_weight; });
  1363. auto it = find_if(candidates.rbegin(), candidates.rend(), pred);
  1364. for (; it != candidates.rend(); ++it) {
  1365. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1366. return found_font;
  1367. }
  1368. return {};
  1369. }
  1370. // Partial implementation of the font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  1371. // FIXME: This should be replaced by the full CSS font selection algorithm.
  1372. RefPtr<Gfx::Font const> StyleComputer::font_matching_algorithm(FontFaceKey const& key, float font_size_in_pt) const
  1373. {
  1374. // If a font family match occurs, the user agent assembles the set of font faces in that family and then
  1375. // narrows the set to a single face using other font properties in the order given below.
  1376. Vector<MatchingFontCandidate> matching_family_fonts;
  1377. for (auto const& font_key_and_loader : m_loaded_fonts) {
  1378. if (font_key_and_loader.key.family_name.equals_ignoring_ascii_case(key.family_name))
  1379. matching_family_fonts.empend(font_key_and_loader.key, font_key_and_loader.value.ptr());
  1380. }
  1381. Gfx::FontDatabase::the().for_each_typeface_with_family_name(key.family_name.to_string(), [&](Gfx::Typeface const& typeface) {
  1382. matching_family_fonts.empend(
  1383. FontFaceKey {
  1384. .family_name = typeface.family(),
  1385. .weight = static_cast<int>(typeface.weight()),
  1386. .slope = typeface.slope(),
  1387. },
  1388. &typeface);
  1389. });
  1390. quick_sort(matching_family_fonts, [](auto const& a, auto const& b) {
  1391. return a.key.weight < b.key.weight;
  1392. });
  1393. // FIXME: 1. font-stretch is tried first.
  1394. // FIXME: 2. font-style is tried next.
  1395. // We don't have complete support of italic and oblique fonts, so matching on font-style can be simplified to:
  1396. // If a matching slope is found, all faces which don't have that matching slope are excluded from the matching set.
  1397. auto style_it = find_if(matching_family_fonts.begin(), matching_family_fonts.end(),
  1398. [&](auto const& matching_font_candidate) { return matching_font_candidate.key.slope == key.slope; });
  1399. if (style_it != matching_family_fonts.end()) {
  1400. matching_family_fonts.remove_all_matching([&](auto const& matching_font_candidate) {
  1401. return matching_font_candidate.key.slope != key.slope;
  1402. });
  1403. }
  1404. // 3. font-weight is matched next.
  1405. // If the desired weight is inclusively between 400 and 500, weights greater than or equal to the target weight
  1406. // are checked in ascending order until 500 is hit and checked, followed by weights less than the target weight
  1407. // in descending order, followed by weights greater than 500, until a match is found.
  1408. if (key.weight >= 400 && key.weight <= 500) {
  1409. auto it = find_if(matching_family_fonts.begin(), matching_family_fonts.end(),
  1410. [&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight >= key.weight; });
  1411. for (; it != matching_family_fonts.end() && it->key.weight <= 500; ++it) {
  1412. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1413. return found_font;
  1414. }
  1415. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1416. return found_font;
  1417. for (; it != matching_family_fonts.end(); ++it) {
  1418. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1419. return found_font;
  1420. }
  1421. }
  1422. // If the desired weight is less than 400, weights less than or equal to the desired weight are checked in descending order
  1423. // followed by weights above the desired weight in ascending order until a match is found.
  1424. if (key.weight < 400) {
  1425. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, true))
  1426. return found_font;
  1427. if (auto found_font = find_matching_font_weight_ascending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1428. return found_font;
  1429. }
  1430. // If the desired weight is greater than 500, weights greater than or equal to the desired weight are checked in ascending order
  1431. // followed by weights below the desired weight in descending order until a match is found.
  1432. if (key.weight > 500) {
  1433. if (auto found_font = find_matching_font_weight_ascending(matching_family_fonts, key.weight, font_size_in_pt, true))
  1434. return found_font;
  1435. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1436. return found_font;
  1437. }
  1438. return {};
  1439. }
  1440. RefPtr<Gfx::Font const> StyleComputer::compute_font_for_style_values(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> 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) const
  1441. {
  1442. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1443. auto width = font_stretch.to_font_stretch_width();
  1444. auto weight = font_weight.to_font_weight();
  1445. bool bold = weight > Gfx::FontWeight::Regular;
  1446. // FIXME: Should be based on "user's default font size"
  1447. CSSPixels font_size_in_px = 16;
  1448. auto parent_line_height = parent_or_root_element_line_height(element, pseudo_element);
  1449. Gfx::FontPixelMetrics font_pixel_metrics;
  1450. if (parent_element && parent_element->computed_css_values())
  1451. font_pixel_metrics = parent_element->computed_css_values()->computed_font().pixel_metrics();
  1452. else
  1453. font_pixel_metrics = Platform::FontPlugin::the().default_font().pixel_metrics();
  1454. auto parent_font_size = [&]() -> CSSPixels {
  1455. if (!parent_element || !parent_element->computed_css_values())
  1456. return font_size_in_px;
  1457. auto value = parent_element->computed_css_values()->property(CSS::PropertyID::FontSize);
  1458. if (value->is_length()) {
  1459. auto length = value->as_length().length();
  1460. auto parent_line_height = parent_or_root_element_line_height(parent_element, {});
  1461. if (length.is_absolute() || length.is_relative()) {
  1462. Length::FontMetrics font_metrics { font_size_in_px, font_pixel_metrics, parent_line_height };
  1463. return length.to_px(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1464. }
  1465. }
  1466. return font_size_in_px;
  1467. };
  1468. Length::FontMetrics font_metrics { parent_font_size(), font_pixel_metrics, parent_line_height };
  1469. if (font_size.is_identifier()) {
  1470. // https://w3c.github.io/csswg-drafts/css-fonts/#absolute-size-mapping
  1471. auto get_absolute_size_mapping = [](Web::CSS::ValueID identifier) -> CSSPixelFraction {
  1472. switch (identifier) {
  1473. case CSS::ValueID::XxSmall:
  1474. return CSSPixels(3) / 5;
  1475. case CSS::ValueID::XSmall:
  1476. return CSSPixels(3) / 4;
  1477. case CSS::ValueID::Small:
  1478. return CSSPixels(8) / 9;
  1479. case CSS::ValueID::Medium:
  1480. return 1;
  1481. case CSS::ValueID::Large:
  1482. return CSSPixels(6) / 5;
  1483. case CSS::ValueID::XLarge:
  1484. return CSSPixels(3) / 2;
  1485. case CSS::ValueID::XxLarge:
  1486. return 2;
  1487. case CSS::ValueID::XxxLarge:
  1488. return 3;
  1489. case CSS::ValueID::Smaller:
  1490. return CSSPixels(4) / 5;
  1491. case CSS::ValueID::Larger:
  1492. return CSSPixels(5) / 4;
  1493. default:
  1494. return 1;
  1495. }
  1496. };
  1497. auto const identifier = static_cast<IdentifierStyleValue const&>(font_size).id();
  1498. if (identifier == ValueID::Math) {
  1499. auto math_scaling_factor = [&]() {
  1500. // https://w3c.github.io/mathml-core/#the-math-script-level-property
  1501. // If the specified value font-size is math then the computed value of font-size is obtained by multiplying
  1502. // the inherited value of font-size by a nonzero scale factor calculated by the following procedure:
  1503. // 1. Let A be the inherited math-depth value, B the computed math-depth value, C be 0.71 and S be 1.0
  1504. int inherited_math_depth = parent_element && parent_element->computed_css_values()
  1505. ? parent_element->computed_css_values()->math_depth()
  1506. : InitialValues::math_depth();
  1507. int computed_math_depth = math_depth;
  1508. auto size_ratio = 0.71;
  1509. auto scale = 1.0;
  1510. // 2. If A = B then return S.
  1511. bool invert_scale_factor = false;
  1512. if (inherited_math_depth == computed_math_depth) {
  1513. return scale;
  1514. }
  1515. // If B < A, swap A and B and set InvertScaleFactor to true.
  1516. else if (computed_math_depth < inherited_math_depth) {
  1517. AK::swap(inherited_math_depth, computed_math_depth);
  1518. invert_scale_factor = true;
  1519. }
  1520. // Otherwise B > A and set InvertScaleFactor to false.
  1521. else {
  1522. invert_scale_factor = false;
  1523. }
  1524. // 3. Let E be B - A > 0.
  1525. double e = (computed_math_depth - inherited_math_depth) > 0;
  1526. // FIXME: 4. If the inherited first available font has an OpenType MATH table:
  1527. // - If A ≤ 0 and B ≥ 2 then multiply S by scriptScriptPercentScaleDown and decrement E by 2.
  1528. // - Otherwise if A = 1 then multiply S by scriptScriptPercentScaleDown / scriptPercentScaleDown and decrement E by 1.
  1529. // - Otherwise if B = 1 then multiply S by scriptPercentScaleDown and decrement E by 1.
  1530. // 5. Multiply S by C^E.
  1531. scale *= AK::pow(size_ratio, e);
  1532. // 6. Return S if InvertScaleFactor is false and 1/S otherwise.
  1533. if (!invert_scale_factor)
  1534. return scale;
  1535. return 1.0 / scale;
  1536. };
  1537. font_size_in_px = parent_font_size().scale_by(math_scaling_factor());
  1538. } else {
  1539. // https://w3c.github.io/csswg-drafts/css-fonts/#valdef-font-size-relative-size
  1540. // TODO: If the parent element has a keyword font size in the absolute size keyword mapping table,
  1541. // larger may compute the font size to the next entry in the table,
  1542. // and smaller may compute the font size to the previous entry in the table.
  1543. if (identifier == CSS::ValueID::Smaller || identifier == CSS::ValueID::Larger) {
  1544. if (parent_element && parent_element->computed_css_values()) {
  1545. font_size_in_px = CSSPixels::nearest_value_for(parent_element->computed_css_values()->computed_font().pixel_metrics().size);
  1546. }
  1547. }
  1548. font_size_in_px *= get_absolute_size_mapping(identifier);
  1549. }
  1550. } else {
  1551. Length::ResolutionContext const length_resolution_context {
  1552. .viewport_rect = viewport_rect(),
  1553. .font_metrics = font_metrics,
  1554. .root_font_metrics = m_root_element_font_metrics,
  1555. };
  1556. Optional<Length> maybe_length;
  1557. if (font_size.is_percentage()) {
  1558. // Percentages refer to parent element's font size
  1559. maybe_length = Length::make_px(CSSPixels::nearest_value_for(font_size.as_percentage().percentage().as_fraction() * parent_font_size().to_double()));
  1560. } else if (font_size.is_length()) {
  1561. maybe_length = font_size.as_length().length();
  1562. } else if (font_size.is_calculated()) {
  1563. maybe_length = font_size.as_calculated().resolve_length(length_resolution_context);
  1564. }
  1565. if (maybe_length.has_value()) {
  1566. font_size_in_px = maybe_length.value().to_px(length_resolution_context);
  1567. }
  1568. }
  1569. auto slope = font_style.to_font_slope();
  1570. // FIXME: Implement the full font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  1571. // Note: This is modified by the find_font() lambda
  1572. FontSelector font_selector;
  1573. bool monospace = false;
  1574. float const font_size_in_pt = font_size_in_px * 0.75f;
  1575. auto find_font = [&](FlyString const& family) -> RefPtr<Gfx::Font const> {
  1576. font_selector = { family, font_size_in_pt, weight, width, slope };
  1577. FontFaceKey key {
  1578. .family_name = family,
  1579. .weight = weight,
  1580. .slope = slope,
  1581. };
  1582. if (auto it = m_loaded_fonts.find(key); it != m_loaded_fonts.end()) {
  1583. auto& loader = *it->value;
  1584. if (auto found_font = loader.font_with_point_size(font_size_in_pt))
  1585. return found_font;
  1586. }
  1587. if (auto found_font = m_font_cache.get(font_selector))
  1588. return found_font;
  1589. if (auto found_font = font_matching_algorithm(key, font_size_in_pt))
  1590. return found_font;
  1591. if (auto found_font = Gfx::FontDatabase::the().get(family, font_size_in_pt, weight, width, slope, Gfx::Font::AllowInexactSizeMatch::Yes))
  1592. return found_font;
  1593. return {};
  1594. };
  1595. auto find_generic_font = [&](ValueID font_id) -> RefPtr<Gfx::Font const> {
  1596. Platform::GenericFont generic_font {};
  1597. switch (font_id) {
  1598. case ValueID::Monospace:
  1599. case ValueID::UiMonospace:
  1600. generic_font = Platform::GenericFont::Monospace;
  1601. monospace = true;
  1602. break;
  1603. case ValueID::Serif:
  1604. generic_font = Platform::GenericFont::Serif;
  1605. break;
  1606. case ValueID::Fantasy:
  1607. generic_font = Platform::GenericFont::Fantasy;
  1608. break;
  1609. case ValueID::SansSerif:
  1610. generic_font = Platform::GenericFont::SansSerif;
  1611. break;
  1612. case ValueID::Cursive:
  1613. generic_font = Platform::GenericFont::Cursive;
  1614. break;
  1615. case ValueID::UiSerif:
  1616. generic_font = Platform::GenericFont::UiSerif;
  1617. break;
  1618. case ValueID::UiSansSerif:
  1619. generic_font = Platform::GenericFont::UiSansSerif;
  1620. break;
  1621. case ValueID::UiRounded:
  1622. generic_font = Platform::GenericFont::UiRounded;
  1623. break;
  1624. default:
  1625. return {};
  1626. }
  1627. return find_font(Platform::FontPlugin::the().generic_font_name(generic_font));
  1628. };
  1629. RefPtr<Gfx::Font const> found_font;
  1630. if (font_family.is_value_list()) {
  1631. auto const& family_list = static_cast<StyleValueList const&>(font_family).values();
  1632. for (auto const& family : family_list) {
  1633. if (family->is_identifier()) {
  1634. found_font = find_generic_font(family->to_identifier());
  1635. } else if (family->is_string()) {
  1636. found_font = find_font(family->as_string().string_value());
  1637. } else if (family->is_custom_ident()) {
  1638. found_font = find_font(family->as_custom_ident().custom_ident());
  1639. }
  1640. if (found_font)
  1641. break;
  1642. }
  1643. } else if (font_family.is_identifier()) {
  1644. found_font = find_generic_font(font_family.to_identifier());
  1645. } else if (font_family.is_string()) {
  1646. found_font = find_font(font_family.as_string().string_value());
  1647. } else if (font_family.is_custom_ident()) {
  1648. found_font = find_font(font_family.as_custom_ident().custom_ident());
  1649. }
  1650. if (!found_font) {
  1651. found_font = StyleProperties::font_fallback(monospace, bold);
  1652. if (found_font) {
  1653. if (auto scaled_fallback_font = found_font->with_size(font_size_in_pt))
  1654. found_font = scaled_fallback_font;
  1655. }
  1656. }
  1657. m_font_cache.set(font_selector, *found_font);
  1658. return found_font;
  1659. }
  1660. void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1661. {
  1662. // To compute the font, first ensure that we've defaulted the relevant CSS font properties.
  1663. // FIXME: This should be more sophisticated.
  1664. compute_defaulted_property_value(style, element, CSS::PropertyID::FontFamily, pseudo_element);
  1665. compute_defaulted_property_value(style, element, CSS::PropertyID::FontSize, pseudo_element);
  1666. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStretch, pseudo_element);
  1667. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStyle, pseudo_element);
  1668. compute_defaulted_property_value(style, element, CSS::PropertyID::FontWeight, pseudo_element);
  1669. compute_defaulted_property_value(style, element, CSS::PropertyID::LineHeight, pseudo_element);
  1670. auto font_family = style.property(CSS::PropertyID::FontFamily);
  1671. auto font_size = style.property(CSS::PropertyID::FontSize);
  1672. auto font_style = style.property(CSS::PropertyID::FontStyle);
  1673. auto font_weight = style.property(CSS::PropertyID::FontWeight);
  1674. auto font_stretch = style.property(CSS::PropertyID::FontStretch);
  1675. auto found_font = compute_font_for_style_values(element, pseudo_element, font_family, font_size, font_style, font_weight, font_stretch, style.math_depth());
  1676. style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(CSSPixels::nearest_value_for(found_font->pixel_size()))), nullptr);
  1677. style.set_property(CSS::PropertyID::FontWeight, NumberStyleValue::create(font_weight->to_font_weight()));
  1678. style.set_computed_font(found_font.release_nonnull());
  1679. if (element && is<HTML::HTMLHtmlElement>(*element)) {
  1680. const_cast<StyleComputer&>(*this).m_root_element_font_metrics = calculate_root_element_font_metrics(style);
  1681. }
  1682. }
  1683. Gfx::Font const& StyleComputer::initial_font() const
  1684. {
  1685. // FIXME: This is not correct.
  1686. return StyleProperties::font_fallback(false, false);
  1687. }
  1688. CSSPixels StyleComputer::parent_or_root_element_line_height(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1689. {
  1690. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1691. if (!parent_element)
  1692. return m_root_element_font_metrics.line_height;
  1693. auto const* computed_values = parent_element->computed_css_values();
  1694. if (!computed_values)
  1695. return m_root_element_font_metrics.line_height;
  1696. auto parent_font_pixel_metrics = computed_values->computed_font().pixel_metrics();
  1697. auto parent_font_size = computed_values->property(CSS::PropertyID::FontSize)->as_length().length();
  1698. // FIXME: Can the parent font size be non-absolute here?
  1699. auto parent_font_size_value = parent_font_size.is_absolute() ? parent_font_size.absolute_length_to_px() : m_root_element_font_metrics.font_size;
  1700. auto parent_parent_line_height = parent_or_root_element_line_height(parent_element, {});
  1701. Length::FontMetrics parent_font_metrics { parent_font_size_value, parent_font_pixel_metrics, parent_parent_line_height };
  1702. return computed_values->line_height(viewport_rect(), parent_font_metrics, m_root_element_font_metrics);
  1703. }
  1704. void StyleComputer::absolutize_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1705. {
  1706. auto parent_or_root_line_height = parent_or_root_element_line_height(element, pseudo_element);
  1707. auto font_pixel_metrics = style.computed_font().pixel_metrics();
  1708. Length::FontMetrics font_metrics { m_root_element_font_metrics.font_size, font_pixel_metrics, parent_or_root_line_height };
  1709. auto font_size = style.property(CSS::PropertyID::FontSize)->as_length().length().to_px(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1710. font_metrics.font_size = font_size;
  1711. // NOTE: Percentage line-height values are relative to the font-size of the element.
  1712. // We have to resolve them right away, so that the *computed* line-height is ready for inheritance.
  1713. // We can't simply absolutize *all* percentage values against the font size,
  1714. // because most percentages are relative to containing block metrics.
  1715. auto line_height_value_slot = style.m_property_values[to_underlying(CSS::PropertyID::LineHeight)].map([](auto& x) -> auto& { return x.style; });
  1716. if (line_height_value_slot.has_value() && (*line_height_value_slot)->is_percentage()) {
  1717. *line_height_value_slot = LengthStyleValue::create(
  1718. Length::make_px(CSSPixels::nearest_value_for(font_size * static_cast<double>((*line_height_value_slot)->as_percentage().percentage().as_fraction()))));
  1719. }
  1720. auto line_height = style.line_height(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1721. font_metrics.line_height = line_height;
  1722. // NOTE: line-height might be using lh which should be resolved against the parent line height (like we did here already)
  1723. if (line_height_value_slot.has_value() && (*line_height_value_slot)->is_length())
  1724. (*line_height_value_slot) = LengthStyleValue::create(Length::make_px(line_height));
  1725. for (size_t i = 0; i < style.m_property_values.size(); ++i) {
  1726. auto& value_slot = style.m_property_values[i];
  1727. if (!value_slot.has_value())
  1728. continue;
  1729. value_slot->style = value_slot->style->absolutized(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1730. }
  1731. }
  1732. enum class BoxTypeTransformation {
  1733. None,
  1734. Blockify,
  1735. Inlinify,
  1736. };
  1737. static BoxTypeTransformation required_box_type_transformation(StyleProperties const& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> const& pseudo_element)
  1738. {
  1739. // NOTE: We never blockify <br> elements. They are always inline.
  1740. // There is currently no way to express in CSS how a <br> element really behaves.
  1741. // Spec issue: https://github.com/whatwg/html/issues/2291
  1742. if (is<HTML::HTMLBRElement>(element))
  1743. return BoxTypeTransformation::None;
  1744. // Absolute positioning or floating an element blockifies the box’s display type. [CSS2]
  1745. if (style.position() == CSS::Position::Absolute || style.position() == CSS::Position::Fixed || style.float_() != CSS::Float::None)
  1746. return BoxTypeTransformation::Blockify;
  1747. // FIXME: Containment in a ruby container inlinifies the box’s display type, as described in [CSS-RUBY-1].
  1748. // NOTE: If we're computing style for a pseudo-element, the effective parent will be the originating element itself, not its parent.
  1749. auto const* parent = pseudo_element.has_value() ? &element : element.parent_element();
  1750. // A parent with a grid or flex display value blockifies the box’s display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
  1751. if (parent && parent->computed_css_values()) {
  1752. auto const& parent_display = parent->computed_css_values()->display();
  1753. if (parent_display.is_grid_inside() || parent_display.is_flex_inside())
  1754. return BoxTypeTransformation::Blockify;
  1755. }
  1756. return BoxTypeTransformation::None;
  1757. }
  1758. // https://drafts.csswg.org/css-display/#transformations
  1759. void StyleComputer::transform_box_type_if_needed(StyleProperties& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1760. {
  1761. // 2.7. Automatic Box Type Transformations
  1762. // Some layout effects require blockification or inlinification of the box type,
  1763. // which sets the box’s computed outer display type to block or inline (respectively).
  1764. // (This has no effect on display types that generate no box at all, such as none or contents.)
  1765. auto display = style.display();
  1766. if (display.is_none() || display.is_contents())
  1767. return;
  1768. auto new_display = display;
  1769. if (display.is_math_inside()) {
  1770. // https://w3c.github.io/mathml-core/#new-display-math-value
  1771. // For elements that are not MathML elements, if the specified value of display is inline math or block math
  1772. // then the computed value is block flow and inline flow respectively.
  1773. if (element.namespace_() != Namespace::MathML)
  1774. new_display = CSS::Display { display.outside(), CSS::DisplayInside::Flow };
  1775. // For the mtable element the computed value is block table and inline table respectively.
  1776. else if (element.tag_name().equals_ignoring_ascii_case("mtable"sv))
  1777. new_display = CSS::Display { display.outside(), CSS::DisplayInside::Table };
  1778. // For the mtr element, the computed value is table-row.
  1779. else if (element.tag_name().equals_ignoring_ascii_case("mtr"sv))
  1780. new_display = CSS::Display { CSS::DisplayInternal::TableRow };
  1781. // For the mtd element, the computed value is table-cell.
  1782. else if (element.tag_name().equals_ignoring_ascii_case("mtd"sv))
  1783. new_display = CSS::Display { CSS::DisplayInternal::TableCell };
  1784. }
  1785. switch (required_box_type_transformation(style, element, pseudo_element)) {
  1786. case BoxTypeTransformation::None:
  1787. break;
  1788. case BoxTypeTransformation::Blockify:
  1789. if (display.is_block_outside())
  1790. return;
  1791. // If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
  1792. if (display.is_internal()) {
  1793. new_display = CSS::Display::from_short(CSS::Display::Short::Block);
  1794. } else {
  1795. VERIFY(display.is_outside_and_inside());
  1796. // For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
  1797. // For consistency, a run-in flow-root box also blockifies to a block box.
  1798. if (display.is_inline_block()) {
  1799. new_display = CSS::Display { CSS::DisplayOutside::Block, CSS::DisplayInside::Flow, display.list_item() };
  1800. } else {
  1801. new_display = CSS::Display { CSS::DisplayOutside::Block, display.inside(), display.list_item() };
  1802. }
  1803. }
  1804. break;
  1805. case BoxTypeTransformation::Inlinify:
  1806. if (display.is_inline_outside()) {
  1807. // FIXME: If an inline box (inline flow) is inlinified, it recursively inlinifies all of its in-flow children,
  1808. // so that no block-level descendants break up the inline formatting context in which it participates.
  1809. if (display.is_flow_inside()) {
  1810. dbgln("FIXME: Inlinify inline box children recursively");
  1811. }
  1812. break;
  1813. }
  1814. if (display.is_internal()) {
  1815. // Inlinification has no effect on layout-internal boxes. (However, placement in such an inline context will typically cause them
  1816. // to be wrapped in an appropriately-typed anonymous inline-level box.)
  1817. } else {
  1818. VERIFY(display.is_outside_and_inside());
  1819. // If a block box (block flow) is inlinified, its inner display type is set to flow-root so that it remains a block container.
  1820. if (display.is_block_outside() && display.is_flow_inside()) {
  1821. new_display = CSS::Display { CSS::DisplayOutside::Inline, CSS::DisplayInside::FlowRoot, display.list_item() };
  1822. }
  1823. new_display = CSS::Display { CSS::DisplayOutside::Inline, display.inside(), display.list_item() };
  1824. }
  1825. break;
  1826. }
  1827. if (new_display != display)
  1828. style.set_property(CSS::PropertyID::Display, DisplayStyleValue::create(new_display), style.property_source_declaration(CSS::PropertyID::Display));
  1829. }
  1830. NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const
  1831. {
  1832. auto style = StyleProperties::create();
  1833. compute_math_depth(style, nullptr, {});
  1834. compute_font(style, nullptr, {});
  1835. compute_defaulted_values(style, nullptr, {});
  1836. absolutize_values(style, nullptr, {});
  1837. style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().width())), nullptr);
  1838. style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().height())), nullptr);
  1839. style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::Block)), nullptr);
  1840. return style;
  1841. }
  1842. ErrorOr<NonnullRefPtr<StyleProperties>> StyleComputer::compute_style(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1843. {
  1844. auto style = TRY(compute_style_impl(element, move(pseudo_element), ComputeStyleMode::Normal));
  1845. return style.release_nonnull();
  1846. }
  1847. ErrorOr<RefPtr<StyleProperties>> StyleComputer::compute_pseudo_element_style_if_needed(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1848. {
  1849. return compute_style_impl(element, move(pseudo_element), ComputeStyleMode::CreatePseudoElementStyleIfNeeded);
  1850. }
  1851. ErrorOr<RefPtr<StyleProperties>> StyleComputer::compute_style_impl(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, ComputeStyleMode mode) const
  1852. {
  1853. build_rule_cache_if_needed();
  1854. auto style = StyleProperties::create();
  1855. // 1. Perform the cascade. This produces the "specified style"
  1856. bool did_match_any_pseudo_element_rules = false;
  1857. TRY(compute_cascaded_values(style, element, pseudo_element, did_match_any_pseudo_element_rules, mode));
  1858. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded && !did_match_any_pseudo_element_rules)
  1859. return nullptr;
  1860. // 2. Compute the math-depth property, since that might affect the font-size
  1861. compute_math_depth(style, &element, pseudo_element);
  1862. // 3. Compute the font, since that may be needed for font-relative CSS units
  1863. compute_font(style, &element, pseudo_element);
  1864. // 4. Absolutize values, turning font/viewport relative lengths into absolute lengths
  1865. absolutize_values(style, &element, pseudo_element);
  1866. // 5. Default the values, applying inheritance and 'initial' as needed
  1867. compute_defaulted_values(style, &element, pseudo_element);
  1868. // 6. Run automatic box type transformations
  1869. transform_box_type_if_needed(style, element, pseudo_element);
  1870. return style;
  1871. }
  1872. void StyleComputer::build_rule_cache_if_needed() const
  1873. {
  1874. if (m_author_rule_cache && m_user_rule_cache && m_user_agent_rule_cache)
  1875. return;
  1876. const_cast<StyleComputer&>(*this).build_rule_cache();
  1877. }
  1878. NonnullOwnPtr<StyleComputer::RuleCache> StyleComputer::make_rule_cache_for_cascade_origin(CascadeOrigin cascade_origin)
  1879. {
  1880. auto rule_cache = make<RuleCache>();
  1881. size_t num_class_rules = 0;
  1882. size_t num_id_rules = 0;
  1883. size_t num_tag_name_rules = 0;
  1884. size_t num_pseudo_element_rules = 0;
  1885. Vector<MatchingRule> matching_rules;
  1886. size_t style_sheet_index = 0;
  1887. for_each_stylesheet(cascade_origin, [&](auto& sheet) {
  1888. size_t rule_index = 0;
  1889. sheet.for_each_effective_style_rule([&](auto const& rule) {
  1890. size_t selector_index = 0;
  1891. for (CSS::Selector const& selector : rule.selectors()) {
  1892. MatchingRule matching_rule {
  1893. &rule,
  1894. sheet,
  1895. style_sheet_index,
  1896. rule_index,
  1897. selector_index,
  1898. selector.specificity()
  1899. };
  1900. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  1901. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoElement) {
  1902. matching_rule.contains_pseudo_element = true;
  1903. ++num_pseudo_element_rules;
  1904. break;
  1905. }
  1906. }
  1907. bool added_to_bucket = false;
  1908. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  1909. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Id) {
  1910. rule_cache->rules_by_id.ensure(simple_selector.name()).append(move(matching_rule));
  1911. ++num_id_rules;
  1912. added_to_bucket = true;
  1913. break;
  1914. }
  1915. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Class) {
  1916. rule_cache->rules_by_class.ensure(simple_selector.name()).append(move(matching_rule));
  1917. ++num_class_rules;
  1918. added_to_bucket = true;
  1919. break;
  1920. }
  1921. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::TagName) {
  1922. rule_cache->rules_by_tag_name.ensure(simple_selector.qualified_name().name.lowercase_name).append(move(matching_rule));
  1923. ++num_tag_name_rules;
  1924. added_to_bucket = true;
  1925. break;
  1926. }
  1927. }
  1928. if (!added_to_bucket)
  1929. rule_cache->other_rules.append(move(matching_rule));
  1930. ++selector_index;
  1931. }
  1932. ++rule_index;
  1933. });
  1934. sheet.for_each_effective_keyframes_at_rule([&](CSSKeyframesRule const& rule) {
  1935. auto keyframe_set = make<AnimationKeyFrameSet>();
  1936. AnimationKeyFrameSet::ResolvedKeyFrame resolved_keyframe;
  1937. // Forwards pass, resolve all the user-specified keyframe properties.
  1938. for (auto const& keyframe : rule.keyframes()) {
  1939. auto key = static_cast<u64>(keyframe->key().value() * AnimationKeyFrameKeyScaleFactor);
  1940. auto keyframe_rule = keyframe->style();
  1941. if (!is<PropertyOwningCSSStyleDeclaration>(*keyframe_rule))
  1942. continue;
  1943. auto current_keyframe = resolved_keyframe;
  1944. auto& keyframe_style = static_cast<PropertyOwningCSSStyleDeclaration const&>(*keyframe_rule);
  1945. for (auto& property : keyframe_style.properties())
  1946. current_keyframe.resolved_properties[to_underlying(property.property_id)] = property.value;
  1947. resolved_keyframe = move(current_keyframe);
  1948. keyframe_set->keyframes_by_key.insert(key, resolved_keyframe);
  1949. }
  1950. // If there is no 'from' keyframe, make a synthetic one.
  1951. auto made_a_synthetic_from_keyframe = false;
  1952. if (!keyframe_set->keyframes_by_key.find(0)) {
  1953. keyframe_set->keyframes_by_key.insert(0, AnimationKeyFrameSet::ResolvedKeyFrame());
  1954. made_a_synthetic_from_keyframe = true;
  1955. }
  1956. // Backwards pass, resolve all the implied properties, go read <https://drafts.csswg.org/css-animations-2/#keyframe-processing> to see why.
  1957. auto first = true;
  1958. for (auto const& keyframe : rule.keyframes().in_reverse()) {
  1959. auto key = static_cast<u64>(keyframe->key().value() * AnimationKeyFrameKeyScaleFactor);
  1960. auto keyframe_rule = keyframe->style();
  1961. if (!is<PropertyOwningCSSStyleDeclaration>(*keyframe_rule))
  1962. continue;
  1963. // The last keyframe is already fully resolved.
  1964. if (first) {
  1965. first = false;
  1966. continue;
  1967. }
  1968. auto next_keyframe = resolved_keyframe;
  1969. auto& current_keyframes = *keyframe_set->keyframes_by_key.find(key);
  1970. for (auto it = next_keyframe.resolved_properties.begin(); !it.is_end(); ++it) {
  1971. auto& current_property = current_keyframes.resolved_properties[it.index()];
  1972. if (!current_property.has<Empty>() || it->has<Empty>())
  1973. continue;
  1974. if (key == 0)
  1975. current_property = AnimationKeyFrameSet::ResolvedKeyFrame::UseInitial();
  1976. else
  1977. current_property = *it;
  1978. }
  1979. resolved_keyframe = current_keyframes;
  1980. }
  1981. if (made_a_synthetic_from_keyframe && !first) {
  1982. auto next_keyframe = resolved_keyframe;
  1983. auto& current_keyframes = *keyframe_set->keyframes_by_key.find(0);
  1984. for (auto it = next_keyframe.resolved_properties.begin(); !it.is_end(); ++it) {
  1985. auto& current_property = current_keyframes.resolved_properties[it.index()];
  1986. if (!current_property.has<Empty>() || it->has<Empty>())
  1987. continue;
  1988. current_property = AnimationKeyFrameSet::ResolvedKeyFrame::UseInitial();
  1989. }
  1990. resolved_keyframe = current_keyframes;
  1991. }
  1992. if constexpr (LIBWEB_CSS_DEBUG) {
  1993. dbgln("Resolved keyframe set '{}' into {} keyframes:", rule.name(), keyframe_set->keyframes_by_key.size());
  1994. for (auto it = keyframe_set->keyframes_by_key.begin(); it != keyframe_set->keyframes_by_key.end(); ++it) {
  1995. size_t props = 0;
  1996. for (auto& entry : it->resolved_properties)
  1997. props += !entry.has<Empty>();
  1998. dbgln(" - keyframe {}: {} properties", it.key(), props);
  1999. }
  2000. }
  2001. rule_cache->rules_by_animation_keyframes.set(rule.name(), move(keyframe_set));
  2002. });
  2003. ++style_sheet_index;
  2004. });
  2005. if constexpr (LIBWEB_CSS_DEBUG) {
  2006. dbgln("Built rule cache!");
  2007. dbgln(" ID: {}", num_id_rules);
  2008. dbgln(" Class: {}", num_class_rules);
  2009. dbgln(" TagName: {}", num_tag_name_rules);
  2010. dbgln("PseudoElement: {}", num_pseudo_element_rules);
  2011. dbgln(" Other: {}", rule_cache->other_rules.size());
  2012. dbgln(" Total: {}", num_class_rules + num_id_rules + num_tag_name_rules + rule_cache->other_rules.size());
  2013. }
  2014. return rule_cache;
  2015. }
  2016. void StyleComputer::build_rule_cache()
  2017. {
  2018. // FIXME: How are we sometimes calculating style before the Document has a Page?
  2019. if (document().page()) {
  2020. if (auto user_style_source = document().page()->user_style(); user_style_source.has_value()) {
  2021. m_user_style_sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document()), user_style_source.value()));
  2022. }
  2023. }
  2024. m_author_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::Author);
  2025. m_user_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::User);
  2026. m_user_agent_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::UserAgent);
  2027. }
  2028. void StyleComputer::invalidate_rule_cache()
  2029. {
  2030. m_author_rule_cache = nullptr;
  2031. // NOTE: We could be smarter about keeping the user rule cache, and style sheet.
  2032. // Currently we are re-parsing the user style sheet every time we build the caches,
  2033. // as it may have changed.
  2034. m_user_rule_cache = nullptr;
  2035. m_user_style_sheet = nullptr;
  2036. // NOTE: It might not be necessary to throw away the UA rule cache.
  2037. // If we are sure that it's safe, we could keep it as an optimization.
  2038. m_user_agent_rule_cache = nullptr;
  2039. }
  2040. CSSPixelRect StyleComputer::viewport_rect() const
  2041. {
  2042. if (auto const navigable = document().navigable())
  2043. return navigable->viewport_rect();
  2044. return {};
  2045. }
  2046. void StyleComputer::did_load_font(FlyString const& family_name)
  2047. {
  2048. m_font_cache.did_load_font({}, family_name);
  2049. document().invalidate_style();
  2050. }
  2051. void StyleComputer::load_fonts_from_sheet(CSSStyleSheet const& sheet)
  2052. {
  2053. for (auto const& rule : static_cast<CSSStyleSheet const&>(sheet).rules()) {
  2054. if (!is<CSSFontFaceRule>(*rule))
  2055. continue;
  2056. auto const& font_face = static_cast<CSSFontFaceRule const&>(*rule).font_face();
  2057. if (font_face.sources().is_empty())
  2058. continue;
  2059. FontFaceKey key {
  2060. .family_name = font_face.font_family(),
  2061. .weight = font_face.weight().value_or(0),
  2062. .slope = font_face.slope().value_or(0),
  2063. };
  2064. if (m_loaded_fonts.contains(key))
  2065. continue;
  2066. Vector<AK::URL> urls;
  2067. for (auto& source : font_face.sources()) {
  2068. // FIXME: These should be loaded relative to the stylesheet URL instead of the document URL.
  2069. if (source.local_or_url.has<AK::URL>())
  2070. urls.append(m_document->parse_url(source.local_or_url.get<AK::URL>().to_deprecated_string()));
  2071. // FIXME: Handle local()
  2072. }
  2073. if (urls.is_empty())
  2074. continue;
  2075. auto loader = make<FontLoader>(const_cast<StyleComputer&>(*this), font_face.font_family(), move(urls));
  2076. const_cast<StyleComputer&>(*this).m_loaded_fonts.set(key, move(loader));
  2077. }
  2078. }
  2079. void StyleComputer::compute_math_depth(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  2080. {
  2081. // https://w3c.github.io/mathml-core/#propdef-math-depth
  2082. // First, ensure that the relevant CSS properties have been defaulted.
  2083. // FIXME: This should be more sophisticated.
  2084. compute_defaulted_property_value(style, element, CSS::PropertyID::MathDepth, pseudo_element);
  2085. compute_defaulted_property_value(style, element, CSS::PropertyID::MathStyle, pseudo_element);
  2086. auto inherited_math_depth = [&]() {
  2087. if (!element || !element->parent_element())
  2088. return InitialValues::math_depth();
  2089. return element->parent_element()->computed_css_values()->math_depth();
  2090. };
  2091. auto value = style.property(CSS::PropertyID::MathDepth);
  2092. if (!value->is_math_depth()) {
  2093. style.set_math_depth(inherited_math_depth());
  2094. return;
  2095. }
  2096. auto& math_depth = value->as_math_depth();
  2097. auto resolve_integer = [&](StyleValue const& integer_value) {
  2098. if (integer_value.is_integer())
  2099. return integer_value.as_integer().integer();
  2100. if (integer_value.is_calculated())
  2101. return integer_value.as_calculated().resolve_integer().value();
  2102. VERIFY_NOT_REACHED();
  2103. };
  2104. // The computed value of the math-depth value is determined as follows:
  2105. // - If the specified value of math-depth is auto-add and the inherited value of math-style is compact
  2106. // then the computed value of math-depth of the element is its inherited value plus one.
  2107. if (math_depth.is_auto_add() && style.property(CSS::PropertyID::MathStyle)->to_identifier() == CSS::ValueID::Compact) {
  2108. style.set_math_depth(inherited_math_depth() + 1);
  2109. return;
  2110. }
  2111. // - If the specified value of math-depth is of the form add(<integer>) then the computed value of
  2112. // math-depth of the element is its inherited value plus the specified integer.
  2113. if (math_depth.is_add()) {
  2114. style.set_math_depth(inherited_math_depth() + resolve_integer(*math_depth.integer_value()));
  2115. return;
  2116. }
  2117. // - If the specified value of math-depth is of the form <integer> then the computed value of math-depth
  2118. // of the element is the specified integer.
  2119. if (math_depth.is_integer()) {
  2120. style.set_math_depth(resolve_integer(*math_depth.integer_value()));
  2121. return;
  2122. }
  2123. // - Otherwise, the computed value of math-depth of the element is the inherited one.
  2124. style.set_math_depth(inherited_math_depth());
  2125. }
  2126. }