StyleValue.cpp 70 KB

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