StyleValue.cpp 100 KB

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