StyleComputer.cpp 122 KB

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