StyleValue.cpp 81 KB

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