StyleComputer.cpp 118 KB

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