StyleComputer.cpp 50 KB

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