StyleValue.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/ByteBuffer.h>
  10. #include <LibGfx/Palette.h>
  11. #include <LibWeb/CSS/Serialize.h>
  12. #include <LibWeb/CSS/StyleValue.h>
  13. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  14. #include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
  15. #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
  16. #include <LibWeb/CSS/StyleValues/BackgroundStyleValue.h>
  17. #include <LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.h>
  18. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  19. #include <LibWeb/CSS/StyleValues/BorderStyleValue.h>
  20. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  21. #include <LibWeb/CSS/StyleValues/ConicGradientStyleValue.h>
  22. #include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
  23. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  24. #include <LibWeb/CSS/StyleValues/FlexFlowStyleValue.h>
  25. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  26. #include <LibWeb/CSS/StyleValues/FontStyleValue.h>
  27. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  28. #include <LibWeb/CSS/StyleValues/GridAreaShorthandStyleValue.h>
  29. #include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
  30. #include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
  31. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  32. #include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
  33. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  34. #include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
  35. #include <LibWeb/CSS/StyleValues/LinearGradientStyleValue.h>
  36. #include <LibWeb/DOM/Document.h>
  37. #include <LibWeb/HTML/BrowsingContext.h>
  38. #include <LibWeb/Loader/LoadRequest.h>
  39. #include <LibWeb/Loader/ResourceLoader.h>
  40. #include <LibWeb/Page/Page.h>
  41. #include <LibWeb/Painting/GradientPainting.h>
  42. #include <LibWeb/Platform/Timer.h>
  43. namespace Web::CSS {
  44. StyleValue::StyleValue(Type type)
  45. : m_type(type)
  46. {
  47. }
  48. AbstractImageStyleValue const& StyleValue::as_abstract_image() const
  49. {
  50. VERIFY(is_abstract_image());
  51. return static_cast<AbstractImageStyleValue const&>(*this);
  52. }
  53. AngleStyleValue const& StyleValue::as_angle() const
  54. {
  55. VERIFY(is_angle());
  56. return static_cast<AngleStyleValue const&>(*this);
  57. }
  58. BackgroundStyleValue const& StyleValue::as_background() const
  59. {
  60. VERIFY(is_background());
  61. return static_cast<BackgroundStyleValue const&>(*this);
  62. }
  63. BackgroundRepeatStyleValue const& StyleValue::as_background_repeat() const
  64. {
  65. VERIFY(is_background_repeat());
  66. return static_cast<BackgroundRepeatStyleValue const&>(*this);
  67. }
  68. BackgroundSizeStyleValue const& StyleValue::as_background_size() const
  69. {
  70. VERIFY(is_background_size());
  71. return static_cast<BackgroundSizeStyleValue const&>(*this);
  72. }
  73. BorderStyleValue const& StyleValue::as_border() const
  74. {
  75. VERIFY(is_border());
  76. return static_cast<BorderStyleValue const&>(*this);
  77. }
  78. BorderRadiusStyleValue const& StyleValue::as_border_radius() const
  79. {
  80. VERIFY(is_border_radius());
  81. return static_cast<BorderRadiusStyleValue const&>(*this);
  82. }
  83. BorderRadiusShorthandStyleValue const& StyleValue::as_border_radius_shorthand() const
  84. {
  85. VERIFY(is_border_radius_shorthand());
  86. return static_cast<BorderRadiusShorthandStyleValue const&>(*this);
  87. }
  88. ShadowStyleValue const& StyleValue::as_shadow() const
  89. {
  90. VERIFY(is_shadow());
  91. return static_cast<ShadowStyleValue const&>(*this);
  92. }
  93. CalculatedStyleValue const& StyleValue::as_calculated() const
  94. {
  95. VERIFY(is_calculated());
  96. return static_cast<CalculatedStyleValue const&>(*this);
  97. }
  98. ColorStyleValue const& StyleValue::as_color() const
  99. {
  100. VERIFY(is_color());
  101. return static_cast<ColorStyleValue const&>(*this);
  102. }
  103. ConicGradientStyleValue const& StyleValue::as_conic_gradient() const
  104. {
  105. VERIFY(is_conic_gradient());
  106. return static_cast<ConicGradientStyleValue const&>(*this);
  107. }
  108. ContentStyleValue const& StyleValue::as_content() const
  109. {
  110. VERIFY(is_content());
  111. return static_cast<ContentStyleValue const&>(*this);
  112. }
  113. FilterValueListStyleValue const& StyleValue::as_filter_value_list() const
  114. {
  115. VERIFY(is_filter_value_list());
  116. return static_cast<FilterValueListStyleValue const&>(*this);
  117. }
  118. FlexStyleValue const& StyleValue::as_flex() const
  119. {
  120. VERIFY(is_flex());
  121. return static_cast<FlexStyleValue const&>(*this);
  122. }
  123. FlexFlowStyleValue const& StyleValue::as_flex_flow() const
  124. {
  125. VERIFY(is_flex_flow());
  126. return static_cast<FlexFlowStyleValue const&>(*this);
  127. }
  128. FontStyleValue const& StyleValue::as_font() const
  129. {
  130. VERIFY(is_font());
  131. return static_cast<FontStyleValue const&>(*this);
  132. }
  133. FrequencyStyleValue const& StyleValue::as_frequency() const
  134. {
  135. VERIFY(is_frequency());
  136. return static_cast<FrequencyStyleValue const&>(*this);
  137. }
  138. GridTrackPlacementShorthandStyleValue const& StyleValue::as_grid_track_placement_shorthand() const
  139. {
  140. VERIFY(is_grid_track_placement_shorthand());
  141. return static_cast<GridTrackPlacementShorthandStyleValue const&>(*this);
  142. }
  143. GridAreaShorthandStyleValue const& StyleValue::as_grid_area_shorthand() const
  144. {
  145. VERIFY(is_grid_area_shorthand());
  146. return static_cast<GridAreaShorthandStyleValue const&>(*this);
  147. }
  148. GridTemplateAreaStyleValue const& StyleValue::as_grid_template_area() const
  149. {
  150. VERIFY(is_grid_template_area());
  151. return static_cast<GridTemplateAreaStyleValue const&>(*this);
  152. }
  153. GridTrackPlacementStyleValue const& StyleValue::as_grid_track_placement() const
  154. {
  155. VERIFY(is_grid_track_placement());
  156. return static_cast<GridTrackPlacementStyleValue const&>(*this);
  157. }
  158. IdentifierStyleValue const& StyleValue::as_identifier() const
  159. {
  160. VERIFY(is_identifier());
  161. return static_cast<IdentifierStyleValue const&>(*this);
  162. }
  163. ImageStyleValue const& StyleValue::as_image() const
  164. {
  165. VERIFY(is_image());
  166. return static_cast<ImageStyleValue const&>(*this);
  167. }
  168. InheritStyleValue const& StyleValue::as_inherit() const
  169. {
  170. VERIFY(is_inherit());
  171. return static_cast<InheritStyleValue const&>(*this);
  172. }
  173. InitialStyleValue const& StyleValue::as_initial() const
  174. {
  175. VERIFY(is_initial());
  176. return static_cast<InitialStyleValue const&>(*this);
  177. }
  178. LengthStyleValue const& StyleValue::as_length() const
  179. {
  180. VERIFY(is_length());
  181. return static_cast<LengthStyleValue const&>(*this);
  182. }
  183. GridTrackSizeStyleValue const& StyleValue::as_grid_track_size_list() const
  184. {
  185. VERIFY(is_grid_track_size_list());
  186. return static_cast<GridTrackSizeStyleValue const&>(*this);
  187. }
  188. LinearGradientStyleValue const& StyleValue::as_linear_gradient() const
  189. {
  190. VERIFY(is_linear_gradient());
  191. return static_cast<LinearGradientStyleValue const&>(*this);
  192. }
  193. ListStyleStyleValue const& StyleValue::as_list_style() const
  194. {
  195. VERIFY(is_list_style());
  196. return static_cast<ListStyleStyleValue const&>(*this);
  197. }
  198. NumericStyleValue const& StyleValue::as_numeric() const
  199. {
  200. VERIFY(is_numeric());
  201. return static_cast<NumericStyleValue const&>(*this);
  202. }
  203. OverflowStyleValue const& StyleValue::as_overflow() const
  204. {
  205. VERIFY(is_overflow());
  206. return static_cast<OverflowStyleValue const&>(*this);
  207. }
  208. PercentageStyleValue const& StyleValue::as_percentage() const
  209. {
  210. VERIFY(is_percentage());
  211. return static_cast<PercentageStyleValue const&>(*this);
  212. }
  213. PositionStyleValue const& StyleValue::as_position() const
  214. {
  215. VERIFY(is_position());
  216. return static_cast<PositionStyleValue const&>(*this);
  217. }
  218. RadialGradientStyleValue const& StyleValue::as_radial_gradient() const
  219. {
  220. VERIFY(is_radial_gradient());
  221. return static_cast<RadialGradientStyleValue const&>(*this);
  222. }
  223. RectStyleValue const& StyleValue::as_rect() const
  224. {
  225. VERIFY(is_rect());
  226. return static_cast<RectStyleValue const&>(*this);
  227. }
  228. ResolutionStyleValue const& StyleValue::as_resolution() const
  229. {
  230. VERIFY(is_resolution());
  231. return static_cast<ResolutionStyleValue const&>(*this);
  232. }
  233. StringStyleValue const& StyleValue::as_string() const
  234. {
  235. VERIFY(is_string());
  236. return static_cast<StringStyleValue const&>(*this);
  237. }
  238. TextDecorationStyleValue const& StyleValue::as_text_decoration() const
  239. {
  240. VERIFY(is_text_decoration());
  241. return static_cast<TextDecorationStyleValue const&>(*this);
  242. }
  243. TimeStyleValue const& StyleValue::as_time() const
  244. {
  245. VERIFY(is_time());
  246. return static_cast<TimeStyleValue const&>(*this);
  247. }
  248. TransformationStyleValue const& StyleValue::as_transformation() const
  249. {
  250. VERIFY(is_transformation());
  251. return static_cast<TransformationStyleValue const&>(*this);
  252. }
  253. UnresolvedStyleValue const& StyleValue::as_unresolved() const
  254. {
  255. VERIFY(is_unresolved());
  256. return static_cast<UnresolvedStyleValue const&>(*this);
  257. }
  258. UnsetStyleValue const& StyleValue::as_unset() const
  259. {
  260. VERIFY(is_unset());
  261. return static_cast<UnsetStyleValue const&>(*this);
  262. }
  263. StyleValueList const& StyleValue::as_value_list() const
  264. {
  265. VERIFY(is_value_list());
  266. return static_cast<StyleValueList const&>(*this);
  267. }
  268. void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  269. {
  270. add_or_subtract_internal(SumOperation::Add, other, layout_node, percentage_basis);
  271. }
  272. void CalculatedStyleValue::CalculationResult::subtract(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  273. {
  274. add_or_subtract_internal(SumOperation::Subtract, other, layout_node, percentage_basis);
  275. }
  276. void CalculatedStyleValue::CalculationResult::add_or_subtract_internal(SumOperation op, CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  277. {
  278. // We know from validation when resolving the type, that "both sides have the same type, or that one side is a <number> and the other is an <integer>".
  279. // Though, having the same type may mean that one side is a <dimension> and the other a <percentage>.
  280. // Note: This is almost identical to ::add()
  281. m_value.visit(
  282. [&](Number const& number) {
  283. auto other_number = other.m_value.get<Number>();
  284. if (op == SumOperation::Add) {
  285. m_value = number + other_number;
  286. } else {
  287. m_value = number - other_number;
  288. }
  289. },
  290. [&](Angle const& angle) {
  291. auto this_degrees = angle.to_degrees();
  292. if (other.m_value.has<Angle>()) {
  293. auto other_degrees = other.m_value.get<Angle>().to_degrees();
  294. if (op == SumOperation::Add)
  295. m_value = Angle::make_degrees(this_degrees + other_degrees);
  296. else
  297. m_value = Angle::make_degrees(this_degrees - other_degrees);
  298. } else {
  299. VERIFY(percentage_basis.has<Angle>());
  300. auto other_degrees = percentage_basis.get<Angle>().percentage_of(other.m_value.get<Percentage>()).to_degrees();
  301. if (op == SumOperation::Add)
  302. m_value = Angle::make_degrees(this_degrees + other_degrees);
  303. else
  304. m_value = Angle::make_degrees(this_degrees - other_degrees);
  305. }
  306. },
  307. [&](Frequency const& frequency) {
  308. auto this_hertz = frequency.to_hertz();
  309. if (other.m_value.has<Frequency>()) {
  310. auto other_hertz = other.m_value.get<Frequency>().to_hertz();
  311. if (op == SumOperation::Add)
  312. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  313. else
  314. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  315. } else {
  316. VERIFY(percentage_basis.has<Frequency>());
  317. auto other_hertz = percentage_basis.get<Frequency>().percentage_of(other.m_value.get<Percentage>()).to_hertz();
  318. if (op == SumOperation::Add)
  319. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  320. else
  321. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  322. }
  323. },
  324. [&](Length const& length) {
  325. auto this_px = length.to_px(*layout_node);
  326. if (other.m_value.has<Length>()) {
  327. auto other_px = other.m_value.get<Length>().to_px(*layout_node);
  328. if (op == SumOperation::Add)
  329. m_value = Length::make_px(this_px + other_px);
  330. else
  331. m_value = Length::make_px(this_px - other_px);
  332. } else {
  333. VERIFY(percentage_basis.has<Length>());
  334. auto other_px = percentage_basis.get<Length>().percentage_of(other.m_value.get<Percentage>()).to_px(*layout_node);
  335. if (op == SumOperation::Add)
  336. m_value = Length::make_px(this_px + other_px);
  337. else
  338. m_value = Length::make_px(this_px - other_px);
  339. }
  340. },
  341. [&](Time const& time) {
  342. auto this_seconds = time.to_seconds();
  343. if (other.m_value.has<Time>()) {
  344. auto other_seconds = other.m_value.get<Time>().to_seconds();
  345. if (op == SumOperation::Add)
  346. m_value = Time::make_seconds(this_seconds + other_seconds);
  347. else
  348. m_value = Time::make_seconds(this_seconds - other_seconds);
  349. } else {
  350. VERIFY(percentage_basis.has<Time>());
  351. auto other_seconds = percentage_basis.get<Time>().percentage_of(other.m_value.get<Percentage>()).to_seconds();
  352. if (op == SumOperation::Add)
  353. m_value = Time::make_seconds(this_seconds + other_seconds);
  354. else
  355. m_value = Time::make_seconds(this_seconds - other_seconds);
  356. }
  357. },
  358. [&](Percentage const& percentage) {
  359. if (other.m_value.has<Percentage>()) {
  360. if (op == SumOperation::Add)
  361. m_value = Percentage { percentage.value() + other.m_value.get<Percentage>().value() };
  362. else
  363. m_value = Percentage { percentage.value() - other.m_value.get<Percentage>().value() };
  364. return;
  365. }
  366. // Other side isn't a percentage, so the easiest way to handle it without duplicating all the logic, is just to swap `this` and `other`.
  367. CalculationResult new_value = other;
  368. if (op == SumOperation::Add) {
  369. new_value.add(*this, layout_node, percentage_basis);
  370. } else {
  371. // Turn 'this - other' into '-other + this', as 'A + B == B + A', but 'A - B != B - A'
  372. new_value.multiply_by({ Number { Number::Type::Integer, -1.0f } }, layout_node);
  373. new_value.add(*this, layout_node, percentage_basis);
  374. }
  375. *this = new_value;
  376. });
  377. }
  378. void CalculatedStyleValue::CalculationResult::multiply_by(CalculationResult const& other, Layout::Node const* layout_node)
  379. {
  380. // We know from validation when resolving the type, that at least one side must be a <number> or <integer>.
  381. // Both of these are represented as a float.
  382. VERIFY(m_value.has<Number>() || other.m_value.has<Number>());
  383. bool other_is_number = other.m_value.has<Number>();
  384. m_value.visit(
  385. [&](Number const& number) {
  386. if (other_is_number) {
  387. m_value = number * other.m_value.get<Number>();
  388. } else {
  389. // Avoid duplicating all the logic by swapping `this` and `other`.
  390. CalculationResult new_value = other;
  391. new_value.multiply_by(*this, layout_node);
  392. *this = new_value;
  393. }
  394. },
  395. [&](Angle const& angle) {
  396. m_value = Angle::make_degrees(angle.to_degrees() * other.m_value.get<Number>().value());
  397. },
  398. [&](Frequency const& frequency) {
  399. m_value = Frequency::make_hertz(frequency.to_hertz() * other.m_value.get<Number>().value());
  400. },
  401. [&](Length const& length) {
  402. VERIFY(layout_node);
  403. m_value = Length::make_px(length.to_px(*layout_node) * other.m_value.get<Number>().value());
  404. },
  405. [&](Time const& time) {
  406. m_value = Time::make_seconds(time.to_seconds() * other.m_value.get<Number>().value());
  407. },
  408. [&](Percentage const& percentage) {
  409. m_value = Percentage { percentage.value() * other.m_value.get<Number>().value() };
  410. });
  411. }
  412. void CalculatedStyleValue::CalculationResult::divide_by(CalculationResult const& other, Layout::Node const* layout_node)
  413. {
  414. // We know from validation when resolving the type, that `other` must be a <number> or <integer>.
  415. // Both of these are represented as a Number.
  416. auto denominator = other.m_value.get<Number>().value();
  417. // FIXME: Dividing by 0 is invalid, and should be caught during parsing.
  418. VERIFY(denominator != 0.0f);
  419. m_value.visit(
  420. [&](Number const& number) {
  421. m_value = Number {
  422. Number::Type::Number,
  423. number.value() / denominator
  424. };
  425. },
  426. [&](Angle const& angle) {
  427. m_value = Angle::make_degrees(angle.to_degrees() / denominator);
  428. },
  429. [&](Frequency const& frequency) {
  430. m_value = Frequency::make_hertz(frequency.to_hertz() / denominator);
  431. },
  432. [&](Length const& length) {
  433. VERIFY(layout_node);
  434. m_value = Length::make_px(length.to_px(*layout_node) / denominator);
  435. },
  436. [&](Time const& time) {
  437. m_value = Time::make_seconds(time.to_seconds() / denominator);
  438. },
  439. [&](Percentage const& percentage) {
  440. m_value = Percentage { percentage.value() / denominator };
  441. });
  442. }
  443. ErrorOr<String> CalculatedStyleValue::to_string() const
  444. {
  445. return String::formatted("calc({})", TRY(m_expression->to_string()));
  446. }
  447. bool CalculatedStyleValue::equals(StyleValue const& other) const
  448. {
  449. if (type() != other.type())
  450. return false;
  451. // This is a case where comparing the strings actually makes sense.
  452. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  453. }
  454. ErrorOr<String> CalculatedStyleValue::CalcNumberValue::to_string() const
  455. {
  456. return value.visit(
  457. [](Number const& number) -> ErrorOr<String> { return String::number(number.value()); },
  458. [](NonnullOwnPtr<CalcNumberSum> const& sum) -> ErrorOr<String> { return String::formatted("({})", TRY(sum->to_string())); });
  459. }
  460. ErrorOr<String> CalculatedStyleValue::CalcValue::to_string() const
  461. {
  462. return value.visit(
  463. [](Number const& number) -> ErrorOr<String> { return String::number(number.value()); },
  464. [](NonnullOwnPtr<CalcSum> const& sum) -> ErrorOr<String> { return String::formatted("({})", TRY(sum->to_string())); },
  465. [](auto const& v) -> ErrorOr<String> { return v.to_string(); });
  466. }
  467. ErrorOr<String> CalculatedStyleValue::CalcSum::to_string() const
  468. {
  469. StringBuilder builder;
  470. TRY(builder.try_append(TRY(first_calc_product->to_string())));
  471. for (auto const& item : zero_or_more_additional_calc_products)
  472. TRY(builder.try_append(TRY(item->to_string())));
  473. return builder.to_string();
  474. }
  475. ErrorOr<String> CalculatedStyleValue::CalcNumberSum::to_string() const
  476. {
  477. StringBuilder builder;
  478. TRY(builder.try_append(TRY(first_calc_number_product->to_string())));
  479. for (auto const& item : zero_or_more_additional_calc_number_products)
  480. TRY(builder.try_append(TRY(item->to_string())));
  481. return builder.to_string();
  482. }
  483. ErrorOr<String> CalculatedStyleValue::CalcProduct::to_string() const
  484. {
  485. StringBuilder builder;
  486. TRY(builder.try_append(TRY(first_calc_value.to_string())));
  487. for (auto const& item : zero_or_more_additional_calc_values)
  488. TRY(builder.try_append(TRY(item->to_string())));
  489. return builder.to_string();
  490. }
  491. ErrorOr<String> CalculatedStyleValue::CalcSumPartWithOperator::to_string() const
  492. {
  493. return String::formatted(" {} {}", op == SumOperation::Add ? "+"sv : "-"sv, TRY(value->to_string()));
  494. }
  495. ErrorOr<String> CalculatedStyleValue::CalcProductPartWithOperator::to_string() const
  496. {
  497. auto value_string = TRY(value.visit(
  498. [](CalcValue const& v) { return v.to_string(); },
  499. [](CalcNumberValue const& v) { return v.to_string(); }));
  500. return String::formatted(" {} {}", op == ProductOperation::Multiply ? "*"sv : "/"sv, value_string);
  501. }
  502. ErrorOr<String> CalculatedStyleValue::CalcNumberProduct::to_string() const
  503. {
  504. StringBuilder builder;
  505. TRY(builder.try_append(TRY(first_calc_number_value.to_string())));
  506. for (auto const& item : zero_or_more_additional_calc_number_values)
  507. TRY(builder.try_append(TRY(item->to_string())));
  508. return builder.to_string();
  509. }
  510. ErrorOr<String> CalculatedStyleValue::CalcNumberProductPartWithOperator::to_string() const
  511. {
  512. return String::formatted(" {} {}", op == ProductOperation::Multiply ? "*"sv : "/"sv, TRY(value.to_string()));
  513. }
  514. ErrorOr<String> CalculatedStyleValue::CalcNumberSumPartWithOperator::to_string() const
  515. {
  516. return String::formatted(" {} {}", op == SumOperation::Add ? "+"sv : "-"sv, TRY(value->to_string()));
  517. }
  518. Optional<Angle> CalculatedStyleValue::resolve_angle() const
  519. {
  520. auto result = m_expression->resolve(nullptr, {});
  521. if (result.value().has<Angle>())
  522. return result.value().get<Angle>();
  523. return {};
  524. }
  525. Optional<Angle> CalculatedStyleValue::resolve_angle_percentage(Angle const& percentage_basis) const
  526. {
  527. auto result = m_expression->resolve(nullptr, percentage_basis);
  528. return result.value().visit(
  529. [&](Angle const& angle) -> Optional<Angle> {
  530. return angle;
  531. },
  532. [&](Percentage const& percentage) -> Optional<Angle> {
  533. return percentage_basis.percentage_of(percentage);
  534. },
  535. [&](auto const&) -> Optional<Angle> {
  536. return {};
  537. });
  538. }
  539. Optional<Frequency> CalculatedStyleValue::resolve_frequency() const
  540. {
  541. auto result = m_expression->resolve(nullptr, {});
  542. if (result.value().has<Frequency>())
  543. return result.value().get<Frequency>();
  544. return {};
  545. }
  546. Optional<Frequency> CalculatedStyleValue::resolve_frequency_percentage(Frequency const& percentage_basis) const
  547. {
  548. auto result = m_expression->resolve(nullptr, percentage_basis);
  549. return result.value().visit(
  550. [&](Frequency const& frequency) -> Optional<Frequency> {
  551. return frequency;
  552. },
  553. [&](Percentage const& percentage) -> Optional<Frequency> {
  554. return percentage_basis.percentage_of(percentage);
  555. },
  556. [&](auto const&) -> Optional<Frequency> {
  557. return {};
  558. });
  559. }
  560. Optional<Length> CalculatedStyleValue::resolve_length(Layout::Node const& layout_node) const
  561. {
  562. auto result = m_expression->resolve(&layout_node, {});
  563. if (result.value().has<Length>())
  564. return result.value().get<Length>();
  565. return {};
  566. }
  567. Optional<Length> CalculatedStyleValue::resolve_length_percentage(Layout::Node const& layout_node, Length const& percentage_basis) const
  568. {
  569. auto result = m_expression->resolve(&layout_node, percentage_basis);
  570. return result.value().visit(
  571. [&](Length const& length) -> Optional<Length> {
  572. return length;
  573. },
  574. [&](Percentage const& percentage) -> Optional<Length> {
  575. return percentage_basis.percentage_of(percentage);
  576. },
  577. [&](auto const&) -> Optional<Length> {
  578. return {};
  579. });
  580. }
  581. Optional<Percentage> CalculatedStyleValue::resolve_percentage() const
  582. {
  583. auto result = m_expression->resolve(nullptr, {});
  584. if (result.value().has<Percentage>())
  585. return result.value().get<Percentage>();
  586. return {};
  587. }
  588. Optional<Time> CalculatedStyleValue::resolve_time() const
  589. {
  590. auto result = m_expression->resolve(nullptr, {});
  591. if (result.value().has<Time>())
  592. return result.value().get<Time>();
  593. return {};
  594. }
  595. Optional<Time> CalculatedStyleValue::resolve_time_percentage(Time const& percentage_basis) const
  596. {
  597. auto result = m_expression->resolve(nullptr, percentage_basis);
  598. return result.value().visit(
  599. [&](Time const& time) -> Optional<Time> {
  600. return time;
  601. },
  602. [&](auto const&) -> Optional<Time> {
  603. return {};
  604. });
  605. }
  606. Optional<float> CalculatedStyleValue::resolve_number()
  607. {
  608. auto result = m_expression->resolve(nullptr, {});
  609. if (result.value().has<Number>())
  610. return result.value().get<Number>().value();
  611. return {};
  612. }
  613. Optional<i64> CalculatedStyleValue::resolve_integer()
  614. {
  615. auto result = m_expression->resolve(nullptr, {});
  616. if (result.value().has<Number>())
  617. return result.value().get<Number>().integer_value();
  618. return {};
  619. }
  620. static bool is_number(CalculatedStyleValue::ResolvedType type)
  621. {
  622. return type == CalculatedStyleValue::ResolvedType::Number || type == CalculatedStyleValue::ResolvedType::Integer;
  623. }
  624. static bool is_dimension(CalculatedStyleValue::ResolvedType type)
  625. {
  626. return type != CalculatedStyleValue::ResolvedType::Number
  627. && type != CalculatedStyleValue::ResolvedType::Integer
  628. && type != CalculatedStyleValue::ResolvedType::Percentage;
  629. }
  630. template<typename SumWithOperator>
  631. static Optional<CalculatedStyleValue::ResolvedType> resolve_sum_type(CalculatedStyleValue::ResolvedType first_type, Vector<NonnullOwnPtr<SumWithOperator>> const& zero_or_more_additional_products)
  632. {
  633. auto type = first_type;
  634. for (auto const& product : zero_or_more_additional_products) {
  635. auto maybe_product_type = product->resolved_type();
  636. if (!maybe_product_type.has_value())
  637. return {};
  638. auto product_type = maybe_product_type.value();
  639. // At + or -, check that both sides have the same type, or that one side is a <number> and the other is an <integer>.
  640. // If both sides are the same type, resolve to that type.
  641. if (product_type == type)
  642. continue;
  643. // If one side is a <number> and the other is an <integer>, resolve to <number>.
  644. if (is_number(type) && is_number(product_type)) {
  645. type = CalculatedStyleValue::ResolvedType::Number;
  646. continue;
  647. }
  648. // FIXME: calc() handles <percentage> by allowing them to pretend to be whatever <dimension> type is allowed at this location.
  649. // Since we can't easily check what that type is, we just allow <percentage> to combine with any other <dimension> type.
  650. if (type == CalculatedStyleValue::ResolvedType::Percentage && is_dimension(product_type)) {
  651. type = product_type;
  652. continue;
  653. }
  654. if (is_dimension(type) && product_type == CalculatedStyleValue::ResolvedType::Percentage)
  655. continue;
  656. return {};
  657. }
  658. return type;
  659. }
  660. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcSum::resolved_type() const
  661. {
  662. auto maybe_type = first_calc_product->resolved_type();
  663. if (!maybe_type.has_value())
  664. return {};
  665. auto type = maybe_type.value();
  666. return resolve_sum_type(type, zero_or_more_additional_calc_products);
  667. }
  668. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  669. Gfx::FloatRect EdgeRect::resolved(Layout::Node const& layout_node, Gfx::FloatRect border_box) const
  670. {
  671. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  672. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  673. // <left> specify offsets from the left border edge of the box.
  674. // The value 'auto' means that a given edge of the clipping region will be the same as the edge
  675. // of the element's generated border box (i.e., 'auto' means the same as '0' for <top> and
  676. // <left>, the same as the used value of the height plus the sum of vertical padding and border
  677. // widths for <bottom>, and the same as the used value of the width plus the sum of the
  678. // horizontal padding and border widths for <right>, such that four 'auto' values result in the
  679. // clipping region being the same as the element's border box).
  680. auto left = border_box.left() + (left_edge.is_auto() ? 0 : left_edge.to_px(layout_node)).value();
  681. auto top = border_box.top() + (top_edge.is_auto() ? 0 : top_edge.to_px(layout_node)).value();
  682. auto right = border_box.left() + (right_edge.is_auto() ? border_box.width() : right_edge.to_px(layout_node)).value();
  683. auto bottom = border_box.top() + (bottom_edge.is_auto() ? border_box.height() : bottom_edge.to_px(layout_node)).value();
  684. return Gfx::FloatRect {
  685. left,
  686. top,
  687. right - left,
  688. bottom - top
  689. };
  690. }
  691. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberSum::resolved_type() const
  692. {
  693. auto maybe_type = first_calc_number_product->resolved_type();
  694. if (!maybe_type.has_value())
  695. return {};
  696. auto type = maybe_type.value();
  697. return resolve_sum_type(type, zero_or_more_additional_calc_number_products);
  698. }
  699. template<typename ProductWithOperator>
  700. static Optional<CalculatedStyleValue::ResolvedType> resolve_product_type(CalculatedStyleValue::ResolvedType first_type, Vector<NonnullOwnPtr<ProductWithOperator>> const& zero_or_more_additional_values)
  701. {
  702. auto type = first_type;
  703. for (auto const& value : zero_or_more_additional_values) {
  704. auto maybe_value_type = value->resolved_type();
  705. if (!maybe_value_type.has_value())
  706. return {};
  707. auto value_type = maybe_value_type.value();
  708. if (value->op == CalculatedStyleValue::ProductOperation::Multiply) {
  709. // At *, check that at least one side is <number>.
  710. if (!(is_number(type) || is_number(value_type)))
  711. return {};
  712. // If both sides are <integer>, resolve to <integer>.
  713. if (type == CalculatedStyleValue::ResolvedType::Integer && value_type == CalculatedStyleValue::ResolvedType::Integer) {
  714. type = CalculatedStyleValue::ResolvedType::Integer;
  715. } else {
  716. // Otherwise, resolve to the type of the other side.
  717. if (is_number(type))
  718. type = value_type;
  719. }
  720. continue;
  721. } else {
  722. VERIFY(value->op == CalculatedStyleValue::ProductOperation::Divide);
  723. // At /, check that the right side is <number>.
  724. if (!is_number(value_type))
  725. return {};
  726. // If the left side is <integer>, resolve to <number>.
  727. if (type == CalculatedStyleValue::ResolvedType::Integer) {
  728. type = CalculatedStyleValue::ResolvedType::Number;
  729. } else {
  730. // Otherwise, resolve to the type of the left side.
  731. }
  732. // FIXME: Division by zero makes the whole calc() expression invalid.
  733. }
  734. }
  735. return type;
  736. }
  737. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcProduct::resolved_type() const
  738. {
  739. auto maybe_type = first_calc_value.resolved_type();
  740. if (!maybe_type.has_value())
  741. return {};
  742. auto type = maybe_type.value();
  743. return resolve_product_type(type, zero_or_more_additional_calc_values);
  744. }
  745. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcSumPartWithOperator::resolved_type() const
  746. {
  747. return value->resolved_type();
  748. }
  749. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberProduct::resolved_type() const
  750. {
  751. auto maybe_type = first_calc_number_value.resolved_type();
  752. if (!maybe_type.has_value())
  753. return {};
  754. auto type = maybe_type.value();
  755. return resolve_product_type(type, zero_or_more_additional_calc_number_values);
  756. }
  757. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberProductPartWithOperator::resolved_type() const
  758. {
  759. return value.resolved_type();
  760. }
  761. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberSumPartWithOperator::resolved_type() const
  762. {
  763. return value->resolved_type();
  764. }
  765. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcProductPartWithOperator::resolved_type() const
  766. {
  767. return value.visit(
  768. [](CalcValue const& calc_value) {
  769. return calc_value.resolved_type();
  770. },
  771. [](CalcNumberValue const& calc_number_value) {
  772. return calc_number_value.resolved_type();
  773. });
  774. }
  775. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcValue::resolved_type() const
  776. {
  777. return value.visit(
  778. [](Number const& number) -> Optional<CalculatedStyleValue::ResolvedType> {
  779. return { number.is_integer() ? ResolvedType::Integer : ResolvedType::Number };
  780. },
  781. [](Angle const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Angle }; },
  782. [](Frequency const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Frequency }; },
  783. [](Length const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Length }; },
  784. [](Percentage const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Percentage }; },
  785. [](Time const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Time }; },
  786. [](NonnullOwnPtr<CalcSum> const& sum) { return sum->resolved_type(); });
  787. }
  788. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberValue::resolved_type() const
  789. {
  790. return value.visit(
  791. [](Number const& number) -> Optional<CalculatedStyleValue::ResolvedType> {
  792. return { number.is_integer() ? ResolvedType::Integer : ResolvedType::Number };
  793. },
  794. [](NonnullOwnPtr<CalcNumberSum> const& sum) { return sum->resolved_type(); });
  795. }
  796. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberValue::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  797. {
  798. return value.visit(
  799. [&](Number const& number) -> CalculatedStyleValue::CalculationResult {
  800. return CalculatedStyleValue::CalculationResult { number };
  801. },
  802. [&](NonnullOwnPtr<CalcNumberSum> const& sum) -> CalculatedStyleValue::CalculationResult {
  803. return sum->resolve(layout_node, percentage_basis);
  804. });
  805. }
  806. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcValue::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  807. {
  808. return value.visit(
  809. [&](NonnullOwnPtr<CalcSum> const& sum) -> CalculatedStyleValue::CalculationResult {
  810. return sum->resolve(layout_node, percentage_basis);
  811. },
  812. [&](auto const& v) -> CalculatedStyleValue::CalculationResult {
  813. return CalculatedStyleValue::CalculationResult { v };
  814. });
  815. }
  816. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcSum::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  817. {
  818. auto value = first_calc_product->resolve(layout_node, percentage_basis);
  819. for (auto& additional_product : zero_or_more_additional_calc_products) {
  820. auto additional_value = additional_product->resolve(layout_node, percentage_basis);
  821. if (additional_product->op == CalculatedStyleValue::SumOperation::Add)
  822. value.add(additional_value, layout_node, percentage_basis);
  823. else if (additional_product->op == CalculatedStyleValue::SumOperation::Subtract)
  824. value.subtract(additional_value, layout_node, percentage_basis);
  825. else
  826. VERIFY_NOT_REACHED();
  827. }
  828. return value;
  829. }
  830. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberSum::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  831. {
  832. auto value = first_calc_number_product->resolve(layout_node, percentage_basis);
  833. for (auto& additional_product : zero_or_more_additional_calc_number_products) {
  834. auto additional_value = additional_product->resolve(layout_node, percentage_basis);
  835. if (additional_product->op == CSS::CalculatedStyleValue::SumOperation::Add)
  836. value.add(additional_value, layout_node, percentage_basis);
  837. else if (additional_product->op == CalculatedStyleValue::SumOperation::Subtract)
  838. value.subtract(additional_value, layout_node, percentage_basis);
  839. else
  840. VERIFY_NOT_REACHED();
  841. }
  842. return value;
  843. }
  844. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcProduct::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  845. {
  846. auto value = first_calc_value.resolve(layout_node, percentage_basis);
  847. for (auto& additional_value : zero_or_more_additional_calc_values) {
  848. additional_value->value.visit(
  849. [&](CalculatedStyleValue::CalcValue const& calc_value) {
  850. VERIFY(additional_value->op == CalculatedStyleValue::ProductOperation::Multiply);
  851. auto resolved_value = calc_value.resolve(layout_node, percentage_basis);
  852. value.multiply_by(resolved_value, layout_node);
  853. },
  854. [&](CalculatedStyleValue::CalcNumberValue const& calc_number_value) {
  855. VERIFY(additional_value->op == CalculatedStyleValue::ProductOperation::Divide);
  856. auto resolved_calc_number_value = calc_number_value.resolve(layout_node, percentage_basis);
  857. // FIXME: Checking for division by 0 should happen during parsing.
  858. VERIFY(resolved_calc_number_value.value().get<Number>().value() != 0.0f);
  859. value.divide_by(resolved_calc_number_value, layout_node);
  860. });
  861. }
  862. return value;
  863. }
  864. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberProduct::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  865. {
  866. auto value = first_calc_number_value.resolve(layout_node, percentage_basis);
  867. for (auto& additional_number_value : zero_or_more_additional_calc_number_values) {
  868. auto additional_value = additional_number_value->resolve(layout_node, percentage_basis);
  869. if (additional_number_value->op == CalculatedStyleValue::ProductOperation::Multiply)
  870. value.multiply_by(additional_value, layout_node);
  871. else if (additional_number_value->op == CalculatedStyleValue::ProductOperation::Divide)
  872. value.divide_by(additional_value, layout_node);
  873. else
  874. VERIFY_NOT_REACHED();
  875. }
  876. return value;
  877. }
  878. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcProductPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  879. {
  880. return value.visit(
  881. [&](CalcValue const& calc_value) {
  882. return calc_value.resolve(layout_node, percentage_basis);
  883. },
  884. [&](CalcNumberValue const& calc_number_value) {
  885. return calc_number_value.resolve(layout_node, percentage_basis);
  886. });
  887. }
  888. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcSumPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  889. {
  890. return value->resolve(layout_node, percentage_basis);
  891. }
  892. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberProductPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  893. {
  894. return value.resolve(layout_node, percentage_basis);
  895. }
  896. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberSumPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  897. {
  898. return value->resolve(layout_node, percentage_basis);
  899. }
  900. static ErrorOr<void> serialize_color_stop_list(StringBuilder& builder, auto const& color_stop_list)
  901. {
  902. bool first = true;
  903. for (auto const& element : color_stop_list) {
  904. if (!first)
  905. TRY(builder.try_append(", "sv));
  906. if (element.transition_hint.has_value())
  907. TRY(builder.try_appendff("{}, "sv, TRY(element.transition_hint->value.to_string())));
  908. TRY(serialize_a_srgb_value(builder, element.color_stop.color));
  909. for (auto position : Array { &element.color_stop.position, &element.color_stop.second_position }) {
  910. if (position->has_value())
  911. TRY(builder.try_appendff(" {}"sv, TRY((*position)->to_string())));
  912. }
  913. first = false;
  914. }
  915. return {};
  916. }
  917. CSSPixelPoint PositionValue::resolved(Layout::Node const& node, CSSPixelRect const& rect) const
  918. {
  919. // Note: A preset + a none default x/y_relative_to is impossible in the syntax (and makes little sense)
  920. CSSPixels x = horizontal_position.visit(
  921. [&](HorizontalPreset preset) -> CSSPixels {
  922. return rect.width() * [&] {
  923. switch (preset) {
  924. case HorizontalPreset::Left:
  925. return 0.0f;
  926. case HorizontalPreset::Center:
  927. return 0.5f;
  928. case HorizontalPreset::Right:
  929. return 1.0f;
  930. default:
  931. VERIFY_NOT_REACHED();
  932. }
  933. }();
  934. },
  935. [&](LengthPercentage length_percentage) -> CSSPixels {
  936. return length_percentage.resolved(node, Length::make_px(rect.width())).to_px(node);
  937. });
  938. CSSPixels y = vertical_position.visit(
  939. [&](VerticalPreset preset) -> CSSPixels {
  940. return rect.height() * [&] {
  941. switch (preset) {
  942. case VerticalPreset::Top:
  943. return 0.0f;
  944. case VerticalPreset::Center:
  945. return 0.5f;
  946. case VerticalPreset::Bottom:
  947. return 1.0f;
  948. default:
  949. VERIFY_NOT_REACHED();
  950. }
  951. }();
  952. },
  953. [&](LengthPercentage length_percentage) -> CSSPixels {
  954. return length_percentage.resolved(node, Length::make_px(rect.height())).to_px(node);
  955. });
  956. if (x_relative_to == HorizontalEdge::Right)
  957. x = rect.width() - x;
  958. if (y_relative_to == VerticalEdge::Bottom)
  959. y = rect.height() - y;
  960. return CSSPixelPoint { rect.x() + x, rect.y() + y };
  961. }
  962. ErrorOr<void> PositionValue::serialize(StringBuilder& builder) const
  963. {
  964. // Note: This means our serialization with simplify any with explicit edges that are just `top left`.
  965. bool has_relative_edges = x_relative_to == HorizontalEdge::Right || y_relative_to == VerticalEdge::Bottom;
  966. if (has_relative_edges)
  967. TRY(builder.try_append(x_relative_to == HorizontalEdge::Left ? "left "sv : "right "sv));
  968. TRY(horizontal_position.visit(
  969. [&](HorizontalPreset preset) -> ErrorOr<void> {
  970. return builder.try_append([&] {
  971. switch (preset) {
  972. case HorizontalPreset::Left:
  973. return "left"sv;
  974. case HorizontalPreset::Center:
  975. return "center"sv;
  976. case HorizontalPreset::Right:
  977. return "right"sv;
  978. default:
  979. VERIFY_NOT_REACHED();
  980. }
  981. }());
  982. },
  983. [&](LengthPercentage length_percentage) -> ErrorOr<void> {
  984. return builder.try_appendff(TRY(length_percentage.to_string()));
  985. }));
  986. TRY(builder.try_append(' '));
  987. if (has_relative_edges)
  988. TRY(builder.try_append(y_relative_to == VerticalEdge::Top ? "top "sv : "bottom "sv));
  989. TRY(vertical_position.visit(
  990. [&](VerticalPreset preset) -> ErrorOr<void> {
  991. return builder.try_append([&] {
  992. switch (preset) {
  993. case VerticalPreset::Top:
  994. return "top"sv;
  995. case VerticalPreset::Center:
  996. return "center"sv;
  997. case VerticalPreset::Bottom:
  998. return "bottom"sv;
  999. default:
  1000. VERIFY_NOT_REACHED();
  1001. }
  1002. }());
  1003. },
  1004. [&](LengthPercentage length_percentage) -> ErrorOr<void> {
  1005. return builder.try_append(TRY(length_percentage.to_string()));
  1006. }));
  1007. return {};
  1008. }
  1009. ErrorOr<String> RadialGradientStyleValue::to_string() const
  1010. {
  1011. StringBuilder builder;
  1012. if (is_repeating())
  1013. TRY(builder.try_append("repeating-"sv));
  1014. TRY(builder.try_appendff("radial-gradient({} "sv,
  1015. m_properties.ending_shape == EndingShape::Circle ? "circle"sv : "ellipse"sv));
  1016. TRY(m_properties.size.visit(
  1017. [&](Extent extent) -> ErrorOr<void> {
  1018. return builder.try_append([&] {
  1019. switch (extent) {
  1020. case Extent::ClosestCorner:
  1021. return "closest-corner"sv;
  1022. case Extent::ClosestSide:
  1023. return "closest-side"sv;
  1024. case Extent::FarthestCorner:
  1025. return "farthest-corner"sv;
  1026. case Extent::FarthestSide:
  1027. return "farthest-side"sv;
  1028. default:
  1029. VERIFY_NOT_REACHED();
  1030. }
  1031. }());
  1032. },
  1033. [&](CircleSize const& circle_size) -> ErrorOr<void> {
  1034. return builder.try_append(TRY(circle_size.radius.to_string()));
  1035. },
  1036. [&](EllipseSize const& ellipse_size) -> ErrorOr<void> {
  1037. return builder.try_appendff("{} {}", TRY(ellipse_size.radius_a.to_string()), TRY(ellipse_size.radius_b.to_string()));
  1038. }));
  1039. if (m_properties.position != PositionValue::center()) {
  1040. TRY(builder.try_appendff(" at "sv));
  1041. TRY(m_properties.position.serialize(builder));
  1042. }
  1043. TRY(builder.try_append(", "sv));
  1044. TRY(serialize_color_stop_list(builder, m_properties.color_stop_list));
  1045. TRY(builder.try_append(')'));
  1046. return builder.to_string();
  1047. }
  1048. Gfx::FloatSize RadialGradientStyleValue::resolve_size(Layout::Node const& node, Gfx::FloatPoint center, Gfx::FloatRect const& size) const
  1049. {
  1050. auto const side_shape = [&](auto distance_function) {
  1051. auto const distance_from = [&](float v, float a, float b, auto distance_function) {
  1052. return distance_function(fabs(a - v), fabs(b - v));
  1053. };
  1054. auto x_dist = distance_from(center.x(), size.left(), size.right(), distance_function);
  1055. auto y_dist = distance_from(center.y(), size.top(), size.bottom(), distance_function);
  1056. if (m_properties.ending_shape == EndingShape::Circle) {
  1057. auto dist = distance_function(x_dist, y_dist);
  1058. return Gfx::FloatSize { dist, dist };
  1059. } else {
  1060. return Gfx::FloatSize { x_dist, y_dist };
  1061. }
  1062. };
  1063. auto const closest_side_shape = [&] {
  1064. return side_shape(AK::min<float>);
  1065. };
  1066. auto const farthest_side_shape = [&] {
  1067. return side_shape(AK::max<float>);
  1068. };
  1069. auto const corner_distance = [&](auto distance_compare, Gfx::FloatPoint& corner) {
  1070. auto top_left_distance = size.top_left().distance_from(center);
  1071. auto top_right_distance = size.top_right().distance_from(center);
  1072. auto bottom_right_distance = size.bottom_right().distance_from(center);
  1073. auto bottom_left_distance = size.bottom_left().distance_from(center);
  1074. auto distance = top_left_distance;
  1075. if (distance_compare(top_right_distance, distance)) {
  1076. corner = size.top_right();
  1077. distance = top_right_distance;
  1078. }
  1079. if (distance_compare(bottom_right_distance, distance)) {
  1080. corner = size.top_right();
  1081. distance = bottom_right_distance;
  1082. }
  1083. if (distance_compare(bottom_left_distance, distance)) {
  1084. corner = size.top_right();
  1085. distance = bottom_left_distance;
  1086. }
  1087. return distance;
  1088. };
  1089. auto const closest_corner_distance = [&](Gfx::FloatPoint& corner) {
  1090. return corner_distance([](float a, float b) { return a < b; }, corner);
  1091. };
  1092. auto const farthest_corner_distance = [&](Gfx::FloatPoint& corner) {
  1093. return corner_distance([](float a, float b) { return a > b; }, corner);
  1094. };
  1095. auto const corner_shape = [&](auto corner_distance, auto get_shape) {
  1096. Gfx::FloatPoint corner {};
  1097. auto distance = corner_distance(corner);
  1098. if (m_properties.ending_shape == EndingShape::Ellipse) {
  1099. auto shape = get_shape();
  1100. auto aspect_ratio = shape.width() / shape.height();
  1101. auto p = corner - center;
  1102. auto radius_a = AK::sqrt(p.y() * p.y() * aspect_ratio * aspect_ratio + p.x() * p.x());
  1103. auto radius_b = radius_a / aspect_ratio;
  1104. return Gfx::FloatSize { radius_a, radius_b };
  1105. }
  1106. return Gfx::FloatSize { distance, distance };
  1107. };
  1108. // https://w3c.github.io/csswg-drafts/css-images/#radial-gradient-syntax
  1109. auto resolved_size = m_properties.size.visit(
  1110. [&](Extent extent) {
  1111. switch (extent) {
  1112. case Extent::ClosestSide:
  1113. // The ending shape is sized so that it exactly meets the side of the gradient box closest to the gradient’s center.
  1114. // If the shape is an ellipse, it exactly meets the closest side in each dimension.
  1115. return closest_side_shape();
  1116. case Extent::ClosestCorner:
  1117. // The ending shape is sized so that it passes through the corner of the gradient box closest to the gradient’s center.
  1118. // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified
  1119. return corner_shape(closest_corner_distance, closest_side_shape);
  1120. case Extent::FarthestCorner:
  1121. // Same as closest-corner, except the ending shape is sized based on the farthest corner.
  1122. // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
  1123. return corner_shape(farthest_corner_distance, farthest_side_shape);
  1124. case Extent::FarthestSide:
  1125. // Same as closest-side, except the ending shape is sized based on the farthest side(s).
  1126. return farthest_side_shape();
  1127. default:
  1128. VERIFY_NOT_REACHED();
  1129. }
  1130. },
  1131. [&](CircleSize const& circle_size) {
  1132. auto radius = circle_size.radius.to_px(node);
  1133. return Gfx::FloatSize { radius, radius };
  1134. },
  1135. [&](EllipseSize const& ellipse_size) {
  1136. auto radius_a = ellipse_size.radius_a.resolved(node, CSS::Length::make_px(size.width())).to_px(node);
  1137. auto radius_b = ellipse_size.radius_b.resolved(node, CSS::Length::make_px(size.height())).to_px(node);
  1138. return Gfx::FloatSize { radius_a, radius_b };
  1139. });
  1140. // Handle degenerate cases
  1141. // https://w3c.github.io/csswg-drafts/css-images/#degenerate-radials
  1142. constexpr auto arbitrary_small_number = 1e-10;
  1143. constexpr auto arbitrary_large_number = 1e10;
  1144. // If the ending shape is a circle with zero radius:
  1145. if (m_properties.ending_shape == EndingShape::Circle && resolved_size.is_empty()) {
  1146. // Render as if the ending shape was a circle whose radius was an arbitrary very small number greater than zero.
  1147. // This will make the gradient continue to look like a circle.
  1148. return Gfx::FloatSize { arbitrary_small_number, arbitrary_small_number };
  1149. }
  1150. // If the ending shape has zero width (regardless of the height):
  1151. if (resolved_size.width() <= 0) {
  1152. // Render as if the ending shape was an ellipse whose height was an arbitrary very large number
  1153. // and whose width was an arbitrary very small number greater than zero.
  1154. // This will make the gradient look similar to a horizontal linear gradient that is mirrored across the center of the ellipse.
  1155. // It also means that all color-stop positions specified with a percentage resolve to 0px.
  1156. return Gfx::FloatSize { arbitrary_small_number, arbitrary_large_number };
  1157. }
  1158. // Otherwise, if the ending shape has zero height:
  1159. if (resolved_size.height() <= 0) {
  1160. // Render as if the ending shape was an ellipse whose width was an arbitrary very large number and whose height
  1161. // was an arbitrary very small number greater than zero. This will make the gradient look like a solid-color image equal
  1162. // to the color of the last color-stop, or equal to the average color of the gradient if it’s repeating.
  1163. return Gfx::FloatSize { arbitrary_large_number, arbitrary_small_number };
  1164. }
  1165. return resolved_size;
  1166. }
  1167. void RadialGradientStyleValue::resolve_for_size(Layout::Node const& node, CSSPixelSize paint_size) const
  1168. {
  1169. CSSPixelRect gradient_box { { 0, 0 }, paint_size };
  1170. auto center = m_properties.position.resolved(node, gradient_box).to_type<float>();
  1171. auto gradient_size = resolve_size(node, center, gradient_box.to_type<float>());
  1172. if (m_resolved.has_value() && m_resolved->gradient_size == gradient_size)
  1173. return;
  1174. m_resolved = ResolvedData {
  1175. Painting::resolve_radial_gradient_data(node, gradient_size.to_type<CSSPixels>(), *this),
  1176. gradient_size,
  1177. center,
  1178. };
  1179. }
  1180. bool RadialGradientStyleValue::equals(StyleValue const& other) const
  1181. {
  1182. if (type() != other.type())
  1183. return false;
  1184. auto& other_gradient = other.as_radial_gradient();
  1185. return m_properties == other_gradient.m_properties;
  1186. }
  1187. void RadialGradientStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering) const
  1188. {
  1189. VERIFY(m_resolved.has_value());
  1190. Painting::paint_radial_gradient(context, dest_rect, m_resolved->data,
  1191. context.rounded_device_point(m_resolved->center.to_type<CSSPixels>()),
  1192. context.rounded_device_size(m_resolved->gradient_size.to_type<CSSPixels>()));
  1193. }
  1194. ErrorOr<String> ListStyleStyleValue::to_string() const
  1195. {
  1196. return String::formatted("{} {} {}", TRY(m_properties.position->to_string()), TRY(m_properties.image->to_string()), TRY(m_properties.style_type->to_string()));
  1197. }
  1198. ErrorOr<String> NumericStyleValue::to_string() const
  1199. {
  1200. return m_value.visit(
  1201. [](auto value) {
  1202. return String::formatted("{}", value);
  1203. });
  1204. }
  1205. ErrorOr<String> OverflowStyleValue::to_string() const
  1206. {
  1207. return String::formatted("{} {}", TRY(m_properties.overflow_x->to_string()), TRY(m_properties.overflow_y->to_string()));
  1208. }
  1209. ErrorOr<String> PercentageStyleValue::to_string() const
  1210. {
  1211. return m_percentage.to_string();
  1212. }
  1213. ErrorOr<String> PositionStyleValue::to_string() const
  1214. {
  1215. auto to_string = [](PositionEdge edge) {
  1216. switch (edge) {
  1217. case PositionEdge::Left:
  1218. return "left";
  1219. case PositionEdge::Right:
  1220. return "right";
  1221. case PositionEdge::Top:
  1222. return "top";
  1223. case PositionEdge::Bottom:
  1224. return "bottom";
  1225. }
  1226. VERIFY_NOT_REACHED();
  1227. };
  1228. return String::formatted("{} {} {} {}", to_string(m_properties.edge_x), TRY(m_properties.offset_x.to_string()), to_string(m_properties.edge_y), TRY(m_properties.offset_y.to_string()));
  1229. }
  1230. ErrorOr<String> RectStyleValue::to_string() const
  1231. {
  1232. return String::formatted("rect({} {} {} {})", m_rect.top_edge, m_rect.right_edge, m_rect.bottom_edge, m_rect.left_edge);
  1233. }
  1234. ErrorOr<String> ShadowStyleValue::to_string() const
  1235. {
  1236. StringBuilder builder;
  1237. TRY(builder.try_appendff("{} {} {} {} {}", m_properties.color.to_deprecated_string(), TRY(m_properties.offset_x.to_string()), TRY(m_properties.offset_y.to_string()), TRY(m_properties.blur_radius.to_string()), TRY(m_properties.spread_distance.to_string())));
  1238. if (m_properties.placement == ShadowPlacement::Inner)
  1239. TRY(builder.try_append(" inset"sv));
  1240. return builder.to_string();
  1241. }
  1242. ErrorOr<String> TextDecorationStyleValue::to_string() const
  1243. {
  1244. return String::formatted("{} {} {} {}", TRY(m_properties.line->to_string()), TRY(m_properties.thickness->to_string()), TRY(m_properties.style->to_string()), TRY(m_properties.color->to_string()));
  1245. }
  1246. ErrorOr<String> TransformationStyleValue::to_string() const
  1247. {
  1248. StringBuilder builder;
  1249. TRY(builder.try_append(CSS::to_string(m_properties.transform_function)));
  1250. TRY(builder.try_append('('));
  1251. for (size_t i = 0; i < m_properties.values.size(); ++i) {
  1252. TRY(builder.try_append(TRY(m_properties.values[i]->to_string())));
  1253. if (i != m_properties.values.size() - 1)
  1254. TRY(builder.try_append(", "sv));
  1255. }
  1256. TRY(builder.try_append(')'));
  1257. return builder.to_string();
  1258. }
  1259. bool TransformationStyleValue::Properties::operator==(Properties const& other) const
  1260. {
  1261. return transform_function == other.transform_function && values.span() == other.values.span();
  1262. }
  1263. ErrorOr<String> UnresolvedStyleValue::to_string() const
  1264. {
  1265. StringBuilder builder;
  1266. for (auto& value : m_values)
  1267. TRY(builder.try_append(TRY(value.to_string())));
  1268. return builder.to_string();
  1269. }
  1270. bool UnresolvedStyleValue::equals(StyleValue const& other) const
  1271. {
  1272. if (type() != other.type())
  1273. return false;
  1274. // This is a case where comparing the strings actually makes sense.
  1275. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  1276. }
  1277. bool StyleValueList::Properties::operator==(Properties const& other) const
  1278. {
  1279. return separator == other.separator && values.span() == other.values.span();
  1280. }
  1281. ErrorOr<String> StyleValueList::to_string() const
  1282. {
  1283. auto separator = ""sv;
  1284. switch (m_properties.separator) {
  1285. case Separator::Space:
  1286. separator = " "sv;
  1287. break;
  1288. case Separator::Comma:
  1289. separator = ", "sv;
  1290. break;
  1291. default:
  1292. VERIFY_NOT_REACHED();
  1293. }
  1294. StringBuilder builder;
  1295. for (size_t i = 0; i < m_properties.values.size(); ++i) {
  1296. TRY(builder.try_append(TRY(m_properties.values[i]->to_string())));
  1297. if (i != m_properties.values.size() - 1)
  1298. TRY(builder.try_append(separator));
  1299. }
  1300. return builder.to_string();
  1301. }
  1302. ValueComparingNonnullRefPtr<RectStyleValue> RectStyleValue::create(EdgeRect rect)
  1303. {
  1304. return adopt_ref(*new RectStyleValue(rect));
  1305. }
  1306. ValueComparingNonnullRefPtr<LengthStyleValue> LengthStyleValue::create(Length const& length)
  1307. {
  1308. if (length.is_auto()) {
  1309. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_auto()));
  1310. return value;
  1311. }
  1312. if (length.is_px()) {
  1313. if (length.raw_value() == 0) {
  1314. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_px(0)));
  1315. return value;
  1316. }
  1317. if (length.raw_value() == 1) {
  1318. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_px(1)));
  1319. return value;
  1320. }
  1321. }
  1322. return adopt_ref(*new LengthStyleValue(length));
  1323. }
  1324. Optional<CSS::Length> absolutized_length(CSS::Length const& length, CSSPixelRect const& viewport_rect, Gfx::FontPixelMetrics const& font_metrics, CSSPixels font_size, CSSPixels root_font_size, CSSPixels line_height, CSSPixels root_line_height)
  1325. {
  1326. if (length.is_px())
  1327. return {};
  1328. if (length.is_absolute() || length.is_relative()) {
  1329. auto px = length.to_px(viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height);
  1330. return CSS::Length::make_px(px);
  1331. }
  1332. return {};
  1333. }
  1334. ValueComparingNonnullRefPtr<StyleValue const> StyleValue::absolutized(CSSPixelRect const&, Gfx::FontPixelMetrics const&, CSSPixels, CSSPixels, CSSPixels, CSSPixels) const
  1335. {
  1336. return *this;
  1337. }
  1338. ValueComparingNonnullRefPtr<StyleValue const> LengthStyleValue::absolutized(CSSPixelRect const& viewport_rect, Gfx::FontPixelMetrics const& font_metrics, CSSPixels font_size, CSSPixels root_font_size, CSSPixels line_height, CSSPixels root_line_height) const
  1339. {
  1340. if (auto length = absolutized_length(m_length, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height); length.has_value())
  1341. return LengthStyleValue::create(length.release_value());
  1342. return *this;
  1343. }
  1344. ValueComparingNonnullRefPtr<StyleValue const> ShadowStyleValue::absolutized(CSSPixelRect const& viewport_rect, Gfx::FontPixelMetrics const& font_metrics, CSSPixels font_size, CSSPixels root_font_size, CSSPixels line_height, CSSPixels root_line_height) const
  1345. {
  1346. auto absolutized_offset_x = absolutized_length(m_properties.offset_x, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height).value_or(m_properties.offset_x);
  1347. auto absolutized_offset_y = absolutized_length(m_properties.offset_y, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height).value_or(m_properties.offset_y);
  1348. auto absolutized_blur_radius = absolutized_length(m_properties.blur_radius, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height).value_or(m_properties.blur_radius);
  1349. auto absolutized_spread_distance = absolutized_length(m_properties.spread_distance, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height).value_or(m_properties.spread_distance);
  1350. return ShadowStyleValue::create(m_properties.color, absolutized_offset_x, absolutized_offset_y, absolutized_blur_radius, absolutized_spread_distance, m_properties.placement);
  1351. }
  1352. bool CalculatedStyleValue::contains_percentage() const
  1353. {
  1354. return m_expression->contains_percentage();
  1355. }
  1356. bool CalculatedStyleValue::CalcSum::contains_percentage() const
  1357. {
  1358. if (first_calc_product->contains_percentage())
  1359. return true;
  1360. for (auto& part : zero_or_more_additional_calc_products) {
  1361. if (part->contains_percentage())
  1362. return true;
  1363. }
  1364. return false;
  1365. }
  1366. bool CalculatedStyleValue::CalcSumPartWithOperator::contains_percentage() const
  1367. {
  1368. return value->contains_percentage();
  1369. }
  1370. bool CalculatedStyleValue::CalcProduct::contains_percentage() const
  1371. {
  1372. if (first_calc_value.contains_percentage())
  1373. return true;
  1374. for (auto& part : zero_or_more_additional_calc_values) {
  1375. if (part->contains_percentage())
  1376. return true;
  1377. }
  1378. return false;
  1379. }
  1380. bool CalculatedStyleValue::CalcProductPartWithOperator::contains_percentage() const
  1381. {
  1382. return value.visit(
  1383. [](CalcValue const& value) { return value.contains_percentage(); },
  1384. [](CalcNumberValue const&) { return false; });
  1385. }
  1386. bool CalculatedStyleValue::CalcValue::contains_percentage() const
  1387. {
  1388. return value.visit(
  1389. [](Percentage const&) { return true; },
  1390. [](NonnullOwnPtr<CalcSum> const& sum) { return sum->contains_percentage(); },
  1391. [](auto const&) { return false; });
  1392. }
  1393. bool calculated_style_value_contains_percentage(CalculatedStyleValue const& value)
  1394. {
  1395. return value.contains_percentage();
  1396. }
  1397. }