StyleComputer.cpp 51 KB

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