StyleValue.cpp 79 KB

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