StyleComputer.cpp 50 KB

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