StyleComputer.cpp 41 KB

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