StyleComputer.cpp 122 KB

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