StyleComputer.cpp 55 KB

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