StyleComputer.cpp 45 KB

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