StyleValue.cpp 100 KB

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