StyleValue.cpp 89 KB

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