StyleValue.cpp 79 KB

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