StyleComputer.cpp 131 KB

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