StyleValue.cpp 100 KB

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