StyleValue.cpp 97 KB

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