StyleComputer.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/Error.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/TemporaryChange.h>
  13. #include <LibGfx/Font/Font.h>
  14. #include <LibGfx/Font/FontDatabase.h>
  15. #include <LibGfx/Font/FontStyleMapping.h>
  16. #include <LibGfx/Font/OpenType/Font.h>
  17. #include <LibGfx/Font/ScaledFont.h>
  18. #include <LibGfx/Font/VectorFont.h>
  19. #include <LibGfx/Font/WOFF/Font.h>
  20. #include <LibWeb/CSS/CSSFontFaceRule.h>
  21. #include <LibWeb/CSS/CSSImportRule.h>
  22. #include <LibWeb/CSS/CSSStyleRule.h>
  23. #include <LibWeb/CSS/Parser/Parser.h>
  24. #include <LibWeb/CSS/SelectorEngine.h>
  25. #include <LibWeb/CSS/StyleComputer.h>
  26. #include <LibWeb/CSS/StyleSheet.h>
  27. #include <LibWeb/CSS/StyleValues/BackgroundStyleValue.h>
  28. #include <LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.h>
  29. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  30. #include <LibWeb/CSS/StyleValues/BorderStyleValue.h>
  31. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  32. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  33. #include <LibWeb/CSS/StyleValues/FlexFlowStyleValue.h>
  34. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  35. #include <LibWeb/CSS/StyleValues/FontStyleValue.h>
  36. #include <LibWeb/CSS/StyleValues/GridAreaShorthandStyleValue.h>
  37. #include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  40. #include <LibWeb/DOM/Document.h>
  41. #include <LibWeb/DOM/Element.h>
  42. #include <LibWeb/FontCache.h>
  43. #include <LibWeb/HTML/HTMLHtmlElement.h>
  44. #include <LibWeb/Loader/ResourceLoader.h>
  45. #include <LibWeb/Platform/FontPlugin.h>
  46. #include <stdio.h>
  47. namespace Web::CSS {
  48. StyleComputer::StyleComputer(DOM::Document& document)
  49. : m_document(document)
  50. {
  51. }
  52. StyleComputer::~StyleComputer() = default;
  53. class StyleComputer::FontLoader : public ResourceClient {
  54. public:
  55. explicit FontLoader(StyleComputer& style_computer, FlyString family_name, Vector<AK::URL> urls)
  56. : m_style_computer(style_computer)
  57. , m_family_name(move(family_name))
  58. , m_urls(move(urls))
  59. {
  60. start_loading_next_url();
  61. }
  62. virtual ~FontLoader() override { }
  63. virtual void resource_did_load() override
  64. {
  65. auto result = try_load_font();
  66. if (result.is_error())
  67. return start_loading_next_url();
  68. m_vector_font = result.release_value();
  69. m_style_computer.did_load_font(m_family_name);
  70. }
  71. virtual void resource_did_fail() override
  72. {
  73. }
  74. RefPtr<Gfx::Font> font_with_point_size(float point_size) const
  75. {
  76. if (!m_vector_font)
  77. return nullptr;
  78. if (auto it = m_cached_fonts.find(point_size); it != m_cached_fonts.end())
  79. return it->value;
  80. // FIXME: It might be nicer to have a global cap on the number of fonts we cache
  81. // instead of doing it at the per-font level like this.
  82. constexpr size_t max_cached_font_size_count = 64;
  83. if (m_cached_fonts.size() > max_cached_font_size_count)
  84. m_cached_fonts.remove(m_cached_fonts.begin());
  85. auto font = adopt_ref(*new Gfx::ScaledFont(*m_vector_font, point_size, point_size));
  86. m_cached_fonts.set(point_size, font);
  87. return font;
  88. }
  89. private:
  90. void start_loading_next_url()
  91. {
  92. if (m_urls.is_empty())
  93. return;
  94. LoadRequest request;
  95. request.set_url(m_urls.take_first());
  96. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  97. }
  98. ErrorOr<NonnullRefPtr<Gfx::VectorFont>> try_load_font()
  99. {
  100. // FIXME: This could maybe use the format() provided in @font-face as well, since often the mime type is just application/octet-stream and we have to try every format
  101. auto mime_type = resource()->mime_type();
  102. if (mime_type == "font/ttf"sv || mime_type == "application/x-font-ttf"sv)
  103. return TRY(OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
  104. if (mime_type == "font/woff"sv || mime_type == "application/font-woff"sv)
  105. return TRY(WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data()));
  106. auto ttf = OpenType::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  107. if (!ttf.is_error())
  108. return ttf.release_value();
  109. auto woff = WOFF::Font::try_load_from_externally_owned_memory(resource()->encoded_data());
  110. if (!woff.is_error())
  111. return woff.release_value();
  112. return ttf.release_error();
  113. }
  114. StyleComputer& m_style_computer;
  115. FlyString m_family_name;
  116. RefPtr<Gfx::VectorFont> m_vector_font;
  117. Vector<AK::URL> m_urls;
  118. HashMap<float, NonnullRefPtr<Gfx::ScaledFont>> mutable m_cached_fonts;
  119. };
  120. static CSSStyleSheet& default_stylesheet(DOM::Document const& document)
  121. {
  122. static JS::Handle<CSSStyleSheet> sheet;
  123. if (!sheet.cell()) {
  124. extern StringView default_stylesheet_source;
  125. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), default_stylesheet_source));
  126. }
  127. return *sheet;
  128. }
  129. static CSSStyleSheet& quirks_mode_stylesheet(DOM::Document const& document)
  130. {
  131. static JS::Handle<CSSStyleSheet> sheet;
  132. if (!sheet.cell()) {
  133. extern StringView quirks_mode_stylesheet_source;
  134. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), quirks_mode_stylesheet_source));
  135. }
  136. return *sheet;
  137. }
  138. static void collect_style_sheets(CSSStyleSheet const& sheet, Vector<JS::NonnullGCPtr<CSSStyleSheet const>>& sheets)
  139. {
  140. sheets.append(sheet);
  141. for (auto const& rule : sheet.rules()) {
  142. if (rule->type() == CSSRule::Type::Import) {
  143. auto const& import_rule = static_cast<CSSImportRule const&>(*rule);
  144. if (auto const* imported_sheet = import_rule.loaded_style_sheet()) {
  145. collect_style_sheets(*imported_sheet, sheets);
  146. }
  147. }
  148. }
  149. }
  150. template<typename Callback>
  151. void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const
  152. {
  153. if (cascade_origin == CascadeOrigin::UserAgent) {
  154. callback(default_stylesheet(document()));
  155. if (document().in_quirks_mode())
  156. callback(quirks_mode_stylesheet(document()));
  157. }
  158. if (cascade_origin == CascadeOrigin::Author) {
  159. Vector<JS::NonnullGCPtr<CSSStyleSheet const>> sheets;
  160. for (auto const& sheet : document().style_sheets().sheets())
  161. collect_style_sheets(sheet, sheets);
  162. for (auto const& sheet : sheets)
  163. callback(*sheet);
  164. }
  165. }
  166. StyleComputer::RuleCache const& StyleComputer::rule_cache_for_cascade_origin(CascadeOrigin cascade_origin) const
  167. {
  168. switch (cascade_origin) {
  169. case CascadeOrigin::Author:
  170. return *m_author_rule_cache;
  171. case CascadeOrigin::UserAgent:
  172. return *m_user_agent_rule_cache;
  173. default:
  174. TODO();
  175. }
  176. }
  177. Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin cascade_origin, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  178. {
  179. auto const& rule_cache = rule_cache_for_cascade_origin(cascade_origin);
  180. Vector<MatchingRule> rules_to_run;
  181. auto add_rules_to_run = [&](Vector<MatchingRule> const& rules) {
  182. if (pseudo_element.has_value()) {
  183. for (auto& rule : rules) {
  184. if (rule.contains_pseudo_element)
  185. rules_to_run.append(rule);
  186. }
  187. } else {
  188. rules_to_run.extend(rules);
  189. }
  190. };
  191. for (auto const& class_name : element.class_names()) {
  192. if (auto it = rule_cache.rules_by_class.find(class_name); it != rule_cache.rules_by_class.end())
  193. add_rules_to_run(it->value);
  194. }
  195. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null()) {
  196. if (auto it = rule_cache.rules_by_id.find(FlyString::from_deprecated_fly_string(id).release_value_but_fixme_should_propagate_errors()); it != rule_cache.rules_by_id.end())
  197. add_rules_to_run(it->value);
  198. }
  199. if (auto it = rule_cache.rules_by_tag_name.find(FlyString::from_deprecated_fly_string(element.local_name()).release_value_but_fixme_should_propagate_errors()); it != rule_cache.rules_by_tag_name.end())
  200. add_rules_to_run(it->value);
  201. add_rules_to_run(rule_cache.other_rules);
  202. Vector<MatchingRule> matching_rules;
  203. matching_rules.ensure_capacity(rules_to_run.size());
  204. for (auto const& rule_to_run : rules_to_run) {
  205. auto const& selector = rule_to_run.rule->selectors()[rule_to_run.selector_index];
  206. if (SelectorEngine::matches(selector, element, pseudo_element))
  207. matching_rules.append(rule_to_run);
  208. }
  209. return matching_rules;
  210. }
  211. static void sort_matching_rules(Vector<MatchingRule>& matching_rules)
  212. {
  213. quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) {
  214. auto const& a_selector = a.rule->selectors()[a.selector_index];
  215. auto const& b_selector = b.rule->selectors()[b.selector_index];
  216. auto a_specificity = a_selector->specificity();
  217. auto b_specificity = b_selector->specificity();
  218. if (a_selector->specificity() == b_selector->specificity()) {
  219. if (a.style_sheet_index == b.style_sheet_index)
  220. return a.rule_index < b.rule_index;
  221. return a.style_sheet_index < b.style_sheet_index;
  222. }
  223. return a_specificity < b_specificity;
  224. });
  225. }
  226. enum class Edge {
  227. Top,
  228. Right,
  229. Bottom,
  230. Left,
  231. All,
  232. };
  233. static bool contains(Edge a, Edge b)
  234. {
  235. return a == b || b == Edge::All;
  236. }
  237. static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document)
  238. {
  239. auto assign_edge_values = [&style](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
  240. if (values.size() == 4) {
  241. style.set_property(top_property, values[0]);
  242. style.set_property(right_property, values[1]);
  243. style.set_property(bottom_property, values[2]);
  244. style.set_property(left_property, values[3]);
  245. } else if (values.size() == 3) {
  246. style.set_property(top_property, values[0]);
  247. style.set_property(right_property, values[1]);
  248. style.set_property(bottom_property, values[2]);
  249. style.set_property(left_property, values[1]);
  250. } else if (values.size() == 2) {
  251. style.set_property(top_property, values[0]);
  252. style.set_property(right_property, values[1]);
  253. style.set_property(bottom_property, values[0]);
  254. style.set_property(left_property, values[1]);
  255. } else if (values.size() == 1) {
  256. style.set_property(top_property, values[0]);
  257. style.set_property(right_property, values[0]);
  258. style.set_property(bottom_property, values[0]);
  259. style.set_property(left_property, values[0]);
  260. }
  261. };
  262. if (property_id == CSS::PropertyID::TextDecoration) {
  263. if (value.is_text_decoration()) {
  264. auto const& text_decoration = value.as_text_decoration();
  265. style.set_property(CSS::PropertyID::TextDecorationLine, text_decoration.line());
  266. style.set_property(CSS::PropertyID::TextDecorationThickness, text_decoration.thickness());
  267. style.set_property(CSS::PropertyID::TextDecorationStyle, text_decoration.style());
  268. style.set_property(CSS::PropertyID::TextDecorationColor, text_decoration.color());
  269. return;
  270. }
  271. style.set_property(CSS::PropertyID::TextDecorationLine, value);
  272. style.set_property(CSS::PropertyID::TextDecorationThickness, value);
  273. style.set_property(CSS::PropertyID::TextDecorationStyle, value);
  274. style.set_property(CSS::PropertyID::TextDecorationColor, value);
  275. return;
  276. }
  277. if (property_id == CSS::PropertyID::Overflow) {
  278. if (value.is_overflow()) {
  279. auto const& overflow = value.as_overflow();
  280. style.set_property(CSS::PropertyID::OverflowX, overflow.overflow_x());
  281. style.set_property(CSS::PropertyID::OverflowY, overflow.overflow_y());
  282. return;
  283. }
  284. style.set_property(CSS::PropertyID::OverflowX, value);
  285. style.set_property(CSS::PropertyID::OverflowY, value);
  286. return;
  287. }
  288. if (property_id == CSS::PropertyID::Border) {
  289. set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document);
  290. set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document);
  291. set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document);
  292. set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document);
  293. // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands
  294. return;
  295. }
  296. if (property_id == CSS::PropertyID::BorderRadius) {
  297. if (value.is_border_radius_shorthand()) {
  298. auto const& shorthand = value.as_border_radius_shorthand();
  299. style.set_property(CSS::PropertyID::BorderTopLeftRadius, shorthand.top_left());
  300. style.set_property(CSS::PropertyID::BorderTopRightRadius, shorthand.top_right());
  301. style.set_property(CSS::PropertyID::BorderBottomRightRadius, shorthand.bottom_right());
  302. style.set_property(CSS::PropertyID::BorderBottomLeftRadius, shorthand.bottom_left());
  303. return;
  304. }
  305. style.set_property(CSS::PropertyID::BorderTopLeftRadius, value);
  306. style.set_property(CSS::PropertyID::BorderTopRightRadius, value);
  307. style.set_property(CSS::PropertyID::BorderBottomRightRadius, value);
  308. style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value);
  309. return;
  310. }
  311. if (property_id == CSS::PropertyID::BorderTop
  312. || property_id == CSS::PropertyID::BorderRight
  313. || property_id == CSS::PropertyID::BorderBottom
  314. || property_id == CSS::PropertyID::BorderLeft) {
  315. Edge edge = Edge::All;
  316. switch (property_id) {
  317. case CSS::PropertyID::BorderTop:
  318. edge = Edge::Top;
  319. break;
  320. case CSS::PropertyID::BorderRight:
  321. edge = Edge::Right;
  322. break;
  323. case CSS::PropertyID::BorderBottom:
  324. edge = Edge::Bottom;
  325. break;
  326. case CSS::PropertyID::BorderLeft:
  327. edge = Edge::Left;
  328. break;
  329. default:
  330. break;
  331. }
  332. if (value.is_border()) {
  333. auto const& border = value.as_border();
  334. if (contains(Edge::Top, edge)) {
  335. style.set_property(PropertyID::BorderTopWidth, border.border_width());
  336. style.set_property(PropertyID::BorderTopStyle, border.border_style());
  337. style.set_property(PropertyID::BorderTopColor, border.border_color());
  338. }
  339. if (contains(Edge::Right, edge)) {
  340. style.set_property(PropertyID::BorderRightWidth, border.border_width());
  341. style.set_property(PropertyID::BorderRightStyle, border.border_style());
  342. style.set_property(PropertyID::BorderRightColor, border.border_color());
  343. }
  344. if (contains(Edge::Bottom, edge)) {
  345. style.set_property(PropertyID::BorderBottomWidth, border.border_width());
  346. style.set_property(PropertyID::BorderBottomStyle, border.border_style());
  347. style.set_property(PropertyID::BorderBottomColor, border.border_color());
  348. }
  349. if (contains(Edge::Left, edge)) {
  350. style.set_property(PropertyID::BorderLeftWidth, border.border_width());
  351. style.set_property(PropertyID::BorderLeftStyle, border.border_style());
  352. style.set_property(PropertyID::BorderLeftColor, border.border_color());
  353. }
  354. return;
  355. }
  356. return;
  357. }
  358. if (property_id == CSS::PropertyID::BorderStyle) {
  359. if (value.is_value_list()) {
  360. auto const& values_list = value.as_value_list();
  361. assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values());
  362. return;
  363. }
  364. style.set_property(CSS::PropertyID::BorderTopStyle, value);
  365. style.set_property(CSS::PropertyID::BorderRightStyle, value);
  366. style.set_property(CSS::PropertyID::BorderBottomStyle, value);
  367. style.set_property(CSS::PropertyID::BorderLeftStyle, value);
  368. return;
  369. }
  370. if (property_id == CSS::PropertyID::BorderWidth) {
  371. if (value.is_value_list()) {
  372. auto const& values_list = value.as_value_list();
  373. assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values());
  374. return;
  375. }
  376. style.set_property(CSS::PropertyID::BorderTopWidth, value);
  377. style.set_property(CSS::PropertyID::BorderRightWidth, value);
  378. style.set_property(CSS::PropertyID::BorderBottomWidth, value);
  379. style.set_property(CSS::PropertyID::BorderLeftWidth, value);
  380. return;
  381. }
  382. if (property_id == CSS::PropertyID::BorderColor) {
  383. if (value.is_value_list()) {
  384. auto const& values_list = value.as_value_list();
  385. assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values());
  386. return;
  387. }
  388. style.set_property(CSS::PropertyID::BorderTopColor, value);
  389. style.set_property(CSS::PropertyID::BorderRightColor, value);
  390. style.set_property(CSS::PropertyID::BorderBottomColor, value);
  391. style.set_property(CSS::PropertyID::BorderLeftColor, value);
  392. return;
  393. }
  394. if (property_id == CSS::PropertyID::Background) {
  395. if (value.is_background()) {
  396. auto const& background = value.as_background();
  397. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, background.color(), document);
  398. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, background.image(), document);
  399. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, background.position(), document);
  400. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, background.size(), document);
  401. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, background.repeat(), document);
  402. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, background.attachment(), document);
  403. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, background.origin(), document);
  404. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, background.clip(), document);
  405. return;
  406. }
  407. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, value, document);
  408. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document);
  409. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, value, document);
  410. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, value, document);
  411. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document);
  412. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, value, document);
  413. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, value, document);
  414. set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, value, document);
  415. return;
  416. }
  417. if (property_id == CSS::PropertyID::Margin) {
  418. if (value.is_value_list()) {
  419. auto const& values_list = value.as_value_list();
  420. assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values());
  421. return;
  422. }
  423. style.set_property(CSS::PropertyID::MarginTop, value);
  424. style.set_property(CSS::PropertyID::MarginRight, value);
  425. style.set_property(CSS::PropertyID::MarginBottom, value);
  426. style.set_property(CSS::PropertyID::MarginLeft, value);
  427. return;
  428. }
  429. if (property_id == CSS::PropertyID::Padding) {
  430. if (value.is_value_list()) {
  431. auto const& values_list = value.as_value_list();
  432. assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values());
  433. return;
  434. }
  435. style.set_property(CSS::PropertyID::PaddingTop, value);
  436. style.set_property(CSS::PropertyID::PaddingRight, value);
  437. style.set_property(CSS::PropertyID::PaddingBottom, value);
  438. style.set_property(CSS::PropertyID::PaddingLeft, value);
  439. return;
  440. }
  441. if (property_id == CSS::PropertyID::ListStyle) {
  442. if (value.is_list_style()) {
  443. auto const& list_style = value.as_list_style();
  444. style.set_property(CSS::PropertyID::ListStylePosition, list_style.position());
  445. style.set_property(CSS::PropertyID::ListStyleImage, list_style.image());
  446. style.set_property(CSS::PropertyID::ListStyleType, list_style.style_type());
  447. return;
  448. }
  449. style.set_property(CSS::PropertyID::ListStylePosition, value);
  450. style.set_property(CSS::PropertyID::ListStyleImage, value);
  451. style.set_property(CSS::PropertyID::ListStyleType, value);
  452. return;
  453. }
  454. if (property_id == CSS::PropertyID::Font) {
  455. if (value.is_font()) {
  456. auto const& font_shorthand = value.as_font();
  457. style.set_property(CSS::PropertyID::FontSize, font_shorthand.font_size());
  458. style.set_property(CSS::PropertyID::FontFamily, font_shorthand.font_families());
  459. style.set_property(CSS::PropertyID::FontStretch, font_shorthand.font_stretch());
  460. style.set_property(CSS::PropertyID::FontStyle, font_shorthand.font_style());
  461. style.set_property(CSS::PropertyID::FontWeight, font_shorthand.font_weight());
  462. style.set_property(CSS::PropertyID::LineHeight, font_shorthand.line_height());
  463. // FIXME: Implement font-variant
  464. return;
  465. }
  466. style.set_property(CSS::PropertyID::FontStretch, value);
  467. style.set_property(CSS::PropertyID::FontSize, value);
  468. style.set_property(CSS::PropertyID::FontFamily, value);
  469. style.set_property(CSS::PropertyID::FontStyle, value);
  470. style.set_property(CSS::PropertyID::FontWeight, value);
  471. style.set_property(CSS::PropertyID::LineHeight, value);
  472. // FIXME: Implement font-variant
  473. return;
  474. }
  475. if (property_id == CSS::PropertyID::Flex) {
  476. if (value.is_flex()) {
  477. auto const& flex = value.as_flex();
  478. style.set_property(CSS::PropertyID::FlexGrow, flex.grow());
  479. style.set_property(CSS::PropertyID::FlexShrink, flex.shrink());
  480. style.set_property(CSS::PropertyID::FlexBasis, flex.basis());
  481. return;
  482. }
  483. style.set_property(CSS::PropertyID::FlexGrow, value);
  484. style.set_property(CSS::PropertyID::FlexShrink, value);
  485. style.set_property(CSS::PropertyID::FlexBasis, value);
  486. return;
  487. }
  488. if (property_id == CSS::PropertyID::FlexFlow) {
  489. if (value.is_flex_flow()) {
  490. auto const& flex_flow = value.as_flex_flow();
  491. style.set_property(CSS::PropertyID::FlexDirection, flex_flow.flex_direction());
  492. style.set_property(CSS::PropertyID::FlexWrap, flex_flow.flex_wrap());
  493. return;
  494. }
  495. style.set_property(CSS::PropertyID::FlexDirection, value);
  496. style.set_property(CSS::PropertyID::FlexWrap, value);
  497. return;
  498. }
  499. if (property_id == CSS::PropertyID::GridArea) {
  500. if (value.is_grid_area_shorthand()) {
  501. auto const& shorthand = value.as_grid_area_shorthand();
  502. style.set_property(CSS::PropertyID::GridRowStart, shorthand.row_start());
  503. style.set_property(CSS::PropertyID::GridColumnStart, shorthand.column_start());
  504. style.set_property(CSS::PropertyID::GridRowEnd, shorthand.row_end());
  505. style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.column_end());
  506. return;
  507. }
  508. style.set_property(CSS::PropertyID::GridRowStart, value);
  509. style.set_property(CSS::PropertyID::GridColumnStart, value);
  510. style.set_property(CSS::PropertyID::GridRowEnd, value);
  511. style.set_property(CSS::PropertyID::GridColumnEnd, value);
  512. return;
  513. }
  514. if (property_id == CSS::PropertyID::GridColumn) {
  515. if (value.is_grid_track_placement_shorthand()) {
  516. auto const& shorthand = value.as_grid_track_placement_shorthand();
  517. style.set_property(CSS::PropertyID::GridColumnStart, shorthand.start());
  518. style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.end());
  519. return;
  520. }
  521. style.set_property(CSS::PropertyID::GridColumnStart, value);
  522. style.set_property(CSS::PropertyID::GridColumnEnd, value);
  523. return;
  524. }
  525. if (property_id == CSS::PropertyID::GridRow) {
  526. if (value.is_grid_track_placement_shorthand()) {
  527. auto const& shorthand = value.as_grid_track_placement_shorthand();
  528. style.set_property(CSS::PropertyID::GridRowStart, shorthand.start());
  529. style.set_property(CSS::PropertyID::GridRowEnd, shorthand.end());
  530. return;
  531. }
  532. style.set_property(CSS::PropertyID::GridRowStart, value);
  533. style.set_property(CSS::PropertyID::GridRowEnd, value);
  534. return;
  535. }
  536. if (property_id == CSS::PropertyID::Gap || property_id == CSS::PropertyID::GridGap) {
  537. if (value.is_value_list()) {
  538. auto const& values_list = value.as_value_list();
  539. style.set_property(CSS::PropertyID::RowGap, values_list.values()[0]);
  540. style.set_property(CSS::PropertyID::ColumnGap, values_list.values()[1]);
  541. return;
  542. }
  543. style.set_property(CSS::PropertyID::RowGap, value);
  544. style.set_property(CSS::PropertyID::ColumnGap, value);
  545. return;
  546. }
  547. if (property_id == CSS::PropertyID::RowGap || property_id == CSS::PropertyID::GridRowGap) {
  548. style.set_property(CSS::PropertyID::RowGap, value);
  549. return;
  550. }
  551. if (property_id == CSS::PropertyID::ColumnGap || property_id == CSS::PropertyID::GridColumnGap) {
  552. style.set_property(CSS::PropertyID::ColumnGap, value);
  553. return;
  554. }
  555. style.set_property(property_id, value);
  556. }
  557. static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, FlyString const& custom_property_name)
  558. {
  559. for (auto const* current_element = &element; current_element; current_element = current_element->parent_element()) {
  560. if (auto it = current_element->custom_properties().find(custom_property_name.to_string().to_deprecated_string()); it != current_element->custom_properties().end())
  561. return it->value.value;
  562. }
  563. return nullptr;
  564. }
  565. bool StyleComputer::expand_variables(DOM::Element& element, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Parser::TokenStream<Parser::ComponentValue>& source, Vector<Parser::ComponentValue>& dest) const
  566. {
  567. // Arbitrary large value chosen to avoid the billion-laughs attack.
  568. // https://www.w3.org/TR/css-variables-1/#long-variables
  569. const size_t MAX_VALUE_COUNT = 16384;
  570. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  571. dbgln("Stopped expanding CSS variables: maximum length reached.");
  572. return false;
  573. }
  574. auto get_dependency_node = [&](FlyString name) -> NonnullRefPtr<PropertyDependencyNode> {
  575. if (auto existing = dependencies.get(name); existing.has_value())
  576. return *existing.value();
  577. auto new_node = PropertyDependencyNode::create(name.to_string());
  578. dependencies.set(name, new_node);
  579. return new_node;
  580. };
  581. while (source.has_next_token()) {
  582. auto const& value = source.next_token();
  583. if (!value.is_function()) {
  584. dest.empend(value);
  585. continue;
  586. }
  587. if (!value.function().name().equals_ignoring_ascii_case("var"sv)) {
  588. auto const& source_function = value.function();
  589. Vector<Parser::ComponentValue> function_values;
  590. Parser::TokenStream source_function_contents { source_function.values() };
  591. if (!expand_variables(element, property_name, dependencies, source_function_contents, function_values))
  592. return false;
  593. NonnullRefPtr<Parser::Function> function = Parser::Function::create(FlyString::from_utf8(source_function.name()).release_value_but_fixme_should_propagate_errors(), move(function_values));
  594. dest.empend(function);
  595. continue;
  596. }
  597. Parser::TokenStream var_contents { value.function().values() };
  598. var_contents.skip_whitespace();
  599. if (!var_contents.has_next_token())
  600. return false;
  601. auto const& custom_property_name_token = var_contents.next_token();
  602. if (!custom_property_name_token.is(Parser::Token::Type::Ident))
  603. return false;
  604. auto custom_property_name = custom_property_name_token.token().ident();
  605. if (!custom_property_name.starts_with("--"sv))
  606. return false;
  607. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  608. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  609. // but rebuilding it every time.
  610. if (custom_property_name == property_name)
  611. return false;
  612. auto parent = get_dependency_node(FlyString::from_utf8(property_name).release_value_but_fixme_should_propagate_errors());
  613. auto child = get_dependency_node(FlyString::from_utf8(custom_property_name).release_value_but_fixme_should_propagate_errors());
  614. parent->add_child(child);
  615. if (parent->has_cycles())
  616. return false;
  617. if (auto custom_property_value = get_custom_property(element, FlyString::from_utf8(custom_property_name).release_value_but_fixme_should_propagate_errors())) {
  618. VERIFY(custom_property_value->is_unresolved());
  619. Parser::TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  620. if (!expand_variables(element, custom_property_name, dependencies, custom_property_tokens, dest))
  621. return false;
  622. continue;
  623. }
  624. // Use the provided fallback value, if any.
  625. var_contents.skip_whitespace();
  626. if (var_contents.has_next_token()) {
  627. auto const& comma_token = var_contents.next_token();
  628. if (!comma_token.is(Parser::Token::Type::Comma))
  629. return false;
  630. var_contents.skip_whitespace();
  631. if (!expand_variables(element, property_name, dependencies, var_contents, dest))
  632. return false;
  633. }
  634. }
  635. return true;
  636. }
  637. bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView property_name, Parser::TokenStream<Parser::ComponentValue>& source, Vector<Parser::ComponentValue>& dest) const
  638. {
  639. // FIXME: Do this better!
  640. // We build a copy of the tree of ComponentValues, with all var()s and attr()s replaced with their contents.
  641. // This is a very naive solution, and we could do better if the CSS Parser could accept tokens one at a time.
  642. while (source.has_next_token()) {
  643. auto const& value = source.next_token();
  644. if (value.is_function()) {
  645. if (value.function().name().equals_ignoring_ascii_case("attr"sv)) {
  646. // https://drafts.csswg.org/css-values-5/#attr-substitution
  647. Parser::TokenStream attr_contents { value.function().values() };
  648. attr_contents.skip_whitespace();
  649. if (!attr_contents.has_next_token())
  650. return false;
  651. auto const& attr_name_token = attr_contents.next_token();
  652. if (!attr_name_token.is(Parser::Token::Type::Ident))
  653. return false;
  654. auto attr_name = attr_name_token.token().ident();
  655. auto attr_value = element.get_attribute(attr_name);
  656. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  657. if (!attr_value.is_null()) {
  658. // FIXME: attr() should also accept an optional type argument, not just strings.
  659. dest.empend(Parser::Token::of_string(FlyString::from_deprecated_fly_string(attr_value).release_value_but_fixme_should_propagate_errors()));
  660. continue;
  661. }
  662. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  663. // If there are any var() or attr() references in the fallback, substitute them as well.
  664. attr_contents.skip_whitespace();
  665. if (attr_contents.has_next_token()) {
  666. auto const& comma_token = attr_contents.next_token();
  667. if (!comma_token.is(Parser::Token::Type::Comma))
  668. return false;
  669. attr_contents.skip_whitespace();
  670. if (!expand_unresolved_values(element, property_name, attr_contents, dest))
  671. return false;
  672. continue;
  673. }
  674. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  675. return false;
  676. }
  677. if (value.function().name().equals_ignoring_ascii_case("calc"sv)) {
  678. auto const& calc_function = value.function();
  679. if (auto calc_value = CSS::Parser::Parser::parse_calculated_value({}, Parser::ParsingContext { document() }, calc_function.values())) {
  680. switch (calc_value->resolved_type()) {
  681. case CalculatedStyleValue::ResolvedType::Integer: {
  682. auto resolved_value = calc_value->resolve_integer();
  683. dest.empend(Parser::Token::create_number(resolved_value.value()));
  684. continue;
  685. }
  686. case CalculatedStyleValue::ResolvedType::Percentage: {
  687. auto resolved_value = calc_value->resolve_percentage();
  688. dest.empend(Parser::Token::create_percentage(resolved_value.value().value()));
  689. continue;
  690. }
  691. default:
  692. dbgln("FIXME: Unimplemented calc() expansion: {}", calc_value->to_string());
  693. break;
  694. }
  695. }
  696. }
  697. auto const& source_function = value.function();
  698. Vector<Parser::ComponentValue> function_values;
  699. Parser::TokenStream source_function_contents { source_function.values() };
  700. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  701. return false;
  702. // FIXME: This would be much nicer if we could access the source_function's FlyString value directly.
  703. NonnullRefPtr<Parser::Function> function = Parser::Function::create(FlyString::from_utf8(source_function.name()).release_value_but_fixme_should_propagate_errors(), move(function_values));
  704. dest.empend(function);
  705. continue;
  706. }
  707. if (value.is_block()) {
  708. auto const& source_block = value.block();
  709. Parser::TokenStream source_block_values { source_block.values() };
  710. Vector<Parser::ComponentValue> block_values;
  711. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  712. return false;
  713. NonnullRefPtr<Parser::Block> block = Parser::Block::create(source_block.token(), move(block_values));
  714. dest.empend(move(block));
  715. continue;
  716. }
  717. dest.empend(value.token());
  718. }
  719. return true;
  720. }
  721. RefPtr<StyleValue> StyleComputer::resolve_unresolved_style_value(DOM::Element& element, PropertyID property_id, UnresolvedStyleValue const& unresolved) const
  722. {
  723. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  724. // to produce a different StyleValue from it.
  725. VERIFY(unresolved.contains_var_or_attr());
  726. Parser::TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  727. Vector<Parser::ComponentValue> values_with_variables_expanded;
  728. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  729. if (!expand_variables(element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  730. return {};
  731. Parser::TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  732. Vector<Parser::ComponentValue> expanded_values;
  733. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  734. return {};
  735. if (auto parsed_value = Parser::Parser::parse_css_value({}, Parser::ParsingContext { document() }, property_id, expanded_values))
  736. return parsed_value.release_nonnull();
  737. return {};
  738. }
  739. void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, Important important) const
  740. {
  741. for (auto const& match : matching_rules) {
  742. for (auto const& property : verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).properties()) {
  743. if (important != property.important)
  744. continue;
  745. auto property_value = property.value;
  746. if (property.value->is_unresolved()) {
  747. if (auto resolved = resolve_unresolved_style_value(element, property.property_id, property.value->as_unresolved()))
  748. property_value = resolved.release_nonnull();
  749. }
  750. if (!property_value->is_unresolved())
  751. set_property_expanding_shorthands(style, property.property_id, property_value, m_document);
  752. }
  753. }
  754. if (cascade_origin == CascadeOrigin::Author) {
  755. if (auto const* inline_style = verify_cast<ElementInlineCSSStyleDeclaration>(element.inline_style())) {
  756. for (auto const& property : inline_style->properties()) {
  757. if (important != property.important)
  758. continue;
  759. auto property_value = property.value;
  760. if (property.value->is_unresolved()) {
  761. if (auto resolved = resolve_unresolved_style_value(element, property.property_id, property.value->as_unresolved()))
  762. property_value = resolved.release_nonnull();
  763. }
  764. if (!property_value->is_unresolved())
  765. set_property_expanding_shorthands(style, property.property_id, property_value, m_document);
  766. }
  767. }
  768. }
  769. }
  770. static ErrorOr<void> cascade_custom_properties(DOM::Element& element, Vector<MatchingRule> const& matching_rules)
  771. {
  772. size_t needed_capacity = 0;
  773. for (auto const& matching_rule : matching_rules)
  774. needed_capacity += verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties().size();
  775. if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style()))
  776. needed_capacity += inline_style->custom_properties().size();
  777. HashMap<DeprecatedFlyString, StyleProperty> custom_properties;
  778. TRY(custom_properties.try_ensure_capacity(needed_capacity));
  779. for (auto const& matching_rule : matching_rules) {
  780. for (auto const& it : verify_cast<PropertyOwningCSSStyleDeclaration>(matching_rule.rule->declaration()).custom_properties())
  781. custom_properties.set(it.key, it.value);
  782. }
  783. if (auto const* inline_style = verify_cast<PropertyOwningCSSStyleDeclaration>(element.inline_style())) {
  784. for (auto const& it : inline_style->custom_properties())
  785. custom_properties.set(it.key, it.value);
  786. }
  787. element.set_custom_properties(move(custom_properties));
  788. return {};
  789. }
  790. // https://www.w3.org/TR/css-cascade/#cascading
  791. ErrorOr<void> StyleComputer::compute_cascaded_values(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, bool& did_match_any_pseudo_element_rules, ComputeStyleMode mode) const
  792. {
  793. // First, we collect all the CSS rules whose selectors match `element`:
  794. MatchingRuleSet matching_rule_set;
  795. matching_rule_set.user_agent_rules = collect_matching_rules(element, CascadeOrigin::UserAgent, pseudo_element);
  796. sort_matching_rules(matching_rule_set.user_agent_rules);
  797. matching_rule_set.author_rules = collect_matching_rules(element, CascadeOrigin::Author, pseudo_element);
  798. sort_matching_rules(matching_rule_set.author_rules);
  799. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded) {
  800. VERIFY(pseudo_element.has_value());
  801. if (matching_rule_set.author_rules.is_empty() && matching_rule_set.user_agent_rules.is_empty()) {
  802. did_match_any_pseudo_element_rules = false;
  803. return {};
  804. }
  805. did_match_any_pseudo_element_rules = true;
  806. }
  807. // Then we resolve all the CSS custom properties ("variables") for this element:
  808. // FIXME: Look into how custom properties should interact with pseudo elements and support that properly.
  809. if (!pseudo_element.has_value())
  810. TRY(cascade_custom_properties(element, matching_rule_set.author_rules));
  811. // Then we apply the declarations from the matched rules in cascade order:
  812. // Normal user agent declarations
  813. cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::No);
  814. // FIXME: Normal user declarations
  815. // Author presentational hints (NOTE: The spec doesn't say exactly how to prioritize these.)
  816. element.apply_presentational_hints(style);
  817. // Normal author declarations
  818. cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::No);
  819. // FIXME: Animation declarations [css-animations-1]
  820. // Important author declarations
  821. cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::Yes);
  822. // FIXME: Important user declarations
  823. // Important user agent declarations
  824. cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::Yes);
  825. // FIXME: Transition declarations [css-transitions-1]
  826. return {};
  827. }
  828. static DOM::Element const* element_to_inherit_style_from(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  829. {
  830. // Pseudo-elements treat their originating element as their parent.
  831. DOM::Element const* parent_element = nullptr;
  832. if (pseudo_element.has_value()) {
  833. parent_element = element;
  834. } else if (element) {
  835. parent_element = element->parent_or_shadow_host_element();
  836. }
  837. return parent_element;
  838. }
  839. static NonnullRefPtr<StyleValue const> get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID property_id, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  840. {
  841. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  842. if (!parent_element || !parent_element->computed_css_values())
  843. return property_initial_value(initial_value_context_realm, property_id);
  844. return parent_element->computed_css_values()->property(property_id);
  845. };
  846. void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM::Element const* element, CSS::PropertyID property_id, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  847. {
  848. // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue.
  849. auto& value_slot = style.m_property_values[to_underlying(property_id)];
  850. if (!value_slot) {
  851. if (is_inherited_property(property_id))
  852. style.m_property_values[to_underlying(property_id)] = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  853. else
  854. style.m_property_values[to_underlying(property_id)] = property_initial_value(document().realm(), property_id);
  855. return;
  856. }
  857. if (value_slot->is_initial()) {
  858. value_slot = property_initial_value(document().realm(), property_id);
  859. return;
  860. }
  861. if (value_slot->is_inherit()) {
  862. value_slot = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  863. return;
  864. }
  865. // https://www.w3.org/TR/css-cascade-4/#inherit-initial
  866. // If the cascaded value of a property is the unset keyword,
  867. if (value_slot->is_unset()) {
  868. if (is_inherited_property(property_id)) {
  869. // then if it is an inherited property, this is treated as inherit,
  870. value_slot = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  871. } else {
  872. // and if it is not, this is treated as initial.
  873. value_slot = property_initial_value(document().realm(), property_id);
  874. }
  875. }
  876. }
  877. // https://www.w3.org/TR/css-cascade/#defaulting
  878. void StyleComputer::compute_defaulted_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  879. {
  880. // Walk the list of all known CSS properties and:
  881. // - Add them to `style` if they are missing.
  882. // - Resolve `inherit` and `initial` as needed.
  883. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  884. auto property_id = (CSS::PropertyID)i;
  885. compute_defaulted_property_value(style, element, property_id, pseudo_element);
  886. }
  887. }
  888. CSSPixels StyleComputer::root_element_font_size() const
  889. {
  890. constexpr float default_root_element_font_size = 16;
  891. auto const* root_element = m_document->first_child_of_type<HTML::HTMLHtmlElement>();
  892. if (!root_element)
  893. return default_root_element_font_size;
  894. auto const* computed_root_style = root_element->computed_css_values();
  895. if (!computed_root_style)
  896. return default_root_element_font_size;
  897. auto root_value = computed_root_style->property(CSS::PropertyID::FontSize);
  898. auto font_metrics = computed_root_style->computed_font().pixel_metrics();
  899. auto line_height = font_metrics.line_spacing();
  900. return root_value->to_length().to_px(viewport_rect(), font_metrics, default_root_element_font_size, default_root_element_font_size, line_height, line_height);
  901. }
  902. CSSPixels StyleComputer::root_element_line_height() const
  903. {
  904. constexpr float default_root_element_line_height = 16;
  905. auto const* root_element = m_document->first_child_of_type<HTML::HTMLHtmlElement>();
  906. if (!root_element)
  907. return default_root_element_line_height;
  908. auto const* computed_root_style = root_element->computed_css_values();
  909. if (!computed_root_style)
  910. return default_root_element_line_height;
  911. auto font_metrics = computed_root_style->computed_font().pixel_metrics();
  912. auto font_size = root_element_font_size();
  913. auto line_height = font_metrics.line_spacing();
  914. return computed_root_style->line_height(viewport_rect(), font_metrics, font_size, font_size, line_height, line_height);
  915. }
  916. void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  917. {
  918. // To compute the font, first ensure that we've defaulted the relevant CSS font properties.
  919. // FIXME: This should be more sophisticated.
  920. compute_defaulted_property_value(style, element, CSS::PropertyID::FontFamily, pseudo_element);
  921. compute_defaulted_property_value(style, element, CSS::PropertyID::FontSize, pseudo_element);
  922. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStretch, pseudo_element);
  923. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStyle, pseudo_element);
  924. compute_defaulted_property_value(style, element, CSS::PropertyID::FontWeight, pseudo_element);
  925. compute_defaulted_property_value(style, element, CSS::PropertyID::LineHeight, pseudo_element);
  926. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  927. auto font_size = style.property(CSS::PropertyID::FontSize);
  928. auto font_style = style.property(CSS::PropertyID::FontStyle);
  929. auto font_weight = style.property(CSS::PropertyID::FontWeight);
  930. auto font_stretch = style.property(CSS::PropertyID::FontStretch);
  931. int width = Gfx::FontWidth::Normal;
  932. if (font_stretch->is_identifier()) {
  933. switch (static_cast<IdentifierStyleValue const&>(*font_stretch).id()) {
  934. case CSS::ValueID::UltraCondensed:
  935. width = Gfx::FontWidth::UltraCondensed;
  936. break;
  937. case CSS::ValueID::ExtraCondensed:
  938. width = Gfx::FontWidth::ExtraCondensed;
  939. break;
  940. case CSS::ValueID::Condensed:
  941. width = Gfx::FontWidth::Condensed;
  942. break;
  943. case CSS::ValueID::SemiCondensed:
  944. width = Gfx::FontWidth::SemiCondensed;
  945. break;
  946. case CSS::ValueID::Normal:
  947. width = Gfx::FontWidth::Normal;
  948. break;
  949. case CSS::ValueID::SemiExpanded:
  950. width = Gfx::FontWidth::SemiExpanded;
  951. break;
  952. case CSS::ValueID::Expanded:
  953. width = Gfx::FontWidth::Expanded;
  954. break;
  955. case CSS::ValueID::ExtraExpanded:
  956. width = Gfx::FontWidth::ExtraExpanded;
  957. break;
  958. case CSS::ValueID::UltraExpanded:
  959. width = Gfx::FontWidth::UltraExpanded;
  960. break;
  961. default:
  962. break;
  963. }
  964. } else if (font_stretch->is_percentage()) {
  965. float percentage = font_stretch->as_percentage().percentage().value();
  966. if (percentage <= 50) {
  967. width = Gfx::FontWidth::UltraCondensed;
  968. } else if (percentage <= 62.5f) {
  969. width = Gfx::FontWidth::ExtraCondensed;
  970. } else if (percentage <= 75.0f) {
  971. width = Gfx::FontWidth::Condensed;
  972. } else if (percentage <= 87.5f) {
  973. width = Gfx::FontWidth::SemiCondensed;
  974. } else if (percentage <= 100.0f) {
  975. width = Gfx::FontWidth::Normal;
  976. } else if (percentage <= 112.5f) {
  977. width = Gfx::FontWidth::SemiExpanded;
  978. } else if (percentage <= 125.0f) {
  979. width = Gfx::FontWidth::Expanded;
  980. } else if (percentage <= 150.0f) {
  981. width = Gfx::FontWidth::ExtraExpanded;
  982. } else {
  983. width = Gfx::FontWidth::UltraExpanded;
  984. }
  985. }
  986. int weight = Gfx::FontWeight::Regular;
  987. if (font_weight->is_identifier()) {
  988. switch (static_cast<IdentifierStyleValue const&>(*font_weight).id()) {
  989. case CSS::ValueID::Normal:
  990. weight = Gfx::FontWeight::Regular;
  991. break;
  992. case CSS::ValueID::Bold:
  993. weight = Gfx::FontWeight::Bold;
  994. break;
  995. case CSS::ValueID::Lighter:
  996. // FIXME: This should be relative to the parent.
  997. weight = Gfx::FontWeight::Regular;
  998. break;
  999. case CSS::ValueID::Bolder:
  1000. // FIXME: This should be relative to the parent.
  1001. weight = Gfx::FontWeight::Bold;
  1002. break;
  1003. default:
  1004. break;
  1005. }
  1006. } else if (font_weight->has_integer()) {
  1007. int font_weight_integer = font_weight->to_integer();
  1008. if (font_weight_integer <= Gfx::FontWeight::Regular)
  1009. weight = Gfx::FontWeight::Regular;
  1010. else if (font_weight_integer <= Gfx::FontWeight::Bold)
  1011. weight = Gfx::FontWeight::Bold;
  1012. else
  1013. weight = Gfx::FontWeight::Black;
  1014. } else if (font_weight->is_calculated()) {
  1015. auto maybe_weight = const_cast<CalculatedStyleValue&>(font_weight->as_calculated()).resolve_integer();
  1016. if (maybe_weight.has_value())
  1017. weight = maybe_weight.value();
  1018. }
  1019. bool bold = weight > Gfx::FontWeight::Regular;
  1020. // FIXME: Should be based on "user's default font size"
  1021. float font_size_in_px = 16;
  1022. if (font_size->is_identifier()) {
  1023. // https://w3c.github.io/csswg-drafts/css-fonts/#absolute-size-mapping
  1024. AK::HashMap<Web::CSS::ValueID, float> absolute_size_mapping = {
  1025. { CSS::ValueID::XxSmall, 0.6 },
  1026. { CSS::ValueID::XSmall, 0.75 },
  1027. { CSS::ValueID::Small, 8.0 / 9.0 },
  1028. { CSS::ValueID::Medium, 1.0 },
  1029. { CSS::ValueID::Large, 1.2 },
  1030. { CSS::ValueID::XLarge, 1.5 },
  1031. { CSS::ValueID::XxLarge, 2.0 },
  1032. { CSS::ValueID::XxxLarge, 3.0 },
  1033. { CSS::ValueID::Smaller, 0.8 },
  1034. { CSS::ValueID::Larger, 1.25 },
  1035. };
  1036. auto const identifier = static_cast<IdentifierStyleValue const&>(*font_size).id();
  1037. // https://w3c.github.io/csswg-drafts/css-fonts/#valdef-font-size-relative-size
  1038. // TODO: If the parent element has a keyword font size in the absolute size keyword mapping table,
  1039. // larger may compute the font size to the next entry in the table,
  1040. // and smaller may compute the font size to the previous entry in the table.
  1041. if (identifier == CSS::ValueID::Smaller || identifier == CSS::ValueID::Larger) {
  1042. if (parent_element && parent_element->computed_css_values()) {
  1043. font_size_in_px = parent_element->computed_css_values()->computed_font().pixel_metrics().size;
  1044. }
  1045. }
  1046. auto const multiplier = absolute_size_mapping.get(identifier).value_or(1.0);
  1047. font_size_in_px *= multiplier;
  1048. } else {
  1049. auto root_font_size = root_element_font_size();
  1050. auto root_line_height = root_element_line_height();
  1051. Gfx::FontPixelMetrics font_metrics;
  1052. if (parent_element && parent_element->computed_css_values())
  1053. font_metrics = parent_element->computed_css_values()->computed_font().pixel_metrics();
  1054. else
  1055. font_metrics = Platform::FontPlugin::the().default_font().pixel_metrics();
  1056. auto parent_font_size = [&]() -> CSSPixels {
  1057. if (!parent_element || !parent_element->computed_css_values())
  1058. return font_size_in_px;
  1059. auto value = parent_element->computed_css_values()->property(CSS::PropertyID::FontSize);
  1060. if (value->is_length()) {
  1061. auto length = static_cast<LengthStyleValue const&>(*value).to_length();
  1062. auto parent_line_height = parent_or_root_element_line_height(parent_element, {});
  1063. if (length.is_absolute() || length.is_relative())
  1064. return length.to_px(viewport_rect(), font_metrics, font_size_in_px, root_font_size, parent_line_height, root_line_height);
  1065. }
  1066. return font_size_in_px;
  1067. };
  1068. Optional<Length> maybe_length;
  1069. if (font_size->is_percentage()) {
  1070. // Percentages refer to parent element's font size
  1071. maybe_length = Length::make_px(font_size->as_percentage().percentage().as_fraction() * parent_font_size());
  1072. } else if (font_size->is_length()) {
  1073. maybe_length = font_size->to_length();
  1074. } else if (font_size->is_calculated()) {
  1075. maybe_length = Length::make_calculated(const_cast<CalculatedStyleValue&>(font_size->as_calculated()));
  1076. }
  1077. if (maybe_length.has_value()) {
  1078. // FIXME: Support font-size: calc(...)
  1079. // Theoretically we can do this now, but to resolve it we need a layout_node which we might not have. :^(
  1080. if (!maybe_length->is_calculated()) {
  1081. auto parent_line_height = parent_or_root_element_line_height(element, pseudo_element);
  1082. auto px = maybe_length.value().to_px(viewport_rect(), font_metrics, parent_font_size(), root_font_size, parent_line_height, root_line_height).value();
  1083. if (px != 0)
  1084. font_size_in_px = px;
  1085. }
  1086. }
  1087. }
  1088. int slope = Gfx::name_to_slope("Normal"sv);
  1089. // FIXME: Implement oblique <angle>
  1090. if (font_style->is_identifier()) {
  1091. switch (static_cast<IdentifierStyleValue const&>(*font_style).id()) {
  1092. case CSS::ValueID::Italic:
  1093. slope = Gfx::name_to_slope("Italic"sv);
  1094. break;
  1095. case CSS::ValueID::Oblique:
  1096. slope = Gfx::name_to_slope("Oblique"sv);
  1097. break;
  1098. case CSS::ValueID::Normal:
  1099. default:
  1100. break;
  1101. }
  1102. }
  1103. // FIXME: Implement the full font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  1104. // Note: This is modified by the find_font() lambda
  1105. FontSelector font_selector;
  1106. bool monospace = false;
  1107. auto find_font = [&](String const& family) -> RefPtr<Gfx::Font const> {
  1108. float font_size_in_pt = font_size_in_px * 0.75f;
  1109. font_selector = { family, font_size_in_pt, weight, width, slope };
  1110. if (auto it = m_loaded_fonts.find(family); it != m_loaded_fonts.end()) {
  1111. auto& loader = *it->value;
  1112. if (auto found_font = loader.font_with_point_size(font_size_in_pt))
  1113. return found_font;
  1114. }
  1115. if (auto found_font = FontCache::the().get(font_selector))
  1116. return found_font;
  1117. if (auto found_font = Gfx::FontDatabase::the().get(family.to_deprecated_string(), font_size_in_pt, weight, width, slope, Gfx::Font::AllowInexactSizeMatch::Yes))
  1118. return found_font;
  1119. return {};
  1120. };
  1121. auto find_generic_font = [&](ValueID font_id) -> RefPtr<Gfx::Font const> {
  1122. Platform::GenericFont generic_font {};
  1123. switch (font_id) {
  1124. case ValueID::Monospace:
  1125. case ValueID::UiMonospace:
  1126. generic_font = Platform::GenericFont::Monospace;
  1127. monospace = true;
  1128. break;
  1129. case ValueID::Serif:
  1130. generic_font = Platform::GenericFont::Serif;
  1131. break;
  1132. case ValueID::Fantasy:
  1133. generic_font = Platform::GenericFont::Fantasy;
  1134. break;
  1135. case ValueID::SansSerif:
  1136. generic_font = Platform::GenericFont::SansSerif;
  1137. break;
  1138. case ValueID::Cursive:
  1139. generic_font = Platform::GenericFont::Cursive;
  1140. break;
  1141. case ValueID::UiSerif:
  1142. generic_font = Platform::GenericFont::UiSerif;
  1143. break;
  1144. case ValueID::UiSansSerif:
  1145. generic_font = Platform::GenericFont::UiSansSerif;
  1146. break;
  1147. case ValueID::UiRounded:
  1148. generic_font = Platform::GenericFont::UiRounded;
  1149. break;
  1150. default:
  1151. return {};
  1152. }
  1153. return find_font(String::from_utf8(Platform::FontPlugin::the().generic_font_name(generic_font)).release_value_but_fixme_should_propagate_errors());
  1154. };
  1155. RefPtr<Gfx::Font const> found_font;
  1156. auto family_value = style.property(PropertyID::FontFamily);
  1157. if (family_value->is_value_list()) {
  1158. auto const& family_list = static_cast<StyleValueList const&>(*family_value).values();
  1159. for (auto const& family : family_list) {
  1160. if (family->is_identifier()) {
  1161. found_font = find_generic_font(family->to_identifier());
  1162. } else if (family->is_string()) {
  1163. found_font = find_font(family->to_string().release_value_but_fixme_should_propagate_errors());
  1164. }
  1165. if (found_font)
  1166. break;
  1167. }
  1168. } else if (family_value->is_identifier()) {
  1169. found_font = find_generic_font(family_value->to_identifier());
  1170. } else if (family_value->is_string()) {
  1171. found_font = find_font(family_value->to_string().release_value_but_fixme_should_propagate_errors());
  1172. }
  1173. if (!found_font) {
  1174. found_font = StyleProperties::font_fallback(monospace, bold);
  1175. }
  1176. FontCache::the().set(font_selector, *found_font);
  1177. style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(font_size_in_px)));
  1178. style.set_property(CSS::PropertyID::FontWeight, NumericStyleValue::create_integer(weight));
  1179. style.set_computed_font(found_font.release_nonnull());
  1180. }
  1181. Gfx::Font const& StyleComputer::initial_font() const
  1182. {
  1183. // FIXME: This is not correct.
  1184. return StyleProperties::font_fallback(false, false);
  1185. }
  1186. CSSPixels StyleComputer::parent_or_root_element_line_height(DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1187. {
  1188. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1189. if (!parent_element)
  1190. return root_element_line_height();
  1191. auto root_font_size = root_element_font_size();
  1192. auto root_line_height = root_element_line_height();
  1193. auto* computed_values = parent_element->computed_css_values();
  1194. auto parent_font_size = computed_values->property(CSS::PropertyID::FontSize)->to_length();
  1195. // FIXME: Can the parent font size be non-absolute here?
  1196. auto parent_font_size_value = parent_font_size.is_absolute() ? parent_font_size.absolute_length_to_px() : root_font_size;
  1197. auto parent_parent_line_height = parent_or_root_element_line_height(parent_element, {});
  1198. return computed_values->line_height(viewport_rect(), computed_values->computed_font().pixel_metrics(), parent_font_size_value, root_font_size, parent_parent_line_height, root_line_height);
  1199. }
  1200. void StyleComputer::absolutize_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1201. {
  1202. auto root_line_height = root_element_line_height();
  1203. auto parent_or_root_line_height = parent_or_root_element_line_height(element, pseudo_element);
  1204. auto font_metrics = style.computed_font().pixel_metrics();
  1205. auto root_font_size = root_element_font_size();
  1206. auto font_size = style.property(CSS::PropertyID::FontSize)->to_length().to_px(viewport_rect(), font_metrics, root_font_size, root_font_size, parent_or_root_line_height, root_line_height);
  1207. // NOTE: Percentage line-height values are relative to the font-size of the element.
  1208. // We have to resolve them right away, so that the *computed* line-height is ready for inheritance.
  1209. // We can't simply absolutize *all* percentage values against the font size,
  1210. // because most percentages are relative to containing block metrics.
  1211. auto& line_height_value_slot = style.m_property_values[to_underlying(CSS::PropertyID::LineHeight)];
  1212. if (line_height_value_slot && line_height_value_slot->is_percentage()) {
  1213. line_height_value_slot = LengthStyleValue::create(
  1214. Length::make_px(font_size * line_height_value_slot->as_percentage().percentage().as_fraction()));
  1215. }
  1216. auto line_height = style.line_height(viewport_rect(), font_metrics, font_size.value(), root_font_size.value(), parent_or_root_line_height, root_line_height);
  1217. // NOTE: line-height might be using lh which should be resolved against the parent line height (like we did here already)
  1218. if (line_height_value_slot && line_height_value_slot->is_length())
  1219. line_height_value_slot = LengthStyleValue::create(Length::make_px(line_height));
  1220. for (size_t i = 0; i < style.m_property_values.size(); ++i) {
  1221. auto& value_slot = style.m_property_values[i];
  1222. if (!value_slot)
  1223. continue;
  1224. value_slot = value_slot->absolutized(viewport_rect(), font_metrics, font_size.value(), root_font_size.value(), line_height, root_line_height);
  1225. }
  1226. }
  1227. enum class BoxTypeTransformation {
  1228. None,
  1229. Blockify,
  1230. Inlinify,
  1231. };
  1232. static BoxTypeTransformation required_box_type_transformation(StyleProperties const& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> const&)
  1233. {
  1234. // Absolute positioning or floating an element blockifies the box’s display type. [CSS2]
  1235. if (style.position() == CSS::Position::Absolute || style.position() == CSS::Position::Fixed || style.float_() != CSS::Float::None)
  1236. return BoxTypeTransformation::Blockify;
  1237. // FIXME: Containment in a ruby container inlinifies the box’s display type, as described in [CSS-RUBY-1].
  1238. // A parent with a grid or flex display value blockifies the box’s display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
  1239. if (element.parent_element() && element.parent_element()->computed_css_values()) {
  1240. auto const& parent_display = element.parent_element()->computed_css_values()->display();
  1241. if (parent_display.is_grid_inside() || parent_display.is_flex_inside())
  1242. return BoxTypeTransformation::Blockify;
  1243. }
  1244. return BoxTypeTransformation::None;
  1245. }
  1246. // https://drafts.csswg.org/css-display/#transformations
  1247. void StyleComputer::transform_box_type_if_needed(StyleProperties& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1248. {
  1249. // 2.7. Automatic Box Type Transformations
  1250. // Some layout effects require blockification or inlinification of the box type,
  1251. // which sets the box’s computed outer display type to block or inline (respectively).
  1252. // (This has no effect on display types that generate no box at all, such as none or contents.)
  1253. // 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.
  1254. //
  1255. // FIXME: If an inline box (inline flow) is inlinified, it recursively inlinifies all of its in-flow children,
  1256. // so that no block-level descendants break up the inline formatting context in which it participates.
  1257. //
  1258. // FIXME: For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
  1259. // For consistency, a run-in flow-root box also blockifies to a block box.
  1260. //
  1261. // FIXME: If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
  1262. // Inlinification has no effect on layout-internal boxes. (However, placement in such an inline context will typically cause them
  1263. // to be wrapped in an appropriately-typed anonymous inline-level box.)
  1264. auto display = style.display();
  1265. if (display.is_none() || display.is_contents())
  1266. return;
  1267. switch (required_box_type_transformation(style, element, pseudo_element)) {
  1268. case BoxTypeTransformation::None:
  1269. break;
  1270. case BoxTypeTransformation::Blockify:
  1271. if (!display.is_block_outside()) {
  1272. // FIXME: We only want to change the outer display type here, but we don't have a nice API
  1273. // to do that specifically. For now, we simply check for "inline-flex" and convert
  1274. // that to "flex".
  1275. if (display.is_flex_inside())
  1276. style.set_property(CSS::PropertyID::Display, IdentifierStyleValue::create(CSS::ValueID::Flex));
  1277. else
  1278. style.set_property(CSS::PropertyID::Display, IdentifierStyleValue::create(CSS::ValueID::Block));
  1279. }
  1280. break;
  1281. case BoxTypeTransformation::Inlinify:
  1282. if (!display.is_inline_outside())
  1283. style.set_property(CSS::PropertyID::Display, IdentifierStyleValue::create(CSS::ValueID::Inline));
  1284. break;
  1285. }
  1286. }
  1287. NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const
  1288. {
  1289. auto style = StyleProperties::create();
  1290. compute_font(style, nullptr, {});
  1291. compute_defaulted_values(style, nullptr, {});
  1292. absolutize_values(style, nullptr, {});
  1293. style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().width())));
  1294. style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().height())));
  1295. style->set_property(CSS::PropertyID::Display, CSS::IdentifierStyleValue::create(CSS::ValueID::Block));
  1296. return style;
  1297. }
  1298. ErrorOr<NonnullRefPtr<StyleProperties>> StyleComputer::compute_style(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1299. {
  1300. auto style = TRY(compute_style_impl(element, move(pseudo_element), ComputeStyleMode::Normal));
  1301. return style.release_nonnull();
  1302. }
  1303. ErrorOr<RefPtr<StyleProperties>> StyleComputer::compute_pseudo_element_style_if_needed(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1304. {
  1305. return compute_style_impl(element, move(pseudo_element), ComputeStyleMode::CreatePseudoElementStyleIfNeeded);
  1306. }
  1307. ErrorOr<RefPtr<StyleProperties>> StyleComputer::compute_style_impl(DOM::Element& element, Optional<CSS::Selector::PseudoElement> pseudo_element, ComputeStyleMode mode) const
  1308. {
  1309. build_rule_cache_if_needed();
  1310. auto style = StyleProperties::create();
  1311. // 1. Perform the cascade. This produces the "specified style"
  1312. bool did_match_any_pseudo_element_rules = false;
  1313. TRY(compute_cascaded_values(style, element, pseudo_element, did_match_any_pseudo_element_rules, mode));
  1314. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded && !did_match_any_pseudo_element_rules)
  1315. return nullptr;
  1316. // 2. Compute the font, since that may be needed for font-relative CSS units
  1317. compute_font(style, &element, pseudo_element);
  1318. // 3. Absolutize values, turning font/viewport relative lengths into absolute lengths
  1319. absolutize_values(style, &element, pseudo_element);
  1320. // 4. Default the values, applying inheritance and 'initial' as needed
  1321. compute_defaulted_values(style, &element, pseudo_element);
  1322. // 5. Run automatic box type transformations
  1323. transform_box_type_if_needed(style, element, pseudo_element);
  1324. return style;
  1325. }
  1326. PropertyDependencyNode::PropertyDependencyNode(String name)
  1327. : m_name(move(name))
  1328. {
  1329. }
  1330. void PropertyDependencyNode::add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  1331. {
  1332. for (auto const& child : m_children) {
  1333. if (child->m_name == new_child->m_name)
  1334. return;
  1335. }
  1336. // We detect self-reference already.
  1337. VERIFY(new_child->m_name != m_name);
  1338. m_children.append(move(new_child));
  1339. }
  1340. bool PropertyDependencyNode::has_cycles()
  1341. {
  1342. if (m_marked)
  1343. return true;
  1344. TemporaryChange change { m_marked, true };
  1345. for (auto& child : m_children) {
  1346. if (child->has_cycles())
  1347. return true;
  1348. }
  1349. return false;
  1350. }
  1351. void StyleComputer::build_rule_cache_if_needed() const
  1352. {
  1353. if (m_author_rule_cache && m_user_agent_rule_cache)
  1354. return;
  1355. const_cast<StyleComputer&>(*this).build_rule_cache();
  1356. }
  1357. NonnullOwnPtr<StyleComputer::RuleCache> StyleComputer::make_rule_cache_for_cascade_origin(CascadeOrigin cascade_origin)
  1358. {
  1359. auto rule_cache = make<RuleCache>();
  1360. size_t num_class_rules = 0;
  1361. size_t num_id_rules = 0;
  1362. size_t num_tag_name_rules = 0;
  1363. size_t num_pseudo_element_rules = 0;
  1364. Vector<MatchingRule> matching_rules;
  1365. size_t style_sheet_index = 0;
  1366. for_each_stylesheet(cascade_origin, [&](auto& sheet) {
  1367. size_t rule_index = 0;
  1368. sheet.for_each_effective_style_rule([&](auto const& rule) {
  1369. size_t selector_index = 0;
  1370. for (CSS::Selector const& selector : rule.selectors()) {
  1371. MatchingRule matching_rule {
  1372. &rule,
  1373. style_sheet_index,
  1374. rule_index,
  1375. selector_index,
  1376. selector.specificity(),
  1377. };
  1378. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  1379. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoElement) {
  1380. matching_rule.contains_pseudo_element = true;
  1381. ++num_pseudo_element_rules;
  1382. break;
  1383. }
  1384. }
  1385. bool added_to_bucket = false;
  1386. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  1387. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Id) {
  1388. rule_cache->rules_by_id.ensure(simple_selector.name()).append(move(matching_rule));
  1389. ++num_id_rules;
  1390. added_to_bucket = true;
  1391. break;
  1392. }
  1393. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Class) {
  1394. rule_cache->rules_by_class.ensure(simple_selector.name()).append(move(matching_rule));
  1395. ++num_class_rules;
  1396. added_to_bucket = true;
  1397. break;
  1398. }
  1399. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::TagName) {
  1400. rule_cache->rules_by_tag_name.ensure(simple_selector.name()).append(move(matching_rule));
  1401. ++num_tag_name_rules;
  1402. added_to_bucket = true;
  1403. break;
  1404. }
  1405. }
  1406. if (!added_to_bucket)
  1407. rule_cache->other_rules.append(move(matching_rule));
  1408. ++selector_index;
  1409. }
  1410. ++rule_index;
  1411. });
  1412. ++style_sheet_index;
  1413. });
  1414. if constexpr (LIBWEB_CSS_DEBUG) {
  1415. dbgln("Built rule cache!");
  1416. dbgln(" ID: {}", num_id_rules);
  1417. dbgln(" Class: {}", num_class_rules);
  1418. dbgln(" TagName: {}", num_tag_name_rules);
  1419. dbgln("PseudoElement: {}", num_pseudo_element_rules);
  1420. dbgln(" Other: {}", rule_cache->other_rules.size());
  1421. dbgln(" Total: {}", num_class_rules + num_id_rules + num_tag_name_rules + rule_cache->other_rules.size());
  1422. }
  1423. return rule_cache;
  1424. }
  1425. void StyleComputer::build_rule_cache()
  1426. {
  1427. m_author_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::Author);
  1428. m_user_agent_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::UserAgent);
  1429. }
  1430. void StyleComputer::invalidate_rule_cache()
  1431. {
  1432. m_author_rule_cache = nullptr;
  1433. // NOTE: It might not be necessary to throw away the UA rule cache.
  1434. // If we are sure that it's safe, we could keep it as an optimization.
  1435. m_user_agent_rule_cache = nullptr;
  1436. }
  1437. CSSPixelRect StyleComputer::viewport_rect() const
  1438. {
  1439. if (auto const* browsing_context = document().browsing_context())
  1440. return browsing_context->viewport_rect();
  1441. return {};
  1442. }
  1443. void StyleComputer::did_load_font([[maybe_unused]] FlyString const& family_name)
  1444. {
  1445. document().invalidate_style();
  1446. }
  1447. void StyleComputer::load_fonts_from_sheet(CSSStyleSheet const& sheet)
  1448. {
  1449. for (auto const& rule : static_cast<CSSStyleSheet const&>(sheet).rules()) {
  1450. if (!is<CSSFontFaceRule>(*rule))
  1451. continue;
  1452. auto const& font_face = static_cast<CSSFontFaceRule const&>(*rule).font_face();
  1453. if (font_face.sources().is_empty())
  1454. continue;
  1455. if (m_loaded_fonts.contains(font_face.font_family()))
  1456. continue;
  1457. Vector<AK::URL> urls;
  1458. for (auto& source : font_face.sources()) {
  1459. // FIXME: These should be loaded relative to the stylesheet URL instead of the document URL.
  1460. urls.append(m_document->parse_url(source.url.to_deprecated_string()));
  1461. }
  1462. if (urls.is_empty())
  1463. continue;
  1464. auto loader = make<FontLoader>(const_cast<StyleComputer&>(*this), font_face.font_family(), move(urls));
  1465. const_cast<StyleComputer&>(*this).m_loaded_fonts.set(font_face.font_family().to_string(), move(loader));
  1466. }
  1467. }
  1468. }