StyleComputer.cpp 114 KB

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