StyleValue.cpp 91 KB

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