StyleValue.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  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/DOM/Document.h>
  22. #include <LibWeb/HTML/BrowsingContext.h>
  23. #include <LibWeb/Loader/LoadRequest.h>
  24. #include <LibWeb/Loader/ResourceLoader.h>
  25. #include <LibWeb/Page/Page.h>
  26. #include <LibWeb/Painting/GradientPainting.h>
  27. #include <LibWeb/Platform/Timer.h>
  28. namespace Web::CSS {
  29. StyleValue::StyleValue(Type type)
  30. : m_type(type)
  31. {
  32. }
  33. AbstractImageStyleValue const& StyleValue::as_abstract_image() const
  34. {
  35. VERIFY(is_abstract_image());
  36. return static_cast<AbstractImageStyleValue const&>(*this);
  37. }
  38. AngleStyleValue const& StyleValue::as_angle() const
  39. {
  40. VERIFY(is_angle());
  41. return static_cast<AngleStyleValue const&>(*this);
  42. }
  43. BackgroundStyleValue const& StyleValue::as_background() const
  44. {
  45. VERIFY(is_background());
  46. return static_cast<BackgroundStyleValue const&>(*this);
  47. }
  48. BackgroundRepeatStyleValue const& StyleValue::as_background_repeat() const
  49. {
  50. VERIFY(is_background_repeat());
  51. return static_cast<BackgroundRepeatStyleValue const&>(*this);
  52. }
  53. BackgroundSizeStyleValue const& StyleValue::as_background_size() const
  54. {
  55. VERIFY(is_background_size());
  56. return static_cast<BackgroundSizeStyleValue const&>(*this);
  57. }
  58. BorderStyleValue const& StyleValue::as_border() const
  59. {
  60. VERIFY(is_border());
  61. return static_cast<BorderStyleValue const&>(*this);
  62. }
  63. BorderRadiusStyleValue const& StyleValue::as_border_radius() const
  64. {
  65. VERIFY(is_border_radius());
  66. return static_cast<BorderRadiusStyleValue const&>(*this);
  67. }
  68. BorderRadiusShorthandStyleValue const& StyleValue::as_border_radius_shorthand() const
  69. {
  70. VERIFY(is_border_radius_shorthand());
  71. return static_cast<BorderRadiusShorthandStyleValue const&>(*this);
  72. }
  73. ShadowStyleValue const& StyleValue::as_shadow() const
  74. {
  75. VERIFY(is_shadow());
  76. return static_cast<ShadowStyleValue const&>(*this);
  77. }
  78. CalculatedStyleValue const& StyleValue::as_calculated() const
  79. {
  80. VERIFY(is_calculated());
  81. return static_cast<CalculatedStyleValue const&>(*this);
  82. }
  83. ColorStyleValue const& StyleValue::as_color() const
  84. {
  85. VERIFY(is_color());
  86. return static_cast<ColorStyleValue const&>(*this);
  87. }
  88. ConicGradientStyleValue const& StyleValue::as_conic_gradient() const
  89. {
  90. VERIFY(is_conic_gradient());
  91. return static_cast<ConicGradientStyleValue const&>(*this);
  92. }
  93. ContentStyleValue const& StyleValue::as_content() const
  94. {
  95. VERIFY(is_content());
  96. return static_cast<ContentStyleValue const&>(*this);
  97. }
  98. FilterValueListStyleValue const& StyleValue::as_filter_value_list() const
  99. {
  100. VERIFY(is_filter_value_list());
  101. return static_cast<FilterValueListStyleValue const&>(*this);
  102. }
  103. FlexStyleValue const& StyleValue::as_flex() const
  104. {
  105. VERIFY(is_flex());
  106. return static_cast<FlexStyleValue const&>(*this);
  107. }
  108. FlexFlowStyleValue const& StyleValue::as_flex_flow() const
  109. {
  110. VERIFY(is_flex_flow());
  111. return static_cast<FlexFlowStyleValue const&>(*this);
  112. }
  113. FontStyleValue const& StyleValue::as_font() const
  114. {
  115. VERIFY(is_font());
  116. return static_cast<FontStyleValue const&>(*this);
  117. }
  118. FrequencyStyleValue const& StyleValue::as_frequency() const
  119. {
  120. VERIFY(is_frequency());
  121. return static_cast<FrequencyStyleValue const&>(*this);
  122. }
  123. GridTrackPlacementShorthandStyleValue const& StyleValue::as_grid_track_placement_shorthand() const
  124. {
  125. VERIFY(is_grid_track_placement_shorthand());
  126. return static_cast<GridTrackPlacementShorthandStyleValue const&>(*this);
  127. }
  128. GridAreaShorthandStyleValue const& StyleValue::as_grid_area_shorthand() const
  129. {
  130. VERIFY(is_grid_area_shorthand());
  131. return static_cast<GridAreaShorthandStyleValue const&>(*this);
  132. }
  133. GridTemplateAreaStyleValue const& StyleValue::as_grid_template_area() const
  134. {
  135. VERIFY(is_grid_template_area());
  136. return static_cast<GridTemplateAreaStyleValue const&>(*this);
  137. }
  138. GridTrackPlacementStyleValue const& StyleValue::as_grid_track_placement() const
  139. {
  140. VERIFY(is_grid_track_placement());
  141. return static_cast<GridTrackPlacementStyleValue const&>(*this);
  142. }
  143. IdentifierStyleValue const& StyleValue::as_identifier() const
  144. {
  145. VERIFY(is_identifier());
  146. return static_cast<IdentifierStyleValue const&>(*this);
  147. }
  148. ImageStyleValue const& StyleValue::as_image() const
  149. {
  150. VERIFY(is_image());
  151. return static_cast<ImageStyleValue const&>(*this);
  152. }
  153. InheritStyleValue const& StyleValue::as_inherit() const
  154. {
  155. VERIFY(is_inherit());
  156. return static_cast<InheritStyleValue const&>(*this);
  157. }
  158. InitialStyleValue const& StyleValue::as_initial() const
  159. {
  160. VERIFY(is_initial());
  161. return static_cast<InitialStyleValue const&>(*this);
  162. }
  163. LengthStyleValue const& StyleValue::as_length() const
  164. {
  165. VERIFY(is_length());
  166. return static_cast<LengthStyleValue const&>(*this);
  167. }
  168. GridTrackSizeStyleValue const& StyleValue::as_grid_track_size_list() const
  169. {
  170. VERIFY(is_grid_track_size_list());
  171. return static_cast<GridTrackSizeStyleValue const&>(*this);
  172. }
  173. LinearGradientStyleValue const& StyleValue::as_linear_gradient() const
  174. {
  175. VERIFY(is_linear_gradient());
  176. return static_cast<LinearGradientStyleValue const&>(*this);
  177. }
  178. ListStyleStyleValue const& StyleValue::as_list_style() const
  179. {
  180. VERIFY(is_list_style());
  181. return static_cast<ListStyleStyleValue const&>(*this);
  182. }
  183. NumericStyleValue const& StyleValue::as_numeric() const
  184. {
  185. VERIFY(is_numeric());
  186. return static_cast<NumericStyleValue const&>(*this);
  187. }
  188. OverflowStyleValue const& StyleValue::as_overflow() const
  189. {
  190. VERIFY(is_overflow());
  191. return static_cast<OverflowStyleValue const&>(*this);
  192. }
  193. PercentageStyleValue const& StyleValue::as_percentage() const
  194. {
  195. VERIFY(is_percentage());
  196. return static_cast<PercentageStyleValue const&>(*this);
  197. }
  198. PositionStyleValue const& StyleValue::as_position() const
  199. {
  200. VERIFY(is_position());
  201. return static_cast<PositionStyleValue const&>(*this);
  202. }
  203. RadialGradientStyleValue const& StyleValue::as_radial_gradient() const
  204. {
  205. VERIFY(is_radial_gradient());
  206. return static_cast<RadialGradientStyleValue const&>(*this);
  207. }
  208. RectStyleValue const& StyleValue::as_rect() const
  209. {
  210. VERIFY(is_rect());
  211. return static_cast<RectStyleValue const&>(*this);
  212. }
  213. ResolutionStyleValue const& StyleValue::as_resolution() const
  214. {
  215. VERIFY(is_resolution());
  216. return static_cast<ResolutionStyleValue const&>(*this);
  217. }
  218. StringStyleValue const& StyleValue::as_string() const
  219. {
  220. VERIFY(is_string());
  221. return static_cast<StringStyleValue const&>(*this);
  222. }
  223. TextDecorationStyleValue const& StyleValue::as_text_decoration() const
  224. {
  225. VERIFY(is_text_decoration());
  226. return static_cast<TextDecorationStyleValue const&>(*this);
  227. }
  228. TimeStyleValue const& StyleValue::as_time() const
  229. {
  230. VERIFY(is_time());
  231. return static_cast<TimeStyleValue const&>(*this);
  232. }
  233. TransformationStyleValue const& StyleValue::as_transformation() const
  234. {
  235. VERIFY(is_transformation());
  236. return static_cast<TransformationStyleValue const&>(*this);
  237. }
  238. UnresolvedStyleValue const& StyleValue::as_unresolved() const
  239. {
  240. VERIFY(is_unresolved());
  241. return static_cast<UnresolvedStyleValue const&>(*this);
  242. }
  243. UnsetStyleValue const& StyleValue::as_unset() const
  244. {
  245. VERIFY(is_unset());
  246. return static_cast<UnsetStyleValue const&>(*this);
  247. }
  248. StyleValueList const& StyleValue::as_value_list() const
  249. {
  250. VERIFY(is_value_list());
  251. return static_cast<StyleValueList const&>(*this);
  252. }
  253. void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  254. {
  255. add_or_subtract_internal(SumOperation::Add, other, layout_node, percentage_basis);
  256. }
  257. void CalculatedStyleValue::CalculationResult::subtract(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  258. {
  259. add_or_subtract_internal(SumOperation::Subtract, other, layout_node, percentage_basis);
  260. }
  261. void CalculatedStyleValue::CalculationResult::add_or_subtract_internal(SumOperation op, CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  262. {
  263. // 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>".
  264. // Though, having the same type may mean that one side is a <dimension> and the other a <percentage>.
  265. // Note: This is almost identical to ::add()
  266. m_value.visit(
  267. [&](Number const& number) {
  268. auto other_number = other.m_value.get<Number>();
  269. if (op == SumOperation::Add) {
  270. m_value = number + other_number;
  271. } else {
  272. m_value = number - other_number;
  273. }
  274. },
  275. [&](Angle const& angle) {
  276. auto this_degrees = angle.to_degrees();
  277. if (other.m_value.has<Angle>()) {
  278. auto other_degrees = other.m_value.get<Angle>().to_degrees();
  279. if (op == SumOperation::Add)
  280. m_value = Angle::make_degrees(this_degrees + other_degrees);
  281. else
  282. m_value = Angle::make_degrees(this_degrees - other_degrees);
  283. } else {
  284. VERIFY(percentage_basis.has<Angle>());
  285. auto other_degrees = percentage_basis.get<Angle>().percentage_of(other.m_value.get<Percentage>()).to_degrees();
  286. if (op == SumOperation::Add)
  287. m_value = Angle::make_degrees(this_degrees + other_degrees);
  288. else
  289. m_value = Angle::make_degrees(this_degrees - other_degrees);
  290. }
  291. },
  292. [&](Frequency const& frequency) {
  293. auto this_hertz = frequency.to_hertz();
  294. if (other.m_value.has<Frequency>()) {
  295. auto other_hertz = other.m_value.get<Frequency>().to_hertz();
  296. if (op == SumOperation::Add)
  297. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  298. else
  299. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  300. } else {
  301. VERIFY(percentage_basis.has<Frequency>());
  302. auto other_hertz = percentage_basis.get<Frequency>().percentage_of(other.m_value.get<Percentage>()).to_hertz();
  303. if (op == SumOperation::Add)
  304. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  305. else
  306. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  307. }
  308. },
  309. [&](Length const& length) {
  310. auto this_px = length.to_px(*layout_node);
  311. if (other.m_value.has<Length>()) {
  312. auto other_px = other.m_value.get<Length>().to_px(*layout_node);
  313. if (op == SumOperation::Add)
  314. m_value = Length::make_px(this_px + other_px);
  315. else
  316. m_value = Length::make_px(this_px - other_px);
  317. } else {
  318. VERIFY(percentage_basis.has<Length>());
  319. auto other_px = percentage_basis.get<Length>().percentage_of(other.m_value.get<Percentage>()).to_px(*layout_node);
  320. if (op == SumOperation::Add)
  321. m_value = Length::make_px(this_px + other_px);
  322. else
  323. m_value = Length::make_px(this_px - other_px);
  324. }
  325. },
  326. [&](Time const& time) {
  327. auto this_seconds = time.to_seconds();
  328. if (other.m_value.has<Time>()) {
  329. auto other_seconds = other.m_value.get<Time>().to_seconds();
  330. if (op == SumOperation::Add)
  331. m_value = Time::make_seconds(this_seconds + other_seconds);
  332. else
  333. m_value = Time::make_seconds(this_seconds - other_seconds);
  334. } else {
  335. VERIFY(percentage_basis.has<Time>());
  336. auto other_seconds = percentage_basis.get<Time>().percentage_of(other.m_value.get<Percentage>()).to_seconds();
  337. if (op == SumOperation::Add)
  338. m_value = Time::make_seconds(this_seconds + other_seconds);
  339. else
  340. m_value = Time::make_seconds(this_seconds - other_seconds);
  341. }
  342. },
  343. [&](Percentage const& percentage) {
  344. if (other.m_value.has<Percentage>()) {
  345. if (op == SumOperation::Add)
  346. m_value = Percentage { percentage.value() + other.m_value.get<Percentage>().value() };
  347. else
  348. m_value = Percentage { percentage.value() - other.m_value.get<Percentage>().value() };
  349. return;
  350. }
  351. // 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`.
  352. CalculationResult new_value = other;
  353. if (op == SumOperation::Add) {
  354. new_value.add(*this, layout_node, percentage_basis);
  355. } else {
  356. // Turn 'this - other' into '-other + this', as 'A + B == B + A', but 'A - B != B - A'
  357. new_value.multiply_by({ Number { Number::Type::Integer, -1.0f } }, layout_node);
  358. new_value.add(*this, layout_node, percentage_basis);
  359. }
  360. *this = new_value;
  361. });
  362. }
  363. void CalculatedStyleValue::CalculationResult::multiply_by(CalculationResult const& other, Layout::Node const* layout_node)
  364. {
  365. // We know from validation when resolving the type, that at least one side must be a <number> or <integer>.
  366. // Both of these are represented as a float.
  367. VERIFY(m_value.has<Number>() || other.m_value.has<Number>());
  368. bool other_is_number = other.m_value.has<Number>();
  369. m_value.visit(
  370. [&](Number const& number) {
  371. if (other_is_number) {
  372. m_value = number * other.m_value.get<Number>();
  373. } else {
  374. // Avoid duplicating all the logic by swapping `this` and `other`.
  375. CalculationResult new_value = other;
  376. new_value.multiply_by(*this, layout_node);
  377. *this = new_value;
  378. }
  379. },
  380. [&](Angle const& angle) {
  381. m_value = Angle::make_degrees(angle.to_degrees() * other.m_value.get<Number>().value());
  382. },
  383. [&](Frequency const& frequency) {
  384. m_value = Frequency::make_hertz(frequency.to_hertz() * other.m_value.get<Number>().value());
  385. },
  386. [&](Length const& length) {
  387. VERIFY(layout_node);
  388. m_value = Length::make_px(length.to_px(*layout_node) * other.m_value.get<Number>().value());
  389. },
  390. [&](Time const& time) {
  391. m_value = Time::make_seconds(time.to_seconds() * other.m_value.get<Number>().value());
  392. },
  393. [&](Percentage const& percentage) {
  394. m_value = Percentage { percentage.value() * other.m_value.get<Number>().value() };
  395. });
  396. }
  397. void CalculatedStyleValue::CalculationResult::divide_by(CalculationResult const& other, Layout::Node const* layout_node)
  398. {
  399. // We know from validation when resolving the type, that `other` must be a <number> or <integer>.
  400. // Both of these are represented as a Number.
  401. auto denominator = other.m_value.get<Number>().value();
  402. // FIXME: Dividing by 0 is invalid, and should be caught during parsing.
  403. VERIFY(denominator != 0.0f);
  404. m_value.visit(
  405. [&](Number const& number) {
  406. m_value = Number {
  407. Number::Type::Number,
  408. number.value() / denominator
  409. };
  410. },
  411. [&](Angle const& angle) {
  412. m_value = Angle::make_degrees(angle.to_degrees() / denominator);
  413. },
  414. [&](Frequency const& frequency) {
  415. m_value = Frequency::make_hertz(frequency.to_hertz() / denominator);
  416. },
  417. [&](Length const& length) {
  418. VERIFY(layout_node);
  419. m_value = Length::make_px(length.to_px(*layout_node) / denominator);
  420. },
  421. [&](Time const& time) {
  422. m_value = Time::make_seconds(time.to_seconds() / denominator);
  423. },
  424. [&](Percentage const& percentage) {
  425. m_value = Percentage { percentage.value() / denominator };
  426. });
  427. }
  428. ErrorOr<String> CalculatedStyleValue::to_string() const
  429. {
  430. return String::formatted("calc({})", TRY(m_expression->to_string()));
  431. }
  432. bool CalculatedStyleValue::equals(StyleValue const& other) const
  433. {
  434. if (type() != other.type())
  435. return false;
  436. // This is a case where comparing the strings actually makes sense.
  437. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  438. }
  439. ErrorOr<String> CalculatedStyleValue::CalcNumberValue::to_string() const
  440. {
  441. return value.visit(
  442. [](Number const& number) -> ErrorOr<String> { return String::number(number.value()); },
  443. [](NonnullOwnPtr<CalcNumberSum> const& sum) -> ErrorOr<String> { return String::formatted("({})", TRY(sum->to_string())); });
  444. }
  445. ErrorOr<String> CalculatedStyleValue::CalcValue::to_string() const
  446. {
  447. return value.visit(
  448. [](Number const& number) -> ErrorOr<String> { return String::number(number.value()); },
  449. [](NonnullOwnPtr<CalcSum> const& sum) -> ErrorOr<String> { return String::formatted("({})", TRY(sum->to_string())); },
  450. [](auto const& v) -> ErrorOr<String> { return v.to_string(); });
  451. }
  452. ErrorOr<String> CalculatedStyleValue::CalcSum::to_string() const
  453. {
  454. StringBuilder builder;
  455. TRY(builder.try_append(TRY(first_calc_product->to_string())));
  456. for (auto const& item : zero_or_more_additional_calc_products)
  457. TRY(builder.try_append(TRY(item->to_string())));
  458. return builder.to_string();
  459. }
  460. ErrorOr<String> CalculatedStyleValue::CalcNumberSum::to_string() const
  461. {
  462. StringBuilder builder;
  463. TRY(builder.try_append(TRY(first_calc_number_product->to_string())));
  464. for (auto const& item : zero_or_more_additional_calc_number_products)
  465. TRY(builder.try_append(TRY(item->to_string())));
  466. return builder.to_string();
  467. }
  468. ErrorOr<String> CalculatedStyleValue::CalcProduct::to_string() const
  469. {
  470. StringBuilder builder;
  471. TRY(builder.try_append(TRY(first_calc_value.to_string())));
  472. for (auto const& item : zero_or_more_additional_calc_values)
  473. TRY(builder.try_append(TRY(item->to_string())));
  474. return builder.to_string();
  475. }
  476. ErrorOr<String> CalculatedStyleValue::CalcSumPartWithOperator::to_string() const
  477. {
  478. return String::formatted(" {} {}", op == SumOperation::Add ? "+"sv : "-"sv, TRY(value->to_string()));
  479. }
  480. ErrorOr<String> CalculatedStyleValue::CalcProductPartWithOperator::to_string() const
  481. {
  482. auto value_string = TRY(value.visit(
  483. [](CalcValue const& v) { return v.to_string(); },
  484. [](CalcNumberValue const& v) { return v.to_string(); }));
  485. return String::formatted(" {} {}", op == ProductOperation::Multiply ? "*"sv : "/"sv, value_string);
  486. }
  487. ErrorOr<String> CalculatedStyleValue::CalcNumberProduct::to_string() const
  488. {
  489. StringBuilder builder;
  490. TRY(builder.try_append(TRY(first_calc_number_value.to_string())));
  491. for (auto const& item : zero_or_more_additional_calc_number_values)
  492. TRY(builder.try_append(TRY(item->to_string())));
  493. return builder.to_string();
  494. }
  495. ErrorOr<String> CalculatedStyleValue::CalcNumberProductPartWithOperator::to_string() const
  496. {
  497. return String::formatted(" {} {}", op == ProductOperation::Multiply ? "*"sv : "/"sv, TRY(value.to_string()));
  498. }
  499. ErrorOr<String> CalculatedStyleValue::CalcNumberSumPartWithOperator::to_string() const
  500. {
  501. return String::formatted(" {} {}", op == SumOperation::Add ? "+"sv : "-"sv, TRY(value->to_string()));
  502. }
  503. Optional<Angle> CalculatedStyleValue::resolve_angle() const
  504. {
  505. auto result = m_expression->resolve(nullptr, {});
  506. if (result.value().has<Angle>())
  507. return result.value().get<Angle>();
  508. return {};
  509. }
  510. Optional<Angle> CalculatedStyleValue::resolve_angle_percentage(Angle const& percentage_basis) const
  511. {
  512. auto result = m_expression->resolve(nullptr, percentage_basis);
  513. return result.value().visit(
  514. [&](Angle const& angle) -> Optional<Angle> {
  515. return angle;
  516. },
  517. [&](Percentage const& percentage) -> Optional<Angle> {
  518. return percentage_basis.percentage_of(percentage);
  519. },
  520. [&](auto const&) -> Optional<Angle> {
  521. return {};
  522. });
  523. }
  524. Optional<Frequency> CalculatedStyleValue::resolve_frequency() const
  525. {
  526. auto result = m_expression->resolve(nullptr, {});
  527. if (result.value().has<Frequency>())
  528. return result.value().get<Frequency>();
  529. return {};
  530. }
  531. Optional<Frequency> CalculatedStyleValue::resolve_frequency_percentage(Frequency const& percentage_basis) const
  532. {
  533. auto result = m_expression->resolve(nullptr, percentage_basis);
  534. return result.value().visit(
  535. [&](Frequency const& frequency) -> Optional<Frequency> {
  536. return frequency;
  537. },
  538. [&](Percentage const& percentage) -> Optional<Frequency> {
  539. return percentage_basis.percentage_of(percentage);
  540. },
  541. [&](auto const&) -> Optional<Frequency> {
  542. return {};
  543. });
  544. }
  545. Optional<Length> CalculatedStyleValue::resolve_length(Layout::Node const& layout_node) const
  546. {
  547. auto result = m_expression->resolve(&layout_node, {});
  548. if (result.value().has<Length>())
  549. return result.value().get<Length>();
  550. return {};
  551. }
  552. Optional<Length> CalculatedStyleValue::resolve_length_percentage(Layout::Node const& layout_node, Length const& percentage_basis) const
  553. {
  554. auto result = m_expression->resolve(&layout_node, percentage_basis);
  555. return result.value().visit(
  556. [&](Length const& length) -> Optional<Length> {
  557. return length;
  558. },
  559. [&](Percentage const& percentage) -> Optional<Length> {
  560. return percentage_basis.percentage_of(percentage);
  561. },
  562. [&](auto const&) -> Optional<Length> {
  563. return {};
  564. });
  565. }
  566. Optional<Percentage> CalculatedStyleValue::resolve_percentage() const
  567. {
  568. auto result = m_expression->resolve(nullptr, {});
  569. if (result.value().has<Percentage>())
  570. return result.value().get<Percentage>();
  571. return {};
  572. }
  573. Optional<Time> CalculatedStyleValue::resolve_time() const
  574. {
  575. auto result = m_expression->resolve(nullptr, {});
  576. if (result.value().has<Time>())
  577. return result.value().get<Time>();
  578. return {};
  579. }
  580. Optional<Time> CalculatedStyleValue::resolve_time_percentage(Time const& percentage_basis) const
  581. {
  582. auto result = m_expression->resolve(nullptr, percentage_basis);
  583. return result.value().visit(
  584. [&](Time const& time) -> Optional<Time> {
  585. return time;
  586. },
  587. [&](auto const&) -> Optional<Time> {
  588. return {};
  589. });
  590. }
  591. Optional<float> CalculatedStyleValue::resolve_number()
  592. {
  593. auto result = m_expression->resolve(nullptr, {});
  594. if (result.value().has<Number>())
  595. return result.value().get<Number>().value();
  596. return {};
  597. }
  598. Optional<i64> CalculatedStyleValue::resolve_integer()
  599. {
  600. auto result = m_expression->resolve(nullptr, {});
  601. if (result.value().has<Number>())
  602. return result.value().get<Number>().integer_value();
  603. return {};
  604. }
  605. static bool is_number(CalculatedStyleValue::ResolvedType type)
  606. {
  607. return type == CalculatedStyleValue::ResolvedType::Number || type == CalculatedStyleValue::ResolvedType::Integer;
  608. }
  609. static bool is_dimension(CalculatedStyleValue::ResolvedType type)
  610. {
  611. return type != CalculatedStyleValue::ResolvedType::Number
  612. && type != CalculatedStyleValue::ResolvedType::Integer
  613. && type != CalculatedStyleValue::ResolvedType::Percentage;
  614. }
  615. template<typename SumWithOperator>
  616. static Optional<CalculatedStyleValue::ResolvedType> resolve_sum_type(CalculatedStyleValue::ResolvedType first_type, Vector<NonnullOwnPtr<SumWithOperator>> const& zero_or_more_additional_products)
  617. {
  618. auto type = first_type;
  619. for (auto const& product : zero_or_more_additional_products) {
  620. auto maybe_product_type = product->resolved_type();
  621. if (!maybe_product_type.has_value())
  622. return {};
  623. auto product_type = maybe_product_type.value();
  624. // At + or -, check that both sides have the same type, or that one side is a <number> and the other is an <integer>.
  625. // If both sides are the same type, resolve to that type.
  626. if (product_type == type)
  627. continue;
  628. // If one side is a <number> and the other is an <integer>, resolve to <number>.
  629. if (is_number(type) && is_number(product_type)) {
  630. type = CalculatedStyleValue::ResolvedType::Number;
  631. continue;
  632. }
  633. // FIXME: calc() handles <percentage> by allowing them to pretend to be whatever <dimension> type is allowed at this location.
  634. // Since we can't easily check what that type is, we just allow <percentage> to combine with any other <dimension> type.
  635. if (type == CalculatedStyleValue::ResolvedType::Percentage && is_dimension(product_type)) {
  636. type = product_type;
  637. continue;
  638. }
  639. if (is_dimension(type) && product_type == CalculatedStyleValue::ResolvedType::Percentage)
  640. continue;
  641. return {};
  642. }
  643. return type;
  644. }
  645. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcSum::resolved_type() const
  646. {
  647. auto maybe_type = first_calc_product->resolved_type();
  648. if (!maybe_type.has_value())
  649. return {};
  650. auto type = maybe_type.value();
  651. return resolve_sum_type(type, zero_or_more_additional_calc_products);
  652. }
  653. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  654. Gfx::FloatRect EdgeRect::resolved(Layout::Node const& layout_node, Gfx::FloatRect border_box) const
  655. {
  656. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  657. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  658. // <left> specify offsets from the left border edge of the box.
  659. // The value 'auto' means that a given edge of the clipping region will be the same as the edge
  660. // of the element's generated border box (i.e., 'auto' means the same as '0' for <top> and
  661. // <left>, the same as the used value of the height plus the sum of vertical padding and border
  662. // widths for <bottom>, and the same as the used value of the width plus the sum of the
  663. // horizontal padding and border widths for <right>, such that four 'auto' values result in the
  664. // clipping region being the same as the element's border box).
  665. auto left = border_box.left() + (left_edge.is_auto() ? 0 : left_edge.to_px(layout_node)).value();
  666. auto top = border_box.top() + (top_edge.is_auto() ? 0 : top_edge.to_px(layout_node)).value();
  667. auto right = border_box.left() + (right_edge.is_auto() ? border_box.width() : right_edge.to_px(layout_node)).value();
  668. auto bottom = border_box.top() + (bottom_edge.is_auto() ? border_box.height() : bottom_edge.to_px(layout_node)).value();
  669. return Gfx::FloatRect {
  670. left,
  671. top,
  672. right - left,
  673. bottom - top
  674. };
  675. }
  676. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberSum::resolved_type() const
  677. {
  678. auto maybe_type = first_calc_number_product->resolved_type();
  679. if (!maybe_type.has_value())
  680. return {};
  681. auto type = maybe_type.value();
  682. return resolve_sum_type(type, zero_or_more_additional_calc_number_products);
  683. }
  684. template<typename ProductWithOperator>
  685. static Optional<CalculatedStyleValue::ResolvedType> resolve_product_type(CalculatedStyleValue::ResolvedType first_type, Vector<NonnullOwnPtr<ProductWithOperator>> const& zero_or_more_additional_values)
  686. {
  687. auto type = first_type;
  688. for (auto const& value : zero_or_more_additional_values) {
  689. auto maybe_value_type = value->resolved_type();
  690. if (!maybe_value_type.has_value())
  691. return {};
  692. auto value_type = maybe_value_type.value();
  693. if (value->op == CalculatedStyleValue::ProductOperation::Multiply) {
  694. // At *, check that at least one side is <number>.
  695. if (!(is_number(type) || is_number(value_type)))
  696. return {};
  697. // If both sides are <integer>, resolve to <integer>.
  698. if (type == CalculatedStyleValue::ResolvedType::Integer && value_type == CalculatedStyleValue::ResolvedType::Integer) {
  699. type = CalculatedStyleValue::ResolvedType::Integer;
  700. } else {
  701. // Otherwise, resolve to the type of the other side.
  702. if (is_number(type))
  703. type = value_type;
  704. }
  705. continue;
  706. } else {
  707. VERIFY(value->op == CalculatedStyleValue::ProductOperation::Divide);
  708. // At /, check that the right side is <number>.
  709. if (!is_number(value_type))
  710. return {};
  711. // If the left side is <integer>, resolve to <number>.
  712. if (type == CalculatedStyleValue::ResolvedType::Integer) {
  713. type = CalculatedStyleValue::ResolvedType::Number;
  714. } else {
  715. // Otherwise, resolve to the type of the left side.
  716. }
  717. // FIXME: Division by zero makes the whole calc() expression invalid.
  718. }
  719. }
  720. return type;
  721. }
  722. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcProduct::resolved_type() const
  723. {
  724. auto maybe_type = first_calc_value.resolved_type();
  725. if (!maybe_type.has_value())
  726. return {};
  727. auto type = maybe_type.value();
  728. return resolve_product_type(type, zero_or_more_additional_calc_values);
  729. }
  730. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcSumPartWithOperator::resolved_type() const
  731. {
  732. return value->resolved_type();
  733. }
  734. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberProduct::resolved_type() const
  735. {
  736. auto maybe_type = first_calc_number_value.resolved_type();
  737. if (!maybe_type.has_value())
  738. return {};
  739. auto type = maybe_type.value();
  740. return resolve_product_type(type, zero_or_more_additional_calc_number_values);
  741. }
  742. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberProductPartWithOperator::resolved_type() const
  743. {
  744. return value.resolved_type();
  745. }
  746. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberSumPartWithOperator::resolved_type() const
  747. {
  748. return value->resolved_type();
  749. }
  750. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcProductPartWithOperator::resolved_type() const
  751. {
  752. return value.visit(
  753. [](CalcValue const& calc_value) {
  754. return calc_value.resolved_type();
  755. },
  756. [](CalcNumberValue const& calc_number_value) {
  757. return calc_number_value.resolved_type();
  758. });
  759. }
  760. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcValue::resolved_type() const
  761. {
  762. return value.visit(
  763. [](Number const& number) -> Optional<CalculatedStyleValue::ResolvedType> {
  764. return { number.is_integer() ? ResolvedType::Integer : ResolvedType::Number };
  765. },
  766. [](Angle const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Angle }; },
  767. [](Frequency const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Frequency }; },
  768. [](Length const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Length }; },
  769. [](Percentage const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Percentage }; },
  770. [](Time const&) -> Optional<CalculatedStyleValue::ResolvedType> { return { ResolvedType::Time }; },
  771. [](NonnullOwnPtr<CalcSum> const& sum) { return sum->resolved_type(); });
  772. }
  773. Optional<CalculatedStyleValue::ResolvedType> CalculatedStyleValue::CalcNumberValue::resolved_type() const
  774. {
  775. return value.visit(
  776. [](Number const& number) -> Optional<CalculatedStyleValue::ResolvedType> {
  777. return { number.is_integer() ? ResolvedType::Integer : ResolvedType::Number };
  778. },
  779. [](NonnullOwnPtr<CalcNumberSum> const& sum) { return sum->resolved_type(); });
  780. }
  781. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberValue::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  782. {
  783. return value.visit(
  784. [&](Number const& number) -> CalculatedStyleValue::CalculationResult {
  785. return CalculatedStyleValue::CalculationResult { number };
  786. },
  787. [&](NonnullOwnPtr<CalcNumberSum> const& sum) -> CalculatedStyleValue::CalculationResult {
  788. return sum->resolve(layout_node, percentage_basis);
  789. });
  790. }
  791. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcValue::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  792. {
  793. return value.visit(
  794. [&](NonnullOwnPtr<CalcSum> const& sum) -> CalculatedStyleValue::CalculationResult {
  795. return sum->resolve(layout_node, percentage_basis);
  796. },
  797. [&](auto const& v) -> CalculatedStyleValue::CalculationResult {
  798. return CalculatedStyleValue::CalculationResult { v };
  799. });
  800. }
  801. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcSum::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  802. {
  803. auto value = first_calc_product->resolve(layout_node, percentage_basis);
  804. for (auto& additional_product : zero_or_more_additional_calc_products) {
  805. auto additional_value = additional_product->resolve(layout_node, percentage_basis);
  806. if (additional_product->op == CalculatedStyleValue::SumOperation::Add)
  807. value.add(additional_value, layout_node, percentage_basis);
  808. else if (additional_product->op == CalculatedStyleValue::SumOperation::Subtract)
  809. value.subtract(additional_value, layout_node, percentage_basis);
  810. else
  811. VERIFY_NOT_REACHED();
  812. }
  813. return value;
  814. }
  815. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberSum::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  816. {
  817. auto value = first_calc_number_product->resolve(layout_node, percentage_basis);
  818. for (auto& additional_product : zero_or_more_additional_calc_number_products) {
  819. auto additional_value = additional_product->resolve(layout_node, percentage_basis);
  820. if (additional_product->op == CSS::CalculatedStyleValue::SumOperation::Add)
  821. value.add(additional_value, layout_node, percentage_basis);
  822. else if (additional_product->op == CalculatedStyleValue::SumOperation::Subtract)
  823. value.subtract(additional_value, layout_node, percentage_basis);
  824. else
  825. VERIFY_NOT_REACHED();
  826. }
  827. return value;
  828. }
  829. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcProduct::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  830. {
  831. auto value = first_calc_value.resolve(layout_node, percentage_basis);
  832. for (auto& additional_value : zero_or_more_additional_calc_values) {
  833. additional_value->value.visit(
  834. [&](CalculatedStyleValue::CalcValue const& calc_value) {
  835. VERIFY(additional_value->op == CalculatedStyleValue::ProductOperation::Multiply);
  836. auto resolved_value = calc_value.resolve(layout_node, percentage_basis);
  837. value.multiply_by(resolved_value, layout_node);
  838. },
  839. [&](CalculatedStyleValue::CalcNumberValue const& calc_number_value) {
  840. VERIFY(additional_value->op == CalculatedStyleValue::ProductOperation::Divide);
  841. auto resolved_calc_number_value = calc_number_value.resolve(layout_node, percentage_basis);
  842. // FIXME: Checking for division by 0 should happen during parsing.
  843. VERIFY(resolved_calc_number_value.value().get<Number>().value() != 0.0f);
  844. value.divide_by(resolved_calc_number_value, layout_node);
  845. });
  846. }
  847. return value;
  848. }
  849. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberProduct::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  850. {
  851. auto value = first_calc_number_value.resolve(layout_node, percentage_basis);
  852. for (auto& additional_number_value : zero_or_more_additional_calc_number_values) {
  853. auto additional_value = additional_number_value->resolve(layout_node, percentage_basis);
  854. if (additional_number_value->op == CalculatedStyleValue::ProductOperation::Multiply)
  855. value.multiply_by(additional_value, layout_node);
  856. else if (additional_number_value->op == CalculatedStyleValue::ProductOperation::Divide)
  857. value.divide_by(additional_value, layout_node);
  858. else
  859. VERIFY_NOT_REACHED();
  860. }
  861. return value;
  862. }
  863. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcProductPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  864. {
  865. return value.visit(
  866. [&](CalcValue const& calc_value) {
  867. return calc_value.resolve(layout_node, percentage_basis);
  868. },
  869. [&](CalcNumberValue const& calc_number_value) {
  870. return calc_number_value.resolve(layout_node, percentage_basis);
  871. });
  872. }
  873. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcSumPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  874. {
  875. return value->resolve(layout_node, percentage_basis);
  876. }
  877. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberProductPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  878. {
  879. return value.resolve(layout_node, percentage_basis);
  880. }
  881. CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberSumPartWithOperator::resolve(Layout::Node const* layout_node, PercentageBasis const& percentage_basis) const
  882. {
  883. return value->resolve(layout_node, percentage_basis);
  884. }
  885. ErrorOr<String> ContentStyleValue::to_string() const
  886. {
  887. if (has_alt_text())
  888. return String::formatted("{} / {}", TRY(m_properties.content->to_string()), TRY(m_properties.alt_text->to_string()));
  889. return m_properties.content->to_string();
  890. }
  891. float Filter::Blur::resolved_radius(Layout::Node const& node) const
  892. {
  893. // Default value when omitted is 0px.
  894. auto sigma = 0;
  895. if (radius.has_value())
  896. sigma = radius->resolved(node).to_px(node).value();
  897. // Note: The radius/sigma of the blur needs to be doubled for LibGfx's blur functions.
  898. return sigma * 2;
  899. }
  900. Filter::DropShadow::Resolved Filter::DropShadow::resolved(Layout::Node const& node) const
  901. {
  902. // The default value for omitted values is missing length values set to 0
  903. // and the missing used color is taken from the color property.
  904. return Resolved {
  905. offset_x.resolved(node).to_px(node).value(),
  906. offset_y.resolved(node).to_px(node).value(),
  907. radius.has_value() ? radius->resolved(node).to_px(node).value() : 0.0f,
  908. color.has_value() ? *color : node.computed_values().color()
  909. };
  910. }
  911. float Filter::HueRotate::angle_degrees() const
  912. {
  913. // Default value when omitted is 0deg.
  914. if (!angle.has_value())
  915. return 0.0f;
  916. return angle->visit([&](Angle const& angle) { return angle.to_degrees(); }, [&](auto) { return 0.0f; });
  917. }
  918. float Filter::Color::resolved_amount() const
  919. {
  920. if (amount.has_value()) {
  921. if (amount->is_percentage())
  922. return amount->percentage().as_fraction();
  923. return amount->number().value();
  924. }
  925. // All color filters (brightness, sepia, etc) have a default amount of 1.
  926. return 1.0f;
  927. }
  928. ErrorOr<String> FilterValueListStyleValue::to_string() const
  929. {
  930. StringBuilder builder {};
  931. bool first = true;
  932. for (auto& filter_function : filter_value_list()) {
  933. if (!first)
  934. TRY(builder.try_append(' '));
  935. TRY(filter_function.visit(
  936. [&](Filter::Blur const& blur) -> ErrorOr<void> {
  937. TRY(builder.try_append("blur("sv));
  938. if (blur.radius.has_value())
  939. TRY(builder.try_append(TRY(blur.radius->to_string())));
  940. return {};
  941. },
  942. [&](Filter::DropShadow const& drop_shadow) -> ErrorOr<void> {
  943. TRY(builder.try_appendff("drop-shadow({} {}"sv,
  944. drop_shadow.offset_x, drop_shadow.offset_y));
  945. if (drop_shadow.radius.has_value())
  946. TRY(builder.try_appendff(" {}", TRY(drop_shadow.radius->to_string())));
  947. if (drop_shadow.color.has_value()) {
  948. TRY(builder.try_append(' '));
  949. TRY(serialize_a_srgb_value(builder, *drop_shadow.color));
  950. }
  951. return {};
  952. },
  953. [&](Filter::HueRotate const& hue_rotate) -> ErrorOr<void> {
  954. TRY(builder.try_append("hue-rotate("sv));
  955. if (hue_rotate.angle.has_value()) {
  956. TRY(hue_rotate.angle->visit(
  957. [&](Angle const& angle) -> ErrorOr<void> {
  958. return builder.try_append(TRY(angle.to_string()));
  959. },
  960. [&](auto&) -> ErrorOr<void> {
  961. return builder.try_append('0');
  962. }));
  963. }
  964. return {};
  965. },
  966. [&](Filter::Color const& color) -> ErrorOr<void> {
  967. TRY(builder.try_appendff("{}(",
  968. [&] {
  969. switch (color.operation) {
  970. case Filter::Color::Operation::Brightness:
  971. return "brightness"sv;
  972. case Filter::Color::Operation::Contrast:
  973. return "contrast"sv;
  974. case Filter::Color::Operation::Grayscale:
  975. return "grayscale"sv;
  976. case Filter::Color::Operation::Invert:
  977. return "invert"sv;
  978. case Filter::Color::Operation::Opacity:
  979. return "opacity"sv;
  980. case Filter::Color::Operation::Saturate:
  981. return "saturate"sv;
  982. case Filter::Color::Operation::Sepia:
  983. return "sepia"sv;
  984. default:
  985. VERIFY_NOT_REACHED();
  986. }
  987. }()));
  988. if (color.amount.has_value())
  989. TRY(builder.try_append(TRY(color.amount->to_string())));
  990. return {};
  991. }));
  992. TRY(builder.try_append(')'));
  993. first = false;
  994. }
  995. return builder.to_string();
  996. }
  997. ErrorOr<String> FlexStyleValue::to_string() const
  998. {
  999. return String::formatted("{} {} {}", TRY(m_properties.grow->to_string()), TRY(m_properties.shrink->to_string()), TRY(m_properties.basis->to_string()));
  1000. }
  1001. ErrorOr<String> FlexFlowStyleValue::to_string() const
  1002. {
  1003. return String::formatted("{} {}", TRY(m_properties.flex_direction->to_string()), TRY(m_properties.flex_wrap->to_string()));
  1004. }
  1005. ErrorOr<String> FontStyleValue::to_string() const
  1006. {
  1007. return String::formatted("{} {} {} / {} {}", TRY(m_properties.font_style->to_string()), TRY(m_properties.font_weight->to_string()), TRY(m_properties.font_size->to_string()), TRY(m_properties.line_height->to_string()), TRY(m_properties.font_families->to_string()));
  1008. }
  1009. ErrorOr<String> GridTrackPlacementShorthandStyleValue::to_string() const
  1010. {
  1011. if (m_properties.end->grid_track_placement().is_auto())
  1012. return String::formatted("{}", TRY(m_properties.start->grid_track_placement().to_string()));
  1013. return String::formatted("{} / {}", TRY(m_properties.start->grid_track_placement().to_string()), TRY(m_properties.end->grid_track_placement().to_string()));
  1014. }
  1015. ErrorOr<String> GridAreaShorthandStyleValue::to_string() const
  1016. {
  1017. StringBuilder builder;
  1018. if (!m_properties.row_start->as_grid_track_placement().grid_track_placement().is_auto())
  1019. TRY(builder.try_appendff("{}", TRY(m_properties.row_start->as_grid_track_placement().grid_track_placement().to_string())));
  1020. if (!m_properties.column_start->as_grid_track_placement().grid_track_placement().is_auto())
  1021. TRY(builder.try_appendff(" / {}", TRY(m_properties.column_start->as_grid_track_placement().grid_track_placement().to_string())));
  1022. if (!m_properties.row_end->as_grid_track_placement().grid_track_placement().is_auto())
  1023. TRY(builder.try_appendff(" / {}", TRY(m_properties.row_end->as_grid_track_placement().grid_track_placement().to_string())));
  1024. if (!m_properties.column_end->as_grid_track_placement().grid_track_placement().is_auto())
  1025. TRY(builder.try_appendff(" / {}", TRY(m_properties.column_end->as_grid_track_placement().grid_track_placement().to_string())));
  1026. return builder.to_string();
  1027. }
  1028. ErrorOr<String> GridTrackPlacementStyleValue::to_string() const
  1029. {
  1030. return m_grid_track_placement.to_string();
  1031. }
  1032. ErrorOr<String> GridTemplateAreaStyleValue::to_string() const
  1033. {
  1034. StringBuilder builder;
  1035. for (size_t y = 0; y < m_grid_template_area.size(); ++y) {
  1036. for (size_t x = 0; x < m_grid_template_area[y].size(); ++x) {
  1037. TRY(builder.try_appendff("{}", m_grid_template_area[y][x]));
  1038. if (x < m_grid_template_area[y].size() - 1)
  1039. TRY(builder.try_append(" "sv));
  1040. }
  1041. if (y < m_grid_template_area.size() - 1)
  1042. TRY(builder.try_append(", "sv));
  1043. }
  1044. return builder.to_string();
  1045. }
  1046. ErrorOr<String> GridTrackSizeStyleValue::to_string() const
  1047. {
  1048. return m_grid_track_size_list.to_string();
  1049. }
  1050. ErrorOr<String> IdentifierStyleValue::to_string() const
  1051. {
  1052. return String::from_utf8(CSS::string_from_value_id(m_id));
  1053. }
  1054. bool IdentifierStyleValue::has_color() const
  1055. {
  1056. switch (m_id) {
  1057. case ValueID::Currentcolor:
  1058. case ValueID::LibwebLink:
  1059. case ValueID::LibwebPaletteActiveLink:
  1060. case ValueID::LibwebPaletteActiveWindowBorder1:
  1061. case ValueID::LibwebPaletteActiveWindowBorder2:
  1062. case ValueID::LibwebPaletteActiveWindowTitle:
  1063. case ValueID::LibwebPaletteBase:
  1064. case ValueID::LibwebPaletteBaseText:
  1065. case ValueID::LibwebPaletteButton:
  1066. case ValueID::LibwebPaletteButtonText:
  1067. case ValueID::LibwebPaletteDesktopBackground:
  1068. case ValueID::LibwebPaletteFocusOutline:
  1069. case ValueID::LibwebPaletteHighlightWindowBorder1:
  1070. case ValueID::LibwebPaletteHighlightWindowBorder2:
  1071. case ValueID::LibwebPaletteHighlightWindowTitle:
  1072. case ValueID::LibwebPaletteHoverHighlight:
  1073. case ValueID::LibwebPaletteInactiveSelection:
  1074. case ValueID::LibwebPaletteInactiveSelectionText:
  1075. case ValueID::LibwebPaletteInactiveWindowBorder1:
  1076. case ValueID::LibwebPaletteInactiveWindowBorder2:
  1077. case ValueID::LibwebPaletteInactiveWindowTitle:
  1078. case ValueID::LibwebPaletteLink:
  1079. case ValueID::LibwebPaletteMenuBase:
  1080. case ValueID::LibwebPaletteMenuBaseText:
  1081. case ValueID::LibwebPaletteMenuSelection:
  1082. case ValueID::LibwebPaletteMenuSelectionText:
  1083. case ValueID::LibwebPaletteMenuStripe:
  1084. case ValueID::LibwebPaletteMovingWindowBorder1:
  1085. case ValueID::LibwebPaletteMovingWindowBorder2:
  1086. case ValueID::LibwebPaletteMovingWindowTitle:
  1087. case ValueID::LibwebPaletteRubberBandBorder:
  1088. case ValueID::LibwebPaletteRubberBandFill:
  1089. case ValueID::LibwebPaletteRuler:
  1090. case ValueID::LibwebPaletteRulerActiveText:
  1091. case ValueID::LibwebPaletteRulerBorder:
  1092. case ValueID::LibwebPaletteRulerInactiveText:
  1093. case ValueID::LibwebPaletteSelection:
  1094. case ValueID::LibwebPaletteSelectionText:
  1095. case ValueID::LibwebPaletteSyntaxComment:
  1096. case ValueID::LibwebPaletteSyntaxControlKeyword:
  1097. case ValueID::LibwebPaletteSyntaxIdentifier:
  1098. case ValueID::LibwebPaletteSyntaxKeyword:
  1099. case ValueID::LibwebPaletteSyntaxNumber:
  1100. case ValueID::LibwebPaletteSyntaxOperator:
  1101. case ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  1102. case ValueID::LibwebPaletteSyntaxPreprocessorValue:
  1103. case ValueID::LibwebPaletteSyntaxPunctuation:
  1104. case ValueID::LibwebPaletteSyntaxString:
  1105. case ValueID::LibwebPaletteSyntaxType:
  1106. case ValueID::LibwebPaletteTextCursor:
  1107. case ValueID::LibwebPaletteThreedHighlight:
  1108. case ValueID::LibwebPaletteThreedShadow1:
  1109. case ValueID::LibwebPaletteThreedShadow2:
  1110. case ValueID::LibwebPaletteVisitedLink:
  1111. case ValueID::LibwebPaletteWindow:
  1112. case ValueID::LibwebPaletteWindowText:
  1113. return true;
  1114. default:
  1115. return false;
  1116. }
  1117. }
  1118. Color IdentifierStyleValue::to_color(Layout::NodeWithStyle const& node) const
  1119. {
  1120. if (id() == CSS::ValueID::Currentcolor) {
  1121. if (!node.has_style())
  1122. return Color::Black;
  1123. return node.computed_values().color();
  1124. }
  1125. auto& document = node.document();
  1126. if (id() == CSS::ValueID::LibwebLink)
  1127. return document.link_color();
  1128. if (!document.page())
  1129. return {};
  1130. auto palette = document.page()->palette();
  1131. switch (id()) {
  1132. case CSS::ValueID::LibwebPaletteDesktopBackground:
  1133. return palette.color(ColorRole::DesktopBackground);
  1134. case CSS::ValueID::LibwebPaletteActiveWindowBorder1:
  1135. return palette.color(ColorRole::ActiveWindowBorder1);
  1136. case CSS::ValueID::LibwebPaletteActiveWindowBorder2:
  1137. return palette.color(ColorRole::ActiveWindowBorder2);
  1138. case CSS::ValueID::LibwebPaletteActiveWindowTitle:
  1139. return palette.color(ColorRole::ActiveWindowTitle);
  1140. case CSS::ValueID::LibwebPaletteInactiveWindowBorder1:
  1141. return palette.color(ColorRole::InactiveWindowBorder1);
  1142. case CSS::ValueID::LibwebPaletteInactiveWindowBorder2:
  1143. return palette.color(ColorRole::InactiveWindowBorder2);
  1144. case CSS::ValueID::LibwebPaletteInactiveWindowTitle:
  1145. return palette.color(ColorRole::InactiveWindowTitle);
  1146. case CSS::ValueID::LibwebPaletteMovingWindowBorder1:
  1147. return palette.color(ColorRole::MovingWindowBorder1);
  1148. case CSS::ValueID::LibwebPaletteMovingWindowBorder2:
  1149. return palette.color(ColorRole::MovingWindowBorder2);
  1150. case CSS::ValueID::LibwebPaletteMovingWindowTitle:
  1151. return palette.color(ColorRole::MovingWindowTitle);
  1152. case CSS::ValueID::LibwebPaletteHighlightWindowBorder1:
  1153. return palette.color(ColorRole::HighlightWindowBorder1);
  1154. case CSS::ValueID::LibwebPaletteHighlightWindowBorder2:
  1155. return palette.color(ColorRole::HighlightWindowBorder2);
  1156. case CSS::ValueID::LibwebPaletteHighlightWindowTitle:
  1157. return palette.color(ColorRole::HighlightWindowTitle);
  1158. case CSS::ValueID::LibwebPaletteMenuStripe:
  1159. return palette.color(ColorRole::MenuStripe);
  1160. case CSS::ValueID::LibwebPaletteMenuBase:
  1161. return palette.color(ColorRole::MenuBase);
  1162. case CSS::ValueID::LibwebPaletteMenuBaseText:
  1163. return palette.color(ColorRole::MenuBaseText);
  1164. case CSS::ValueID::LibwebPaletteMenuSelection:
  1165. return palette.color(ColorRole::MenuSelection);
  1166. case CSS::ValueID::LibwebPaletteMenuSelectionText:
  1167. return palette.color(ColorRole::MenuSelectionText);
  1168. case CSS::ValueID::LibwebPaletteWindow:
  1169. return palette.color(ColorRole::Window);
  1170. case CSS::ValueID::LibwebPaletteWindowText:
  1171. return palette.color(ColorRole::WindowText);
  1172. case CSS::ValueID::LibwebPaletteButton:
  1173. return palette.color(ColorRole::Button);
  1174. case CSS::ValueID::LibwebPaletteButtonText:
  1175. return palette.color(ColorRole::ButtonText);
  1176. case CSS::ValueID::LibwebPaletteBase:
  1177. return palette.color(ColorRole::Base);
  1178. case CSS::ValueID::LibwebPaletteBaseText:
  1179. return palette.color(ColorRole::BaseText);
  1180. case CSS::ValueID::LibwebPaletteThreedHighlight:
  1181. return palette.color(ColorRole::ThreedHighlight);
  1182. case CSS::ValueID::LibwebPaletteThreedShadow1:
  1183. return palette.color(ColorRole::ThreedShadow1);
  1184. case CSS::ValueID::LibwebPaletteThreedShadow2:
  1185. return palette.color(ColorRole::ThreedShadow2);
  1186. case CSS::ValueID::LibwebPaletteHoverHighlight:
  1187. return palette.color(ColorRole::HoverHighlight);
  1188. case CSS::ValueID::LibwebPaletteSelection:
  1189. return palette.color(ColorRole::Selection);
  1190. case CSS::ValueID::LibwebPaletteSelectionText:
  1191. return palette.color(ColorRole::SelectionText);
  1192. case CSS::ValueID::LibwebPaletteInactiveSelection:
  1193. return palette.color(ColorRole::InactiveSelection);
  1194. case CSS::ValueID::LibwebPaletteInactiveSelectionText:
  1195. return palette.color(ColorRole::InactiveSelectionText);
  1196. case CSS::ValueID::LibwebPaletteRubberBandFill:
  1197. return palette.color(ColorRole::RubberBandFill);
  1198. case CSS::ValueID::LibwebPaletteRubberBandBorder:
  1199. return palette.color(ColorRole::RubberBandBorder);
  1200. case CSS::ValueID::LibwebPaletteLink:
  1201. return palette.color(ColorRole::Link);
  1202. case CSS::ValueID::LibwebPaletteActiveLink:
  1203. return palette.color(ColorRole::ActiveLink);
  1204. case CSS::ValueID::LibwebPaletteVisitedLink:
  1205. return palette.color(ColorRole::VisitedLink);
  1206. case CSS::ValueID::LibwebPaletteRuler:
  1207. return palette.color(ColorRole::Ruler);
  1208. case CSS::ValueID::LibwebPaletteRulerBorder:
  1209. return palette.color(ColorRole::RulerBorder);
  1210. case CSS::ValueID::LibwebPaletteRulerActiveText:
  1211. return palette.color(ColorRole::RulerActiveText);
  1212. case CSS::ValueID::LibwebPaletteRulerInactiveText:
  1213. return palette.color(ColorRole::RulerInactiveText);
  1214. case CSS::ValueID::LibwebPaletteTextCursor:
  1215. return palette.color(ColorRole::TextCursor);
  1216. case CSS::ValueID::LibwebPaletteFocusOutline:
  1217. return palette.color(ColorRole::FocusOutline);
  1218. case CSS::ValueID::LibwebPaletteSyntaxComment:
  1219. return palette.color(ColorRole::SyntaxComment);
  1220. case CSS::ValueID::LibwebPaletteSyntaxNumber:
  1221. return palette.color(ColorRole::SyntaxNumber);
  1222. case CSS::ValueID::LibwebPaletteSyntaxString:
  1223. return palette.color(ColorRole::SyntaxString);
  1224. case CSS::ValueID::LibwebPaletteSyntaxType:
  1225. return palette.color(ColorRole::SyntaxType);
  1226. case CSS::ValueID::LibwebPaletteSyntaxPunctuation:
  1227. return palette.color(ColorRole::SyntaxPunctuation);
  1228. case CSS::ValueID::LibwebPaletteSyntaxOperator:
  1229. return palette.color(ColorRole::SyntaxOperator);
  1230. case CSS::ValueID::LibwebPaletteSyntaxKeyword:
  1231. return palette.color(ColorRole::SyntaxKeyword);
  1232. case CSS::ValueID::LibwebPaletteSyntaxControlKeyword:
  1233. return palette.color(ColorRole::SyntaxControlKeyword);
  1234. case CSS::ValueID::LibwebPaletteSyntaxIdentifier:
  1235. return palette.color(ColorRole::SyntaxIdentifier);
  1236. case CSS::ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  1237. return palette.color(ColorRole::SyntaxPreprocessorStatement);
  1238. case CSS::ValueID::LibwebPaletteSyntaxPreprocessorValue:
  1239. return palette.color(ColorRole::SyntaxPreprocessorValue);
  1240. default:
  1241. return {};
  1242. }
  1243. }
  1244. ImageStyleValue::ImageStyleValue(AK::URL const& url)
  1245. : AbstractImageStyleValue(Type::Image)
  1246. , m_url(url)
  1247. {
  1248. }
  1249. void ImageStyleValue::load_any_resources(DOM::Document& document)
  1250. {
  1251. if (resource())
  1252. return;
  1253. m_document = &document;
  1254. auto request = LoadRequest::create_for_url_on_page(m_url, document.page());
  1255. set_resource(ResourceLoader::the().load_resource(Resource::Type::Image, request));
  1256. }
  1257. void ImageStyleValue::resource_did_load()
  1258. {
  1259. if (!m_document)
  1260. return;
  1261. // FIXME: Do less than a full repaint if possible?
  1262. if (m_document && m_document->browsing_context())
  1263. m_document->browsing_context()->set_needs_display();
  1264. if (resource()->is_animated() && resource()->frame_count() > 1) {
  1265. m_timer = Platform::Timer::create();
  1266. m_timer->set_interval(resource()->frame_duration(0));
  1267. m_timer->on_timeout = [this] { animate(); };
  1268. m_timer->start();
  1269. }
  1270. }
  1271. void ImageStyleValue::animate()
  1272. {
  1273. m_current_frame_index = (m_current_frame_index + 1) % resource()->frame_count();
  1274. auto current_frame_duration = resource()->frame_duration(m_current_frame_index);
  1275. if (current_frame_duration != m_timer->interval())
  1276. m_timer->restart(current_frame_duration);
  1277. if (m_current_frame_index == resource()->frame_count() - 1) {
  1278. ++m_loops_completed;
  1279. if (m_loops_completed > 0 && m_loops_completed == resource()->loop_count())
  1280. m_timer->stop();
  1281. }
  1282. if (on_animate)
  1283. on_animate();
  1284. }
  1285. Gfx::Bitmap const* ImageStyleValue::bitmap(size_t frame_index) const
  1286. {
  1287. if (!resource())
  1288. return nullptr;
  1289. return resource()->bitmap(frame_index);
  1290. }
  1291. ErrorOr<String> ImageStyleValue::to_string() const
  1292. {
  1293. return serialize_a_url(m_url.to_deprecated_string());
  1294. }
  1295. bool ImageStyleValue::equals(StyleValue const& other) const
  1296. {
  1297. if (type() != other.type())
  1298. return false;
  1299. return m_url == other.as_image().m_url;
  1300. }
  1301. Optional<CSSPixels> ImageStyleValue::natural_width() const
  1302. {
  1303. if (auto* b = bitmap(0); b != nullptr)
  1304. return b->width();
  1305. return {};
  1306. }
  1307. Optional<CSSPixels> ImageStyleValue::natural_height() const
  1308. {
  1309. if (auto* b = bitmap(0); b != nullptr)
  1310. return b->height();
  1311. return {};
  1312. }
  1313. void ImageStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering image_rendering) const
  1314. {
  1315. if (auto* b = bitmap(m_current_frame_index); b != nullptr)
  1316. context.painter().draw_scaled_bitmap(dest_rect.to_type<int>(), *b, bitmap(0)->rect(), 1.0f, to_gfx_scaling_mode(image_rendering));
  1317. }
  1318. static ErrorOr<void> serialize_color_stop_list(StringBuilder& builder, auto const& color_stop_list)
  1319. {
  1320. bool first = true;
  1321. for (auto const& element : color_stop_list) {
  1322. if (!first)
  1323. TRY(builder.try_append(", "sv));
  1324. if (element.transition_hint.has_value())
  1325. TRY(builder.try_appendff("{}, "sv, TRY(element.transition_hint->value.to_string())));
  1326. TRY(serialize_a_srgb_value(builder, element.color_stop.color));
  1327. for (auto position : Array { &element.color_stop.position, &element.color_stop.second_position }) {
  1328. if (position->has_value())
  1329. TRY(builder.try_appendff(" {}"sv, TRY((*position)->to_string())));
  1330. }
  1331. first = false;
  1332. }
  1333. return {};
  1334. }
  1335. ErrorOr<String> LinearGradientStyleValue::to_string() const
  1336. {
  1337. StringBuilder builder;
  1338. auto side_or_corner_to_string = [](SideOrCorner value) {
  1339. switch (value) {
  1340. case SideOrCorner::Top:
  1341. return "top"sv;
  1342. case SideOrCorner::Bottom:
  1343. return "bottom"sv;
  1344. case SideOrCorner::Left:
  1345. return "left"sv;
  1346. case SideOrCorner::Right:
  1347. return "right"sv;
  1348. case SideOrCorner::TopLeft:
  1349. return "top left"sv;
  1350. case SideOrCorner::TopRight:
  1351. return "top right"sv;
  1352. case SideOrCorner::BottomLeft:
  1353. return "bottom left"sv;
  1354. case SideOrCorner::BottomRight:
  1355. return "bottom right"sv;
  1356. default:
  1357. VERIFY_NOT_REACHED();
  1358. }
  1359. };
  1360. if (m_properties.gradient_type == GradientType::WebKit)
  1361. TRY(builder.try_append("-webkit-"sv));
  1362. if (is_repeating())
  1363. TRY(builder.try_append("repeating-"sv));
  1364. TRY(builder.try_append("linear-gradient("sv));
  1365. TRY(m_properties.direction.visit(
  1366. [&](SideOrCorner side_or_corner) -> ErrorOr<void> {
  1367. return builder.try_appendff("{}{}, "sv, m_properties.gradient_type == GradientType::Standard ? "to "sv : ""sv, side_or_corner_to_string(side_or_corner));
  1368. },
  1369. [&](Angle const& angle) -> ErrorOr<void> {
  1370. return builder.try_appendff("{}, "sv, TRY(angle.to_string()));
  1371. }));
  1372. TRY(serialize_color_stop_list(builder, m_properties.color_stop_list));
  1373. TRY(builder.try_append(")"sv));
  1374. return builder.to_string();
  1375. }
  1376. bool LinearGradientStyleValue::equals(StyleValue const& other_) const
  1377. {
  1378. if (type() != other_.type())
  1379. return false;
  1380. auto& other = other_.as_linear_gradient();
  1381. return m_properties == other.m_properties;
  1382. }
  1383. float LinearGradientStyleValue::angle_degrees(CSSPixelSize gradient_size) const
  1384. {
  1385. auto corner_angle_degrees = [&] {
  1386. return static_cast<float>(atan2(gradient_size.height().value(), gradient_size.width().value())) * 180 / AK::Pi<float>;
  1387. };
  1388. return m_properties.direction.visit(
  1389. [&](SideOrCorner side_or_corner) {
  1390. auto angle = [&] {
  1391. switch (side_or_corner) {
  1392. case SideOrCorner::Top:
  1393. return 0.0f;
  1394. case SideOrCorner::Bottom:
  1395. return 180.0f;
  1396. case SideOrCorner::Left:
  1397. return 270.0f;
  1398. case SideOrCorner::Right:
  1399. return 90.0f;
  1400. case SideOrCorner::TopRight:
  1401. return corner_angle_degrees();
  1402. case SideOrCorner::BottomLeft:
  1403. return corner_angle_degrees() + 180.0f;
  1404. case SideOrCorner::TopLeft:
  1405. return -corner_angle_degrees();
  1406. case SideOrCorner::BottomRight:
  1407. return -(corner_angle_degrees() + 180.0f);
  1408. default:
  1409. VERIFY_NOT_REACHED();
  1410. }
  1411. }();
  1412. // Note: For unknowable reasons the angles are opposite on the -webkit- version
  1413. if (m_properties.gradient_type == GradientType::WebKit)
  1414. return angle + 180.0f;
  1415. return angle;
  1416. },
  1417. [&](Angle const& angle) {
  1418. return angle.to_degrees();
  1419. });
  1420. }
  1421. void LinearGradientStyleValue::resolve_for_size(Layout::Node const& node, CSSPixelSize size) const
  1422. {
  1423. if (m_resolved.has_value() && m_resolved->size == size)
  1424. return;
  1425. m_resolved = ResolvedData { Painting::resolve_linear_gradient_data(node, size, *this), size };
  1426. }
  1427. void LinearGradientStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering) const
  1428. {
  1429. VERIFY(m_resolved.has_value());
  1430. Painting::paint_linear_gradient(context, dest_rect, m_resolved->data);
  1431. }
  1432. CSSPixelPoint PositionValue::resolved(Layout::Node const& node, CSSPixelRect const& rect) const
  1433. {
  1434. // Note: A preset + a none default x/y_relative_to is impossible in the syntax (and makes little sense)
  1435. CSSPixels x = horizontal_position.visit(
  1436. [&](HorizontalPreset preset) -> CSSPixels {
  1437. return rect.width() * [&] {
  1438. switch (preset) {
  1439. case HorizontalPreset::Left:
  1440. return 0.0f;
  1441. case HorizontalPreset::Center:
  1442. return 0.5f;
  1443. case HorizontalPreset::Right:
  1444. return 1.0f;
  1445. default:
  1446. VERIFY_NOT_REACHED();
  1447. }
  1448. }();
  1449. },
  1450. [&](LengthPercentage length_percentage) -> CSSPixels {
  1451. return length_percentage.resolved(node, Length::make_px(rect.width())).to_px(node);
  1452. });
  1453. CSSPixels y = vertical_position.visit(
  1454. [&](VerticalPreset preset) -> CSSPixels {
  1455. return rect.height() * [&] {
  1456. switch (preset) {
  1457. case VerticalPreset::Top:
  1458. return 0.0f;
  1459. case VerticalPreset::Center:
  1460. return 0.5f;
  1461. case VerticalPreset::Bottom:
  1462. return 1.0f;
  1463. default:
  1464. VERIFY_NOT_REACHED();
  1465. }
  1466. }();
  1467. },
  1468. [&](LengthPercentage length_percentage) -> CSSPixels {
  1469. return length_percentage.resolved(node, Length::make_px(rect.height())).to_px(node);
  1470. });
  1471. if (x_relative_to == HorizontalEdge::Right)
  1472. x = rect.width() - x;
  1473. if (y_relative_to == VerticalEdge::Bottom)
  1474. y = rect.height() - y;
  1475. return CSSPixelPoint { rect.x() + x, rect.y() + y };
  1476. }
  1477. ErrorOr<void> PositionValue::serialize(StringBuilder& builder) const
  1478. {
  1479. // Note: This means our serialization with simplify any with explicit edges that are just `top left`.
  1480. bool has_relative_edges = x_relative_to == HorizontalEdge::Right || y_relative_to == VerticalEdge::Bottom;
  1481. if (has_relative_edges)
  1482. TRY(builder.try_append(x_relative_to == HorizontalEdge::Left ? "left "sv : "right "sv));
  1483. TRY(horizontal_position.visit(
  1484. [&](HorizontalPreset preset) -> ErrorOr<void> {
  1485. return builder.try_append([&] {
  1486. switch (preset) {
  1487. case HorizontalPreset::Left:
  1488. return "left"sv;
  1489. case HorizontalPreset::Center:
  1490. return "center"sv;
  1491. case HorizontalPreset::Right:
  1492. return "right"sv;
  1493. default:
  1494. VERIFY_NOT_REACHED();
  1495. }
  1496. }());
  1497. },
  1498. [&](LengthPercentage length_percentage) -> ErrorOr<void> {
  1499. return builder.try_appendff(TRY(length_percentage.to_string()));
  1500. }));
  1501. TRY(builder.try_append(' '));
  1502. if (has_relative_edges)
  1503. TRY(builder.try_append(y_relative_to == VerticalEdge::Top ? "top "sv : "bottom "sv));
  1504. TRY(vertical_position.visit(
  1505. [&](VerticalPreset preset) -> ErrorOr<void> {
  1506. return builder.try_append([&] {
  1507. switch (preset) {
  1508. case VerticalPreset::Top:
  1509. return "top"sv;
  1510. case VerticalPreset::Center:
  1511. return "center"sv;
  1512. case VerticalPreset::Bottom:
  1513. return "bottom"sv;
  1514. default:
  1515. VERIFY_NOT_REACHED();
  1516. }
  1517. }());
  1518. },
  1519. [&](LengthPercentage length_percentage) -> ErrorOr<void> {
  1520. return builder.try_append(TRY(length_percentage.to_string()));
  1521. }));
  1522. return {};
  1523. }
  1524. ErrorOr<String> RadialGradientStyleValue::to_string() const
  1525. {
  1526. StringBuilder builder;
  1527. if (is_repeating())
  1528. TRY(builder.try_append("repeating-"sv));
  1529. TRY(builder.try_appendff("radial-gradient({} "sv,
  1530. m_properties.ending_shape == EndingShape::Circle ? "circle"sv : "ellipse"sv));
  1531. TRY(m_properties.size.visit(
  1532. [&](Extent extent) -> ErrorOr<void> {
  1533. return builder.try_append([&] {
  1534. switch (extent) {
  1535. case Extent::ClosestCorner:
  1536. return "closest-corner"sv;
  1537. case Extent::ClosestSide:
  1538. return "closest-side"sv;
  1539. case Extent::FarthestCorner:
  1540. return "farthest-corner"sv;
  1541. case Extent::FarthestSide:
  1542. return "farthest-side"sv;
  1543. default:
  1544. VERIFY_NOT_REACHED();
  1545. }
  1546. }());
  1547. },
  1548. [&](CircleSize const& circle_size) -> ErrorOr<void> {
  1549. return builder.try_append(TRY(circle_size.radius.to_string()));
  1550. },
  1551. [&](EllipseSize const& ellipse_size) -> ErrorOr<void> {
  1552. return builder.try_appendff("{} {}", TRY(ellipse_size.radius_a.to_string()), TRY(ellipse_size.radius_b.to_string()));
  1553. }));
  1554. if (m_properties.position != PositionValue::center()) {
  1555. TRY(builder.try_appendff(" at "sv));
  1556. TRY(m_properties.position.serialize(builder));
  1557. }
  1558. TRY(builder.try_append(", "sv));
  1559. TRY(serialize_color_stop_list(builder, m_properties.color_stop_list));
  1560. TRY(builder.try_append(')'));
  1561. return builder.to_string();
  1562. }
  1563. Gfx::FloatSize RadialGradientStyleValue::resolve_size(Layout::Node const& node, Gfx::FloatPoint center, Gfx::FloatRect const& size) const
  1564. {
  1565. auto const side_shape = [&](auto distance_function) {
  1566. auto const distance_from = [&](float v, float a, float b, auto distance_function) {
  1567. return distance_function(fabs(a - v), fabs(b - v));
  1568. };
  1569. auto x_dist = distance_from(center.x(), size.left(), size.right(), distance_function);
  1570. auto y_dist = distance_from(center.y(), size.top(), size.bottom(), distance_function);
  1571. if (m_properties.ending_shape == EndingShape::Circle) {
  1572. auto dist = distance_function(x_dist, y_dist);
  1573. return Gfx::FloatSize { dist, dist };
  1574. } else {
  1575. return Gfx::FloatSize { x_dist, y_dist };
  1576. }
  1577. };
  1578. auto const closest_side_shape = [&] {
  1579. return side_shape(AK::min<float>);
  1580. };
  1581. auto const farthest_side_shape = [&] {
  1582. return side_shape(AK::max<float>);
  1583. };
  1584. auto const corner_distance = [&](auto distance_compare, Gfx::FloatPoint& corner) {
  1585. auto top_left_distance = size.top_left().distance_from(center);
  1586. auto top_right_distance = size.top_right().distance_from(center);
  1587. auto bottom_right_distance = size.bottom_right().distance_from(center);
  1588. auto bottom_left_distance = size.bottom_left().distance_from(center);
  1589. auto distance = top_left_distance;
  1590. if (distance_compare(top_right_distance, distance)) {
  1591. corner = size.top_right();
  1592. distance = top_right_distance;
  1593. }
  1594. if (distance_compare(bottom_right_distance, distance)) {
  1595. corner = size.top_right();
  1596. distance = bottom_right_distance;
  1597. }
  1598. if (distance_compare(bottom_left_distance, distance)) {
  1599. corner = size.top_right();
  1600. distance = bottom_left_distance;
  1601. }
  1602. return distance;
  1603. };
  1604. auto const closest_corner_distance = [&](Gfx::FloatPoint& corner) {
  1605. return corner_distance([](float a, float b) { return a < b; }, corner);
  1606. };
  1607. auto const farthest_corner_distance = [&](Gfx::FloatPoint& corner) {
  1608. return corner_distance([](float a, float b) { return a > b; }, corner);
  1609. };
  1610. auto const corner_shape = [&](auto corner_distance, auto get_shape) {
  1611. Gfx::FloatPoint corner {};
  1612. auto distance = corner_distance(corner);
  1613. if (m_properties.ending_shape == EndingShape::Ellipse) {
  1614. auto shape = get_shape();
  1615. auto aspect_ratio = shape.width() / shape.height();
  1616. auto p = corner - center;
  1617. auto radius_a = AK::sqrt(p.y() * p.y() * aspect_ratio * aspect_ratio + p.x() * p.x());
  1618. auto radius_b = radius_a / aspect_ratio;
  1619. return Gfx::FloatSize { radius_a, radius_b };
  1620. }
  1621. return Gfx::FloatSize { distance, distance };
  1622. };
  1623. // https://w3c.github.io/csswg-drafts/css-images/#radial-gradient-syntax
  1624. auto resolved_size = m_properties.size.visit(
  1625. [&](Extent extent) {
  1626. switch (extent) {
  1627. case Extent::ClosestSide:
  1628. // The ending shape is sized so that it exactly meets the side of the gradient box closest to the gradient’s center.
  1629. // If the shape is an ellipse, it exactly meets the closest side in each dimension.
  1630. return closest_side_shape();
  1631. case Extent::ClosestCorner:
  1632. // The ending shape is sized so that it passes through the corner of the gradient box closest to the gradient’s center.
  1633. // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified
  1634. return corner_shape(closest_corner_distance, closest_side_shape);
  1635. case Extent::FarthestCorner:
  1636. // Same as closest-corner, except the ending shape is sized based on the farthest corner.
  1637. // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
  1638. return corner_shape(farthest_corner_distance, farthest_side_shape);
  1639. case Extent::FarthestSide:
  1640. // Same as closest-side, except the ending shape is sized based on the farthest side(s).
  1641. return farthest_side_shape();
  1642. default:
  1643. VERIFY_NOT_REACHED();
  1644. }
  1645. },
  1646. [&](CircleSize const& circle_size) {
  1647. auto radius = circle_size.radius.to_px(node);
  1648. return Gfx::FloatSize { radius, radius };
  1649. },
  1650. [&](EllipseSize const& ellipse_size) {
  1651. auto radius_a = ellipse_size.radius_a.resolved(node, CSS::Length::make_px(size.width())).to_px(node);
  1652. auto radius_b = ellipse_size.radius_b.resolved(node, CSS::Length::make_px(size.height())).to_px(node);
  1653. return Gfx::FloatSize { radius_a, radius_b };
  1654. });
  1655. // Handle degenerate cases
  1656. // https://w3c.github.io/csswg-drafts/css-images/#degenerate-radials
  1657. constexpr auto arbitrary_small_number = 1e-10;
  1658. constexpr auto arbitrary_large_number = 1e10;
  1659. // If the ending shape is a circle with zero radius:
  1660. if (m_properties.ending_shape == EndingShape::Circle && resolved_size.is_empty()) {
  1661. // Render as if the ending shape was a circle whose radius was an arbitrary very small number greater than zero.
  1662. // This will make the gradient continue to look like a circle.
  1663. return Gfx::FloatSize { arbitrary_small_number, arbitrary_small_number };
  1664. }
  1665. // If the ending shape has zero width (regardless of the height):
  1666. if (resolved_size.width() <= 0) {
  1667. // Render as if the ending shape was an ellipse whose height was an arbitrary very large number
  1668. // and whose width was an arbitrary very small number greater than zero.
  1669. // This will make the gradient look similar to a horizontal linear gradient that is mirrored across the center of the ellipse.
  1670. // It also means that all color-stop positions specified with a percentage resolve to 0px.
  1671. return Gfx::FloatSize { arbitrary_small_number, arbitrary_large_number };
  1672. }
  1673. // Otherwise, if the ending shape has zero height:
  1674. if (resolved_size.height() <= 0) {
  1675. // Render as if the ending shape was an ellipse whose width was an arbitrary very large number and whose height
  1676. // was an arbitrary very small number greater than zero. This will make the gradient look like a solid-color image equal
  1677. // to the color of the last color-stop, or equal to the average color of the gradient if it’s repeating.
  1678. return Gfx::FloatSize { arbitrary_large_number, arbitrary_small_number };
  1679. }
  1680. return resolved_size;
  1681. }
  1682. void RadialGradientStyleValue::resolve_for_size(Layout::Node const& node, CSSPixelSize paint_size) const
  1683. {
  1684. CSSPixelRect gradient_box { { 0, 0 }, paint_size };
  1685. auto center = m_properties.position.resolved(node, gradient_box).to_type<float>();
  1686. auto gradient_size = resolve_size(node, center, gradient_box.to_type<float>());
  1687. if (m_resolved.has_value() && m_resolved->gradient_size == gradient_size)
  1688. return;
  1689. m_resolved = ResolvedData {
  1690. Painting::resolve_radial_gradient_data(node, gradient_size.to_type<CSSPixels>(), *this),
  1691. gradient_size,
  1692. center,
  1693. };
  1694. }
  1695. bool RadialGradientStyleValue::equals(StyleValue const& other) const
  1696. {
  1697. if (type() != other.type())
  1698. return false;
  1699. auto& other_gradient = other.as_radial_gradient();
  1700. return m_properties == other_gradient.m_properties;
  1701. }
  1702. void RadialGradientStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering) const
  1703. {
  1704. VERIFY(m_resolved.has_value());
  1705. Painting::paint_radial_gradient(context, dest_rect, m_resolved->data,
  1706. context.rounded_device_point(m_resolved->center.to_type<CSSPixels>()),
  1707. context.rounded_device_size(m_resolved->gradient_size.to_type<CSSPixels>()));
  1708. }
  1709. ErrorOr<String> ConicGradientStyleValue::to_string() const
  1710. {
  1711. StringBuilder builder;
  1712. if (is_repeating())
  1713. TRY(builder.try_append("repeating-"sv));
  1714. TRY(builder.try_append("conic-gradient("sv));
  1715. bool has_from_angle = false;
  1716. bool has_at_position = false;
  1717. if ((has_from_angle = m_properties.from_angle.to_degrees() != 0))
  1718. TRY(builder.try_appendff("from {}", TRY(m_properties.from_angle.to_string())));
  1719. if ((has_at_position = m_properties.position != PositionValue::center())) {
  1720. if (has_from_angle)
  1721. TRY(builder.try_append(' '));
  1722. TRY(builder.try_appendff("at "sv));
  1723. TRY(m_properties.position.serialize(builder));
  1724. }
  1725. if (has_from_angle || has_at_position)
  1726. TRY(builder.try_append(", "sv));
  1727. TRY(serialize_color_stop_list(builder, m_properties.color_stop_list));
  1728. TRY(builder.try_append(')'));
  1729. return builder.to_string();
  1730. }
  1731. void ConicGradientStyleValue::resolve_for_size(Layout::Node const& node, CSSPixelSize size) const
  1732. {
  1733. if (!m_resolved.has_value())
  1734. m_resolved = ResolvedData { Painting::resolve_conic_gradient_data(node, *this), {} };
  1735. m_resolved->position = m_properties.position.resolved(node, CSSPixelRect { { 0, 0 }, size });
  1736. }
  1737. void ConicGradientStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering) const
  1738. {
  1739. VERIFY(m_resolved.has_value());
  1740. Painting::paint_conic_gradient(context, dest_rect, m_resolved->data, context.rounded_device_point(m_resolved->position));
  1741. }
  1742. bool ConicGradientStyleValue::equals(StyleValue const& other) const
  1743. {
  1744. if (type() != other.type())
  1745. return false;
  1746. auto& other_gradient = other.as_conic_gradient();
  1747. return m_properties == other_gradient.m_properties;
  1748. }
  1749. float ConicGradientStyleValue::angle_degrees() const
  1750. {
  1751. return m_properties.from_angle.to_degrees();
  1752. }
  1753. ErrorOr<String> ListStyleStyleValue::to_string() const
  1754. {
  1755. return String::formatted("{} {} {}", TRY(m_properties.position->to_string()), TRY(m_properties.image->to_string()), TRY(m_properties.style_type->to_string()));
  1756. }
  1757. ErrorOr<String> NumericStyleValue::to_string() const
  1758. {
  1759. return m_value.visit(
  1760. [](auto value) {
  1761. return String::formatted("{}", value);
  1762. });
  1763. }
  1764. ErrorOr<String> OverflowStyleValue::to_string() const
  1765. {
  1766. return String::formatted("{} {}", TRY(m_properties.overflow_x->to_string()), TRY(m_properties.overflow_y->to_string()));
  1767. }
  1768. ErrorOr<String> PercentageStyleValue::to_string() const
  1769. {
  1770. return m_percentage.to_string();
  1771. }
  1772. ErrorOr<String> PositionStyleValue::to_string() const
  1773. {
  1774. auto to_string = [](PositionEdge edge) {
  1775. switch (edge) {
  1776. case PositionEdge::Left:
  1777. return "left";
  1778. case PositionEdge::Right:
  1779. return "right";
  1780. case PositionEdge::Top:
  1781. return "top";
  1782. case PositionEdge::Bottom:
  1783. return "bottom";
  1784. }
  1785. VERIFY_NOT_REACHED();
  1786. };
  1787. 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()));
  1788. }
  1789. ErrorOr<String> RectStyleValue::to_string() const
  1790. {
  1791. return String::formatted("rect({} {} {} {})", m_rect.top_edge, m_rect.right_edge, m_rect.bottom_edge, m_rect.left_edge);
  1792. }
  1793. ErrorOr<String> ShadowStyleValue::to_string() const
  1794. {
  1795. StringBuilder builder;
  1796. 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())));
  1797. if (m_properties.placement == ShadowPlacement::Inner)
  1798. TRY(builder.try_append(" inset"sv));
  1799. return builder.to_string();
  1800. }
  1801. ErrorOr<String> TextDecorationStyleValue::to_string() const
  1802. {
  1803. 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()));
  1804. }
  1805. ErrorOr<String> TransformationStyleValue::to_string() const
  1806. {
  1807. StringBuilder builder;
  1808. TRY(builder.try_append(CSS::to_string(m_properties.transform_function)));
  1809. TRY(builder.try_append('('));
  1810. for (size_t i = 0; i < m_properties.values.size(); ++i) {
  1811. TRY(builder.try_append(TRY(m_properties.values[i]->to_string())));
  1812. if (i != m_properties.values.size() - 1)
  1813. TRY(builder.try_append(", "sv));
  1814. }
  1815. TRY(builder.try_append(')'));
  1816. return builder.to_string();
  1817. }
  1818. bool TransformationStyleValue::Properties::operator==(Properties const& other) const
  1819. {
  1820. return transform_function == other.transform_function && values.span() == other.values.span();
  1821. }
  1822. ErrorOr<String> UnresolvedStyleValue::to_string() const
  1823. {
  1824. StringBuilder builder;
  1825. for (auto& value : m_values)
  1826. TRY(builder.try_append(TRY(value.to_string())));
  1827. return builder.to_string();
  1828. }
  1829. bool UnresolvedStyleValue::equals(StyleValue const& other) const
  1830. {
  1831. if (type() != other.type())
  1832. return false;
  1833. // This is a case where comparing the strings actually makes sense.
  1834. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  1835. }
  1836. bool StyleValueList::Properties::operator==(Properties const& other) const
  1837. {
  1838. return separator == other.separator && values.span() == other.values.span();
  1839. }
  1840. ErrorOr<String> StyleValueList::to_string() const
  1841. {
  1842. auto separator = ""sv;
  1843. switch (m_properties.separator) {
  1844. case Separator::Space:
  1845. separator = " "sv;
  1846. break;
  1847. case Separator::Comma:
  1848. separator = ", "sv;
  1849. break;
  1850. default:
  1851. VERIFY_NOT_REACHED();
  1852. }
  1853. StringBuilder builder;
  1854. for (size_t i = 0; i < m_properties.values.size(); ++i) {
  1855. TRY(builder.try_append(TRY(m_properties.values[i]->to_string())));
  1856. if (i != m_properties.values.size() - 1)
  1857. TRY(builder.try_append(separator));
  1858. }
  1859. return builder.to_string();
  1860. }
  1861. ValueComparingNonnullRefPtr<GridTemplateAreaStyleValue> GridTemplateAreaStyleValue::create(Vector<Vector<String>> grid_template_area)
  1862. {
  1863. return adopt_ref(*new GridTemplateAreaStyleValue(grid_template_area));
  1864. }
  1865. ValueComparingNonnullRefPtr<GridTrackPlacementStyleValue> GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement grid_track_placement)
  1866. {
  1867. return adopt_ref(*new GridTrackPlacementStyleValue(grid_track_placement));
  1868. }
  1869. ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> GridTrackSizeStyleValue::create(CSS::GridTrackSizeList grid_track_size_list)
  1870. {
  1871. return adopt_ref(*new GridTrackSizeStyleValue(grid_track_size_list));
  1872. }
  1873. ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> GridTrackSizeStyleValue::make_auto()
  1874. {
  1875. return adopt_ref(*new GridTrackSizeStyleValue(CSS::GridTrackSizeList()));
  1876. }
  1877. ValueComparingNonnullRefPtr<RectStyleValue> RectStyleValue::create(EdgeRect rect)
  1878. {
  1879. return adopt_ref(*new RectStyleValue(rect));
  1880. }
  1881. ValueComparingNonnullRefPtr<LengthStyleValue> LengthStyleValue::create(Length const& length)
  1882. {
  1883. if (length.is_auto()) {
  1884. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_auto()));
  1885. return value;
  1886. }
  1887. if (length.is_px()) {
  1888. if (length.raw_value() == 0) {
  1889. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_px(0)));
  1890. return value;
  1891. }
  1892. if (length.raw_value() == 1) {
  1893. static auto value = adopt_ref(*new LengthStyleValue(CSS::Length::make_px(1)));
  1894. return value;
  1895. }
  1896. }
  1897. return adopt_ref(*new LengthStyleValue(length));
  1898. }
  1899. 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)
  1900. {
  1901. if (length.is_px())
  1902. return {};
  1903. if (length.is_absolute() || length.is_relative()) {
  1904. auto px = length.to_px(viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height);
  1905. return CSS::Length::make_px(px);
  1906. }
  1907. return {};
  1908. }
  1909. ValueComparingNonnullRefPtr<StyleValue const> StyleValue::absolutized(CSSPixelRect const&, Gfx::FontPixelMetrics const&, CSSPixels, CSSPixels, CSSPixels, CSSPixels) const
  1910. {
  1911. return *this;
  1912. }
  1913. 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
  1914. {
  1915. if (auto length = absolutized_length(m_length, viewport_rect, font_metrics, font_size, root_font_size, line_height, root_line_height); length.has_value())
  1916. return LengthStyleValue::create(length.release_value());
  1917. return *this;
  1918. }
  1919. 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
  1920. {
  1921. 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);
  1922. 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);
  1923. 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);
  1924. 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);
  1925. return ShadowStyleValue::create(m_properties.color, absolutized_offset_x, absolutized_offset_y, absolutized_blur_radius, absolutized_spread_distance, m_properties.placement);
  1926. }
  1927. bool CalculatedStyleValue::contains_percentage() const
  1928. {
  1929. return m_expression->contains_percentage();
  1930. }
  1931. bool CalculatedStyleValue::CalcSum::contains_percentage() const
  1932. {
  1933. if (first_calc_product->contains_percentage())
  1934. return true;
  1935. for (auto& part : zero_or_more_additional_calc_products) {
  1936. if (part->contains_percentage())
  1937. return true;
  1938. }
  1939. return false;
  1940. }
  1941. bool CalculatedStyleValue::CalcSumPartWithOperator::contains_percentage() const
  1942. {
  1943. return value->contains_percentage();
  1944. }
  1945. bool CalculatedStyleValue::CalcProduct::contains_percentage() const
  1946. {
  1947. if (first_calc_value.contains_percentage())
  1948. return true;
  1949. for (auto& part : zero_or_more_additional_calc_values) {
  1950. if (part->contains_percentage())
  1951. return true;
  1952. }
  1953. return false;
  1954. }
  1955. bool CalculatedStyleValue::CalcProductPartWithOperator::contains_percentage() const
  1956. {
  1957. return value.visit(
  1958. [](CalcValue const& value) { return value.contains_percentage(); },
  1959. [](CalcNumberValue const&) { return false; });
  1960. }
  1961. bool CalculatedStyleValue::CalcValue::contains_percentage() const
  1962. {
  1963. return value.visit(
  1964. [](Percentage const&) { return true; },
  1965. [](NonnullOwnPtr<CalcSum> const& sum) { return sum->contains_percentage(); },
  1966. [](auto const&) { return false; });
  1967. }
  1968. bool calculated_style_value_contains_percentage(CalculatedStyleValue const& value)
  1969. {
  1970. return value.contains_percentage();
  1971. }
  1972. }