StyleValue.cpp 92 KB

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