StyleComputer.cpp 44 KB

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