StyleComputer.cpp 40 KB

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