StyleValue.cpp 91 KB

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