StyleComputer.cpp 116 KB

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