StyleComputer.cpp 113 KB

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