StyleValue.cpp 89 KB

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