StyleValue.cpp 87 KB

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