StyleComputer.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <LibGfx/Font.h>
  12. #include <LibGfx/FontDatabase.h>
  13. #include <LibGfx/FontStyleMapping.h>
  14. #include <LibWeb/CSS/CSSStyleRule.h>
  15. #include <LibWeb/CSS/Parser/Parser.h>
  16. #include <LibWeb/CSS/SelectorEngine.h>
  17. #include <LibWeb/CSS/StyleComputer.h>
  18. #include <LibWeb/CSS/StyleSheet.h>
  19. #include <LibWeb/DOM/Document.h>
  20. #include <LibWeb/DOM/Element.h>
  21. #include <LibWeb/FontCache.h>
  22. #include <stdio.h>
  23. namespace Web::CSS {
  24. StyleComputer::StyleComputer(DOM::Document& document)
  25. : m_document(document)
  26. {
  27. }
  28. StyleComputer::~StyleComputer()
  29. {
  30. }
  31. static StyleSheet& default_stylesheet()
  32. {
  33. static StyleSheet* sheet;
  34. if (!sheet) {
  35. extern char const default_stylesheet_source[];
  36. String css = default_stylesheet_source;
  37. sheet = parse_css(CSS::ParsingContext(), css).leak_ref();
  38. }
  39. return *sheet;
  40. }
  41. static StyleSheet& quirks_mode_stylesheet()
  42. {
  43. static StyleSheet* sheet;
  44. if (!sheet) {
  45. extern char const quirks_mode_stylesheet_source[];
  46. String css = quirks_mode_stylesheet_source;
  47. sheet = parse_css(CSS::ParsingContext(), css).leak_ref();
  48. }
  49. return *sheet;
  50. }
  51. template<typename Callback>
  52. void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const
  53. {
  54. if (cascade_origin == CascadeOrigin::UserAgent) {
  55. callback(default_stylesheet());
  56. if (document().in_quirks_mode())
  57. callback(quirks_mode_stylesheet());
  58. }
  59. if (cascade_origin == CascadeOrigin::Author) {
  60. for (auto const& sheet : document().style_sheets().sheets()) {
  61. callback(sheet);
  62. }
  63. }
  64. }
  65. Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin cascade_origin, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  66. {
  67. if (cascade_origin == CascadeOrigin::Author) {
  68. // FIXME: Cache pseudo-element rules and look at only those if pseudo_element is set.
  69. Vector<MatchingRule> rules_to_run;
  70. for (auto const& class_name : element.class_names()) {
  71. if (auto it = m_rule_cache->rules_by_class.find(class_name); it != m_rule_cache->rules_by_class.end())
  72. rules_to_run.extend(it->value);
  73. }
  74. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null()) {
  75. if (auto it = m_rule_cache->rules_by_id.find(id); it != m_rule_cache->rules_by_id.end())
  76. rules_to_run.extend(it->value);
  77. }
  78. if (auto it = m_rule_cache->rules_by_tag_name.find(element.local_name()); it != m_rule_cache->rules_by_tag_name.end())
  79. rules_to_run.extend(it->value);
  80. rules_to_run.extend(m_rule_cache->other_rules);
  81. Vector<MatchingRule> matching_rules;
  82. for (auto const& rule_to_run : rules_to_run) {
  83. auto const& selector = rule_to_run.rule->selectors()[rule_to_run.selector_index];
  84. if (SelectorEngine::matches(selector, element, pseudo_element))
  85. matching_rules.append(rule_to_run);
  86. }
  87. return matching_rules;
  88. }
  89. Vector<MatchingRule> matching_rules;
  90. size_t style_sheet_index = 0;
  91. for_each_stylesheet(cascade_origin, [&](auto& sheet) {
  92. size_t rule_index = 0;
  93. static_cast<CSSStyleSheet const&>(sheet).for_each_effective_style_rule([&](auto const& rule) {
  94. size_t selector_index = 0;
  95. for (auto& selector : rule.selectors()) {
  96. if (SelectorEngine::matches(selector, element, pseudo_element)) {
  97. matching_rules.append({ rule, style_sheet_index, rule_index, selector_index, selector.specificity() });
  98. break;
  99. }
  100. ++selector_index;
  101. }
  102. ++rule_index;
  103. });
  104. ++style_sheet_index;
  105. });
  106. return matching_rules;
  107. }
  108. static void sort_matching_rules(Vector<MatchingRule>& matching_rules)
  109. {
  110. quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) {
  111. auto const& a_selector = a.rule->selectors()[a.selector_index];
  112. auto const& b_selector = b.rule->selectors()[b.selector_index];
  113. auto a_specificity = a_selector.specificity();
  114. auto b_specificity = b_selector.specificity();
  115. if (a_selector.specificity() == b_selector.specificity()) {
  116. if (a.style_sheet_index == b.style_sheet_index)
  117. return a.rule_index < b.rule_index;
  118. return a.style_sheet_index < b.style_sheet_index;
  119. }
  120. return a_specificity < b_specificity;
  121. });
  122. }
  123. enum class Edge {
  124. Top,
  125. Right,
  126. Bottom,
  127. Left,
  128. All,
  129. };
  130. static bool contains(Edge a, Edge b)
  131. {
  132. return a == b || b == Edge::All;
  133. }
  134. static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document)
  135. {
  136. auto assign_edge_values = [&style](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
  137. if (values.size() == 4) {
  138. style.set_property(top_property, values[0]);
  139. style.set_property(right_property, values[1]);
  140. style.set_property(bottom_property, values[2]);
  141. style.set_property(left_property, values[3]);
  142. } else if (values.size() == 3) {
  143. style.set_property(top_property, values[0]);
  144. style.set_property(right_property, values[1]);
  145. style.set_property(bottom_property, values[2]);
  146. style.set_property(left_property, values[1]);
  147. } else if (values.size() == 2) {
  148. style.set_property(top_property, values[0]);
  149. style.set_property(right_property, values[1]);
  150. style.set_property(bottom_property, values[0]);
  151. style.set_property(left_property, values[1]);
  152. } else if (values.size() == 1) {
  153. style.set_property(top_property, values[0]);
  154. style.set_property(right_property, values[0]);
  155. style.set_property(bottom_property, values[0]);
  156. style.set_property(left_property, values[0]);
  157. }
  158. };
  159. if (property_id == CSS::PropertyID::TextDecoration) {
  160. if (value.is_text_decoration()) {
  161. auto const& text_decoration = value.as_text_decoration();
  162. style.set_property(CSS::PropertyID::TextDecorationLine, text_decoration.line());
  163. style.set_property(CSS::PropertyID::TextDecorationStyle, text_decoration.style());
  164. style.set_property(CSS::PropertyID::TextDecorationColor, text_decoration.color());
  165. return;
  166. }
  167. style.set_property(CSS::PropertyID::TextDecorationLine, value);
  168. style.set_property(CSS::PropertyID::TextDecorationStyle, value);
  169. style.set_property(CSS::PropertyID::TextDecorationColor, value);
  170. return;
  171. }
  172. if (property_id == CSS::PropertyID::Overflow) {
  173. if (value.is_overflow()) {
  174. auto const& overflow = value.as_overflow();
  175. style.set_property(CSS::PropertyID::OverflowX, overflow.overflow_x());
  176. style.set_property(CSS::PropertyID::OverflowY, overflow.overflow_y());
  177. return;
  178. }
  179. style.set_property(CSS::PropertyID::OverflowX, value);
  180. style.set_property(CSS::PropertyID::OverflowY, value);
  181. return;
  182. }
  183. if (property_id == CSS::PropertyID::Border) {
  184. set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document);
  185. set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document);
  186. set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document);
  187. set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document);
  188. // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands
  189. return;
  190. }
  191. if (property_id == CSS::PropertyID::BorderRadius) {
  192. if (value.is_value_list()) {
  193. auto const& values_list = value.as_value_list();
  194. assign_edge_values(PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius, values_list.values());
  195. return;
  196. }
  197. style.set_property(CSS::PropertyID::BorderTopLeftRadius, value);
  198. style.set_property(CSS::PropertyID::BorderTopRightRadius, value);
  199. style.set_property(CSS::PropertyID::BorderBottomRightRadius, value);
  200. style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value);
  201. return;
  202. }
  203. if (property_id == CSS::PropertyID::BorderTop
  204. || property_id == CSS::PropertyID::BorderRight
  205. || property_id == CSS::PropertyID::BorderBottom
  206. || property_id == CSS::PropertyID::BorderLeft) {
  207. Edge edge = Edge::All;
  208. switch (property_id) {
  209. case CSS::PropertyID::BorderTop:
  210. edge = Edge::Top;
  211. break;
  212. case CSS::PropertyID::BorderRight:
  213. edge = Edge::Right;
  214. break;
  215. case CSS::PropertyID::BorderBottom:
  216. edge = Edge::Bottom;
  217. break;
  218. case CSS::PropertyID::BorderLeft:
  219. edge = Edge::Left;
  220. break;
  221. default:
  222. break;
  223. }
  224. if (value.is_border()) {
  225. auto const& border = value.as_border();
  226. if (contains(Edge::Top, edge)) {
  227. style.set_property(PropertyID::BorderTopWidth, border.border_width());
  228. style.set_property(PropertyID::BorderTopStyle, border.border_style());
  229. style.set_property(PropertyID::BorderTopColor, border.border_color());
  230. }
  231. if (contains(Edge::Right, edge)) {
  232. style.set_property(PropertyID::BorderRightWidth, border.border_width());
  233. style.set_property(PropertyID::BorderRightStyle, border.border_style());
  234. style.set_property(PropertyID::BorderRightColor, border.border_color());
  235. }
  236. if (contains(Edge::Bottom, edge)) {
  237. style.set_property(PropertyID::BorderBottomWidth, border.border_width());
  238. style.set_property(PropertyID::BorderBottomStyle, border.border_style());
  239. style.set_property(PropertyID::BorderBottomColor, border.border_color());
  240. }
  241. if (contains(Edge::Left, edge)) {
  242. style.set_property(PropertyID::BorderLeftWidth, border.border_width());
  243. style.set_property(PropertyID::BorderLeftStyle, border.border_style());
  244. style.set_property(PropertyID::BorderLeftColor, border.border_color());
  245. }
  246. return;
  247. }
  248. return;
  249. }
  250. if (property_id == CSS::PropertyID::BorderStyle) {
  251. if (value.is_value_list()) {
  252. auto const& values_list = value.as_value_list();
  253. assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values());
  254. return;
  255. }
  256. style.set_property(CSS::PropertyID::BorderTopStyle, value);
  257. style.set_property(CSS::PropertyID::BorderRightStyle, value);
  258. style.set_property(CSS::PropertyID::BorderBottomStyle, value);
  259. style.set_property(CSS::PropertyID::BorderLeftStyle, value);
  260. return;
  261. }
  262. if (property_id == CSS::PropertyID::BorderWidth) {
  263. if (value.is_value_list()) {
  264. auto const& values_list = value.as_value_list();
  265. assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values());
  266. return;
  267. }
  268. style.set_property(CSS::PropertyID::BorderTopWidth, value);
  269. style.set_property(CSS::PropertyID::BorderRightWidth, value);
  270. style.set_property(CSS::PropertyID::BorderBottomWidth, value);
  271. style.set_property(CSS::PropertyID::BorderLeftWidth, value);
  272. return;
  273. }
  274. if (property_id == CSS::PropertyID::BorderColor) {
  275. if (value.is_value_list()) {
  276. auto const& values_list = value.as_value_list();
  277. assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values());
  278. return;
  279. }
  280. style.set_property(CSS::PropertyID::BorderTopColor, value);
  281. style.set_property(CSS::PropertyID::BorderRightColor, value);
  282. style.set_property(CSS::PropertyID::BorderBottomColor, value);
  283. style.set_property(CSS::PropertyID::BorderLeftColor, value);
  284. return;
  285. }
  286. if (property_id == CSS::PropertyID::Background) {
  287. if (value.is_background()) {
  288. auto const& background = value.as_background();
  289. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, background.color(), document);
  290. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, background.image(), document);
  291. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, background.position(), document);
  292. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, background.size(), document);
  293. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, background.repeat(), document);
  294. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, background.attachment(), document);
  295. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, background.origin(), document);
  296. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, background.clip(), document);
  297. return;
  298. }
  299. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, value, document);
  300. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document);
  301. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, value, document);
  302. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, value, document);
  303. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document);
  304. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, value, document);
  305. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, value, document);
  306. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, value, document);
  307. return;
  308. }
  309. if (property_id == CSS::PropertyID::Margin) {
  310. if (value.is_value_list()) {
  311. auto const& values_list = value.as_value_list();
  312. assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values());
  313. return;
  314. }
  315. style.set_property(CSS::PropertyID::MarginTop, value);
  316. style.set_property(CSS::PropertyID::MarginRight, value);
  317. style.set_property(CSS::PropertyID::MarginBottom, value);
  318. style.set_property(CSS::PropertyID::MarginLeft, value);
  319. return;
  320. }
  321. if (property_id == CSS::PropertyID::Padding) {
  322. if (value.is_value_list()) {
  323. auto const& values_list = value.as_value_list();
  324. assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values());
  325. return;
  326. }
  327. style.set_property(CSS::PropertyID::PaddingTop, value);
  328. style.set_property(CSS::PropertyID::PaddingRight, value);
  329. style.set_property(CSS::PropertyID::PaddingBottom, value);
  330. style.set_property(CSS::PropertyID::PaddingLeft, value);
  331. return;
  332. }
  333. if (property_id == CSS::PropertyID::ListStyle) {
  334. if (value.is_list_style()) {
  335. auto const& list_style = value.as_list_style();
  336. style.set_property(CSS::PropertyID::ListStylePosition, list_style.position());
  337. style.set_property(CSS::PropertyID::ListStyleImage, list_style.image());
  338. style.set_property(CSS::PropertyID::ListStyleType, list_style.style_type());
  339. return;
  340. }
  341. style.set_property(CSS::PropertyID::ListStylePosition, value);
  342. style.set_property(CSS::PropertyID::ListStyleImage, value);
  343. style.set_property(CSS::PropertyID::ListStyleType, value);
  344. return;
  345. }
  346. if (property_id == CSS::PropertyID::Font) {
  347. if (value.is_font()) {
  348. auto const& font_shorthand = value.as_font();
  349. style.set_property(CSS::PropertyID::FontSize, font_shorthand.font_size());
  350. style.set_property(CSS::PropertyID::FontFamily, font_shorthand.font_families());
  351. style.set_property(CSS::PropertyID::FontStyle, font_shorthand.font_style());
  352. style.set_property(CSS::PropertyID::FontWeight, font_shorthand.font_weight());
  353. style.set_property(CSS::PropertyID::LineHeight, font_shorthand.line_height());
  354. // FIXME: Implement font-stretch and font-variant
  355. return;
  356. }
  357. style.set_property(CSS::PropertyID::FontSize, value);
  358. style.set_property(CSS::PropertyID::FontFamily, value);
  359. style.set_property(CSS::PropertyID::FontStyle, value);
  360. style.set_property(CSS::PropertyID::FontWeight, value);
  361. style.set_property(CSS::PropertyID::LineHeight, value);
  362. // FIXME: Implement font-stretch and font-variant
  363. return;
  364. }
  365. if (property_id == CSS::PropertyID::Flex) {
  366. if (value.is_flex()) {
  367. auto const& flex = value.as_flex();
  368. style.set_property(CSS::PropertyID::FlexGrow, flex.grow());
  369. style.set_property(CSS::PropertyID::FlexShrink, flex.shrink());
  370. style.set_property(CSS::PropertyID::FlexBasis, flex.basis());
  371. return;
  372. }
  373. style.set_property(CSS::PropertyID::FlexGrow, value);
  374. style.set_property(CSS::PropertyID::FlexShrink, value);
  375. style.set_property(CSS::PropertyID::FlexBasis, value);
  376. return;
  377. }
  378. if (property_id == CSS::PropertyID::FlexFlow) {
  379. if (value.is_flex_flow()) {
  380. auto const& flex_flow = value.as_flex_flow();
  381. style.set_property(CSS::PropertyID::FlexDirection, flex_flow.flex_direction());
  382. style.set_property(CSS::PropertyID::FlexWrap, flex_flow.flex_wrap());
  383. return;
  384. }
  385. style.set_property(CSS::PropertyID::FlexDirection, value);
  386. style.set_property(CSS::PropertyID::FlexWrap, value);
  387. return;
  388. }
  389. style.set_property(property_id, value);
  390. }
  391. bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView property_name, HashMap<String, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<StyleComponentValueRule> const& source, Vector<StyleComponentValueRule>& dest, size_t source_start_index, HashMap<String, StyleProperty const*> const& custom_properties) const
  392. {
  393. // FIXME: Do this better!
  394. // We build a copy of the tree of StyleComponentValueRules, with all var()s replaced with their contents.
  395. // This is a very naive solution, and we could do better if the CSS Parser could accept tokens one at a time.
  396. // Arbitrary large value chosen to avoid the billion-laughs attack.
  397. // https://www.w3.org/TR/css-variables-1/#long-variables
  398. const size_t MAX_VALUE_COUNT = 16384;
  399. if (source.size() + dest.size() > MAX_VALUE_COUNT) {
  400. dbgln("Stopped expanding CSS variables: maximum length reached.");
  401. return false;
  402. }
  403. auto get_custom_property = [&custom_properties](auto& name) -> RefPtr<StyleValue> {
  404. auto it = custom_properties.find(name);
  405. if (it != custom_properties.end())
  406. return it->value->value;
  407. return nullptr;
  408. };
  409. auto get_dependency_node = [&](auto name) -> NonnullRefPtr<PropertyDependencyNode> {
  410. if (auto existing = dependencies.get(name); existing.has_value())
  411. return *existing.value();
  412. auto new_node = PropertyDependencyNode::create(name);
  413. dependencies.set(name, new_node);
  414. return new_node;
  415. };
  416. for (size_t source_index = source_start_index; source_index < source.size(); source_index++) {
  417. auto const& value = source[source_index];
  418. if (value.is_function()) {
  419. if (value.function().name().equals_ignoring_case("var"sv)) {
  420. auto const& var_contents = value.function().values();
  421. if (var_contents.is_empty())
  422. return false;
  423. auto const& custom_property_name_token = var_contents.first();
  424. if (!custom_property_name_token.is(Token::Type::Ident))
  425. return false;
  426. auto custom_property_name = custom_property_name_token.token().ident();
  427. if (!custom_property_name.starts_with("--"))
  428. return false;
  429. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  430. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  431. // but rebuilding it every time.
  432. if (custom_property_name == property_name)
  433. return false;
  434. auto parent = get_dependency_node(property_name);
  435. auto child = get_dependency_node(custom_property_name);
  436. parent->add_child(child);
  437. if (parent->has_cycles())
  438. return false;
  439. if (auto custom_property_value = get_custom_property(custom_property_name)) {
  440. VERIFY(custom_property_value->is_unresolved());
  441. if (!expand_unresolved_values(element, custom_property_name, dependencies, custom_property_value->as_unresolved().values(), dest, 0, custom_properties))
  442. return false;
  443. continue;
  444. }
  445. // Use the provided fallback value, if any.
  446. if (var_contents.size() > 2 && var_contents[1].is(Token::Type::Comma)) {
  447. if (!expand_unresolved_values(element, property_name, dependencies, var_contents, dest, 2, custom_properties))
  448. return false;
  449. continue;
  450. }
  451. }
  452. auto const& source_function = value.function();
  453. Vector<StyleComponentValueRule> function_values;
  454. if (!expand_unresolved_values(element, property_name, dependencies, source_function.values(), function_values, 0, custom_properties))
  455. return false;
  456. NonnullRefPtr<StyleFunctionRule> function = adopt_ref(*new StyleFunctionRule(source_function.name(), move(function_values)));
  457. dest.empend(function);
  458. continue;
  459. }
  460. if (value.is_block()) {
  461. auto const& source_block = value.block();
  462. Vector<StyleComponentValueRule> block_values;
  463. if (!expand_unresolved_values(element, property_name, dependencies, source_block.values(), block_values, 0, custom_properties))
  464. return false;
  465. NonnullRefPtr<StyleBlockRule> block = adopt_ref(*new StyleBlockRule(source_block.token(), move(block_values)));
  466. dest.empend(block);
  467. continue;
  468. }
  469. dest.empend(value.token());
  470. }
  471. return true;
  472. }
  473. RefPtr<StyleValue> StyleComputer::resolve_unresolved_style_value(DOM::Element& element, PropertyID property_id, UnresolvedStyleValue const& unresolved, HashMap<String, StyleProperty const*> const& custom_properties) const
  474. {
  475. // Unresolved always contains a var(), unless it is a custom property's value, in which case we shouldn't be trying
  476. // to produce a different StyleValue from it.
  477. VERIFY(unresolved.contains_var());
  478. Vector<StyleComponentValueRule> expanded_values;
  479. HashMap<String, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  480. if (!expand_unresolved_values(element, string_from_property_id(property_id), dependencies, unresolved.values(), expanded_values, 0, custom_properties))
  481. return {};
  482. if (auto parsed_value = Parser::parse_css_value({}, ParsingContext { document() }, property_id, expanded_values))
  483. return parsed_value.release_nonnull();
  484. return {};
  485. }
  486. void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, Important important, HashMap<String, StyleProperty const*> const& custom_properties) const
  487. {
  488. for (auto const& match : matching_rules) {
  489. for (auto const& property : verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).properties()) {
  490. if (important != property.important)
  491. continue;
  492. auto property_value = property.value;
  493. if (property.value->is_unresolved()) {
  494. if (auto resolved = resolve_unresolved_style_value(element, property.property_id, property.value->as_unresolved(), custom_properties))
  495. property_value = resolved.release_nonnull();
  496. }
  497. set_property_expanding_shorthands(style, property.property_id, property_value, m_document);
  498. }
  499. }
  500. if (cascade_origin == CascadeOrigin::Author) {
  501. if (auto const* inline_style = verify_cast<ElementInlineCSSStyleDeclaration>(element.inline_style())) {
  502. for (auto const& property : inline_style->properties()) {
  503. if (important != property.important)
  504. continue;
  505. set_property_expanding_shorthands(style, property.property_id, property.value, m_document);
  506. }
  507. }
  508. }
  509. }
  510. static HashMap<String, StyleProperty const*> cascade_custom_properties(DOM::Element& element, Vector<MatchingRule> const& matching_rules)
  511. {
  512. HashMap<String, StyleProperty const*> custom_properties;
  513. if (auto* parent_element = element.parent_element()) {
  514. for (auto const& it : parent_element->custom_properties())
  515. custom_properties.set(it.key, &it.value);
  516. }
  517. for (auto const& matching_rule : matching_rules) {
  518. for (auto const& it : verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties()) {
  519. custom_properties.set(it.key, &it.value);
  520. }
  521. }
  522. element.custom_properties().clear();
  523. for (auto& it : custom_properties)
  524. element.add_custom_property(it.key, *it.value);
  525. return custom_properties;
  526. }
  527. // https://www.w3.org/TR/css-cascade/#cascading
  528. void StyleComputer::compute_cascaded_values(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  529. {
  530. // First, we collect all the CSS rules whose selectors match `element`:
  531. MatchingRuleSet matching_rule_set;
  532. matching_rule_set.user_agent_rules = collect_matching_rules(element, CascadeOrigin::UserAgent, pseudo_element);
  533. sort_matching_rules(matching_rule_set.user_agent_rules);
  534. matching_rule_set.author_rules = collect_matching_rules(element, CascadeOrigin::Author, pseudo_element);
  535. sort_matching_rules(matching_rule_set.author_rules);
  536. // Then we resolve all the CSS custom properties ("variables") for this element:
  537. auto custom_properties = cascade_custom_properties(element, matching_rule_set.author_rules);
  538. // Then we apply the declarations from the matched rules in cascade order:
  539. // Normal user agent declarations
  540. cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::No, custom_properties);
  541. // FIXME: Normal user declarations
  542. // Normal author declarations
  543. cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::No, custom_properties);
  544. // Author presentational hints (NOTE: The spec doesn't say exactly how to prioritize these.)
  545. element.apply_presentational_hints(style);
  546. // FIXME: Animation declarations [css-animations-1]
  547. // Important author declarations
  548. cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::Yes, custom_properties);
  549. // FIXME: Important user declarations
  550. // Important user agent declarations
  551. cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::Yes, custom_properties);
  552. // FIXME: Transition declarations [css-transitions-1]
  553. }
  554. static DOM::Element const* get_parent_element(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  555. {
  556. // Pseudo-elements treat their originating element as their parent.
  557. DOM::Element const* parent_element = nullptr;
  558. if (pseudo_element.has_value()) {
  559. parent_element = element;
  560. } else if (element) {
  561. parent_element = element->parent_element();
  562. }
  563. return parent_element;
  564. }
  565. static NonnullRefPtr<StyleValue> get_inherit_value(CSS::PropertyID property_id, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  566. {
  567. auto* parent_element = get_parent_element(element, pseudo_element);
  568. if (!parent_element || !parent_element->specified_css_values())
  569. return property_initial_value(property_id);
  570. return parent_element->specified_css_values()->property(property_id).release_value();
  571. };
  572. void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM::Element const* element, CSS::PropertyID property_id, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  573. {
  574. // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue.
  575. auto& value_slot = style.m_property_values[to_underlying(property_id)];
  576. if (!value_slot) {
  577. if (is_inherited_property(property_id))
  578. style.m_property_values[to_underlying(property_id)] = get_inherit_value(property_id, element, pseudo_element);
  579. else
  580. style.m_property_values[to_underlying(property_id)] = property_initial_value(property_id);
  581. return;
  582. }
  583. if (value_slot->is_initial()) {
  584. value_slot = property_initial_value(property_id);
  585. return;
  586. }
  587. if (value_slot->is_inherit()) {
  588. value_slot = get_inherit_value(property_id, element, pseudo_element);
  589. return;
  590. }
  591. }
  592. // https://www.w3.org/TR/css-cascade/#defaulting
  593. void StyleComputer::compute_defaulted_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  594. {
  595. // Walk the list of all known CSS properties and:
  596. // - Add them to `style` if they are missing.
  597. // - Resolve `inherit` and `initial` as needed.
  598. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  599. auto property_id = (CSS::PropertyID)i;
  600. compute_defaulted_property_value(style, element, property_id, pseudo_element);
  601. }
  602. }
  603. void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  604. {
  605. // To compute the font, first ensure that we've defaulted the relevant CSS font properties.
  606. // FIXME: This should be more sophisticated.
  607. compute_defaulted_property_value(style, element, CSS::PropertyID::FontFamily, pseudo_element);
  608. compute_defaulted_property_value(style, element, CSS::PropertyID::FontSize, pseudo_element);
  609. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStyle, pseudo_element);
  610. compute_defaulted_property_value(style, element, CSS::PropertyID::FontWeight, pseudo_element);
  611. auto* parent_element = get_parent_element(element, pseudo_element);
  612. auto viewport_rect = document().browsing_context()->viewport_rect();
  613. auto font_size = style.property(CSS::PropertyID::FontSize).value();
  614. auto font_style = style.property(CSS::PropertyID::FontStyle).value();
  615. auto font_weight = style.property(CSS::PropertyID::FontWeight).value();
  616. int weight = Gfx::FontWeight::Regular;
  617. if (font_weight->is_identifier()) {
  618. switch (static_cast<IdentifierStyleValue const&>(*font_weight).id()) {
  619. case CSS::ValueID::Normal:
  620. weight = Gfx::FontWeight::Regular;
  621. break;
  622. case CSS::ValueID::Bold:
  623. weight = Gfx::FontWeight::Bold;
  624. break;
  625. case CSS::ValueID::Lighter:
  626. // FIXME: This should be relative to the parent.
  627. weight = Gfx::FontWeight::Regular;
  628. break;
  629. case CSS::ValueID::Bolder:
  630. // FIXME: This should be relative to the parent.
  631. weight = Gfx::FontWeight::Bold;
  632. break;
  633. default:
  634. break;
  635. }
  636. } else if (font_weight->has_integer()) {
  637. int font_weight_integer = font_weight->to_integer();
  638. if (font_weight_integer <= Gfx::FontWeight::Regular)
  639. weight = Gfx::FontWeight::Regular;
  640. else if (font_weight_integer <= Gfx::FontWeight::Bold)
  641. weight = Gfx::FontWeight::Bold;
  642. else
  643. weight = Gfx::FontWeight::Black;
  644. } else if (font_weight->is_calculated()) {
  645. auto maybe_weight = font_weight->as_calculated().resolve_integer();
  646. if (maybe_weight.has_value())
  647. weight = maybe_weight.value();
  648. }
  649. bool bold = weight > Gfx::FontWeight::Regular;
  650. int size = 10;
  651. if (font_size->is_identifier()) {
  652. switch (static_cast<const IdentifierStyleValue&>(*font_size).id()) {
  653. case CSS::ValueID::XxSmall:
  654. case CSS::ValueID::XSmall:
  655. case CSS::ValueID::Small:
  656. case CSS::ValueID::Medium:
  657. // FIXME: Should be based on "user's default font size"
  658. size = 10;
  659. break;
  660. case CSS::ValueID::Large:
  661. case CSS::ValueID::XLarge:
  662. case CSS::ValueID::XxLarge:
  663. case CSS::ValueID::XxxLarge:
  664. // FIXME: Should be based on "user's default font size"
  665. size = 12;
  666. break;
  667. case CSS::ValueID::Smaller:
  668. case CSS::ValueID::Larger:
  669. // FIXME: Should be based on parent element
  670. break;
  671. default:
  672. break;
  673. }
  674. } else {
  675. // FIXME: Get the root element font.
  676. float root_font_size = 10;
  677. Gfx::FontMetrics font_metrics;
  678. if (parent_element && parent_element->specified_css_values())
  679. font_metrics = parent_element->specified_css_values()->computed_font().metrics('M');
  680. else
  681. font_metrics = Gfx::FontDatabase::default_font().metrics('M');
  682. Optional<Length> maybe_length;
  683. if (font_size->is_percentage()) {
  684. // Percentages refer to parent element's font size
  685. auto percentage = font_size->as_percentage().percentage();
  686. auto parent_font_size = size;
  687. if (parent_element && parent_element->layout_node() && parent_element->specified_css_values()) {
  688. auto value = parent_element->specified_css_values()->property(CSS::PropertyID::FontSize).value();
  689. if (value->is_length()) {
  690. auto length = static_cast<LengthStyleValue const&>(*value).to_length();
  691. if (length.is_absolute() || length.is_relative())
  692. parent_font_size = length.to_px(viewport_rect, font_metrics, size, root_font_size);
  693. }
  694. }
  695. maybe_length = Length::make_px(percentage.as_fraction() * parent_font_size);
  696. } else if (font_size->is_length()) {
  697. maybe_length = font_size->to_length();
  698. } else if (font_size->is_calculated()) {
  699. maybe_length = Length::make_calculated(font_size->as_calculated());
  700. }
  701. if (maybe_length.has_value()) {
  702. // FIXME: Support font-size: calc(...)
  703. // Theoretically we can do this now, but to resolve it we need a layout_node which we might not have. :^(
  704. if (!maybe_length->is_calculated()) {
  705. auto px = maybe_length.value().to_px(viewport_rect, font_metrics, size, root_font_size);
  706. if (px != 0)
  707. size = px;
  708. }
  709. }
  710. }
  711. int slope = Gfx::name_to_slope("Normal");
  712. // FIXME: Implement oblique <angle>
  713. if (font_style->is_identifier()) {
  714. switch (static_cast<IdentifierStyleValue const&>(*font_style).id()) {
  715. case CSS::ValueID::Italic:
  716. slope = Gfx::name_to_slope("Italic");
  717. break;
  718. case CSS::ValueID::Oblique:
  719. slope = Gfx::name_to_slope("Oblique");
  720. break;
  721. case CSS::ValueID::Normal:
  722. default:
  723. break;
  724. }
  725. }
  726. // FIXME: Implement the full font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  727. // Note: This is modified by the find_font() lambda
  728. FontSelector font_selector;
  729. bool monospace = false;
  730. auto find_font = [&](String const& family) -> RefPtr<Gfx::Font> {
  731. font_selector = { family, size, weight, slope };
  732. if (auto found_font = FontCache::the().get(font_selector))
  733. return found_font;
  734. if (auto found_font = Gfx::FontDatabase::the().get(family, size, weight, slope))
  735. return found_font;
  736. return {};
  737. };
  738. // FIXME: Replace hard-coded font names with a relevant call to FontDatabase.
  739. // Currently, we cannot request the default font's name, or request it at a specific size and weight.
  740. // So, hard-coded font names it is.
  741. auto find_generic_font = [&](ValueID font_id) -> RefPtr<Gfx::Font> {
  742. switch (font_id) {
  743. case ValueID::Monospace:
  744. case ValueID::UiMonospace:
  745. monospace = true;
  746. return find_font("Csilla");
  747. case ValueID::Serif:
  748. case ValueID::SansSerif:
  749. case ValueID::Cursive:
  750. case ValueID::Fantasy:
  751. case ValueID::UiSerif:
  752. case ValueID::UiSansSerif:
  753. case ValueID::UiRounded:
  754. return find_font("Katica");
  755. default:
  756. return {};
  757. }
  758. };
  759. RefPtr<Gfx::Font> found_font;
  760. auto family_value = style.property(PropertyID::FontFamily).value();
  761. if (family_value->is_value_list()) {
  762. auto const& family_list = static_cast<StyleValueList const&>(*family_value).values();
  763. for (auto const& family : family_list) {
  764. if (family.is_identifier()) {
  765. found_font = find_generic_font(family.to_identifier());
  766. } else if (family.is_string()) {
  767. found_font = find_font(family.to_string());
  768. }
  769. if (found_font)
  770. break;
  771. }
  772. } else if (family_value->is_identifier()) {
  773. found_font = find_generic_font(family_value->to_identifier());
  774. } else if (family_value->is_string()) {
  775. found_font = find_font(family_value->to_string());
  776. }
  777. if (!found_font) {
  778. found_font = StyleProperties::font_fallback(monospace, bold);
  779. }
  780. FontCache::the().set(font_selector, *found_font);
  781. style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(size)));
  782. style.set_property(CSS::PropertyID::FontWeight, NumericStyleValue::create_integer(weight));
  783. style.set_computed_font(found_font.release_nonnull());
  784. }
  785. void StyleComputer::absolutize_values(StyleProperties& style, DOM::Element const*, Optional<CSS::Selector::PseudoElement>) const
  786. {
  787. auto viewport_rect = document().browsing_context()->viewport_rect();
  788. auto font_metrics = style.computed_font().metrics('M');
  789. // FIXME: Get the root element font.
  790. float root_font_size = 10;
  791. float font_size = style.property(CSS::PropertyID::FontSize).value()->to_length().to_px(viewport_rect, font_metrics, root_font_size, root_font_size);
  792. for (auto& value_slot : style.m_property_values) {
  793. if (!value_slot)
  794. continue;
  795. value_slot->visit_lengths([&](Length& length) {
  796. if (length.is_px())
  797. return;
  798. if (length.is_absolute() || length.is_relative()) {
  799. auto px = length.to_px(viewport_rect, font_metrics, font_size, root_font_size);
  800. length = Length::make_px(px);
  801. }
  802. });
  803. }
  804. }
  805. // https://drafts.csswg.org/css-display/#transformations
  806. void StyleComputer::transform_box_type_if_needed(StyleProperties& style, DOM::Element const&, Optional<CSS::Selector::PseudoElement>) const
  807. {
  808. // 2.7. Automatic Box Type Transformations
  809. // Some layout effects require blockification or inlinification of the box type,
  810. // which sets the box’s computed outer display type to block or inline (respectively).
  811. // (This has no effect on display types that generate no box at all, such as none or contents.)
  812. // Additionally:
  813. // FIXME: If a block box (block flow) is inlinified, its inner display type is set to flow-root so that it remains a block container.
  814. //
  815. // FIXME: If an inline box (inline flow) is inlinified, it recursively inlinifies all of its in-flow children,
  816. // so that no block-level descendants break up the inline formatting context in which it participates.
  817. //
  818. // FIXME: For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
  819. // For consistency, a run-in flow-root box also blockifies to a block box.
  820. //
  821. // FIXME: If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
  822. // Inlinification has no effect on layout-internal boxes. (However, placement in such an inline context will typically cause them
  823. // to be wrapped in an appropriately-typed anonymous inline-level box.)
  824. // Absolute positioning or floating an element blockifies the box’s display type. [CSS2]
  825. auto display = style.display();
  826. if (!display.is_none() && !display.is_contents() && !display.is_block_outside()) {
  827. if (style.position() == CSS::Position::Absolute || style.position() == CSS::Position::Fixed || style.float_() != CSS::Float::None)
  828. style.set_property(CSS::PropertyID::Display, IdentifierStyleValue::create(CSS::ValueID::Block));
  829. }
  830. // FIXME: Containment in a ruby container inlinifies the box’s display type, as described in [CSS-RUBY-1].
  831. // FIXME: A parent with a grid or flex display value blockifies the box’s display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
  832. }
  833. NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const
  834. {
  835. auto style = StyleProperties::create();
  836. compute_font(style, nullptr, {});
  837. compute_defaulted_values(style, nullptr, {});
  838. absolutize_values(style, nullptr, {});
  839. if (auto* browsing_context = m_document.browsing_context()) {
  840. auto viewport_rect = browsing_context->viewport_rect();
  841. style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect.width())));
  842. style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect.height())));
  843. }
  844. return style;
  845. }
  846. NonnullRefPtr<StyleProperties> StyleComputer::compute_style(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  847. {
  848. build_rule_cache_if_needed();
  849. auto style = StyleProperties::create();
  850. // 1. Perform the cascade. This produces the "specified style"
  851. compute_cascaded_values(style, element, pseudo_element);
  852. // 2. Compute the font, since that may be needed for font-relative CSS units
  853. compute_font(style, &element, pseudo_element);
  854. // 3. Absolutize values, turning font/viewport relative lengths into absolute lengths
  855. absolutize_values(style, &element, pseudo_element);
  856. // 4. Default the values, applying inheritance and 'initial' as needed
  857. compute_defaulted_values(style, &element, pseudo_element);
  858. // 5. Run automatic box type transformations
  859. transform_box_type_if_needed(style, element, pseudo_element);
  860. return style;
  861. }
  862. PropertyDependencyNode::PropertyDependencyNode(String name)
  863. : m_name(move(name))
  864. {
  865. }
  866. void PropertyDependencyNode::add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  867. {
  868. for (auto const& child : m_children) {
  869. if (child.m_name == new_child->m_name)
  870. return;
  871. }
  872. // We detect self-reference already.
  873. VERIFY(new_child->m_name != m_name);
  874. m_children.append(move(new_child));
  875. }
  876. bool PropertyDependencyNode::has_cycles()
  877. {
  878. if (m_marked)
  879. return true;
  880. TemporaryChange change { m_marked, true };
  881. for (auto& child : m_children) {
  882. if (child.has_cycles())
  883. return true;
  884. }
  885. return false;
  886. }
  887. void StyleComputer::build_rule_cache_if_needed() const
  888. {
  889. if (m_rule_cache && m_rule_cache->generation == m_document.style_sheets().generation())
  890. return;
  891. const_cast<StyleComputer&>(*this).build_rule_cache();
  892. }
  893. void StyleComputer::build_rule_cache()
  894. {
  895. // FIXME: Make a rule cache for UA style as well.
  896. m_rule_cache = make<RuleCache>();
  897. size_t num_class_rules = 0;
  898. size_t num_id_rules = 0;
  899. size_t num_tag_name_rules = 0;
  900. Vector<MatchingRule> matching_rules;
  901. size_t style_sheet_index = 0;
  902. for_each_stylesheet(CascadeOrigin::Author, [&](auto& sheet) {
  903. size_t rule_index = 0;
  904. static_cast<CSSStyleSheet const&>(sheet).for_each_effective_style_rule([&](auto const& rule) {
  905. size_t selector_index = 0;
  906. for (CSS::Selector const& selector : rule.selectors()) {
  907. MatchingRule matching_rule { rule, style_sheet_index, rule_index, selector_index, selector.specificity() };
  908. bool added_to_bucket = false;
  909. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  910. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Id) {
  911. m_rule_cache->rules_by_id.ensure(simple_selector.value).append(move(matching_rule));
  912. ++num_id_rules;
  913. added_to_bucket = true;
  914. break;
  915. }
  916. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Class) {
  917. m_rule_cache->rules_by_class.ensure(simple_selector.value).append(move(matching_rule));
  918. ++num_class_rules;
  919. added_to_bucket = true;
  920. break;
  921. }
  922. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::TagName) {
  923. m_rule_cache->rules_by_tag_name.ensure(simple_selector.value).append(move(matching_rule));
  924. ++num_tag_name_rules;
  925. added_to_bucket = true;
  926. break;
  927. }
  928. }
  929. if (!added_to_bucket)
  930. m_rule_cache->other_rules.append(move(matching_rule));
  931. ++selector_index;
  932. }
  933. ++rule_index;
  934. });
  935. ++style_sheet_index;
  936. });
  937. if constexpr (LIBWEB_CSS_DEBUG) {
  938. dbgln("Built rule cache!");
  939. dbgln(" ID: {}", num_id_rules);
  940. dbgln(" Class: {}", num_class_rules);
  941. dbgln("TagName: {}", num_tag_name_rules);
  942. dbgln(" Other: {}", m_rule_cache->other_rules.size());
  943. dbgln(" Total: {}", num_class_rules + num_id_rules + num_tag_name_rules + m_rule_cache->other_rules.size());
  944. }
  945. m_rule_cache->generation = m_document.style_sheets().generation();
  946. }
  947. void StyleComputer::invalidate_rule_cache()
  948. {
  949. m_rule_cache = nullptr;
  950. }
  951. }