StyleComputer.cpp 120 KB

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