StyleComputer.cpp 43 KB

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