CalculatedStyleValue.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "CalculatedStyleValue.h"
  10. #include <LibWeb/CSS/Percentage.h>
  11. namespace Web::CSS {
  12. static bool is_number(CalculatedStyleValue::ResolvedType type)
  13. {
  14. return type == CalculatedStyleValue::ResolvedType::Number || type == CalculatedStyleValue::ResolvedType::Integer;
  15. }
  16. static bool is_dimension(CalculatedStyleValue::ResolvedType type)
  17. {
  18. return type != CalculatedStyleValue::ResolvedType::Number
  19. && type != CalculatedStyleValue::ResolvedType::Integer
  20. && type != CalculatedStyleValue::ResolvedType::Percentage;
  21. }
  22. static double resolve_value(CalculatedStyleValue::CalculationResult::Value value, Optional<Length::ResolutionContext const&> context)
  23. {
  24. return value.visit(
  25. [](Number const& number) { return number.value(); },
  26. [](Angle const& angle) { return angle.to_degrees(); },
  27. [](Frequency const& frequency) { return frequency.to_hertz(); },
  28. [&context](Length const& length) { return length.to_px(*context).to_double(); },
  29. [](Percentage const& percentage) { return percentage.value(); },
  30. [](Time const& time) { return time.to_seconds(); });
  31. };
  32. static CalculatedStyleValue::CalculationResult to_resolved_type(CalculatedStyleValue::ResolvedType type, double value)
  33. {
  34. switch (type) {
  35. case CalculatedStyleValue::ResolvedType::Integer:
  36. return { Number(Number::Type::Integer, value) };
  37. case CalculatedStyleValue::ResolvedType::Number:
  38. return { Number(Number::Type::Number, value) };
  39. case CalculatedStyleValue::ResolvedType::Angle:
  40. return { Angle::make_degrees(value) };
  41. case CalculatedStyleValue::ResolvedType::Frequency:
  42. return { Frequency::make_hertz(value) };
  43. case CalculatedStyleValue::ResolvedType::Length:
  44. return { Length::make_px(value) };
  45. case CalculatedStyleValue::ResolvedType::Percentage:
  46. return { Percentage(value) };
  47. case CalculatedStyleValue::ResolvedType::Time:
  48. return { Time::make_seconds(value) };
  49. }
  50. VERIFY_NOT_REACHED();
  51. };
  52. CalculationNode::CalculationNode(Type type)
  53. : m_type(type)
  54. {
  55. }
  56. CalculationNode::~CalculationNode() = default;
  57. ErrorOr<NonnullOwnPtr<NumericCalculationNode>> NumericCalculationNode::create(NumericValue value)
  58. {
  59. return adopt_nonnull_own_or_enomem(new (nothrow) NumericCalculationNode(move(value)));
  60. }
  61. NumericCalculationNode::NumericCalculationNode(NumericValue value)
  62. : CalculationNode(Type::Numeric)
  63. , m_value(move(value))
  64. {
  65. }
  66. NumericCalculationNode::~NumericCalculationNode() = default;
  67. ErrorOr<String> NumericCalculationNode::to_string() const
  68. {
  69. return m_value.visit([](auto& value) { return value.to_string(); });
  70. }
  71. Optional<CalculatedStyleValue::ResolvedType> NumericCalculationNode::resolved_type() const
  72. {
  73. return m_value.visit(
  74. [](Number const&) { return CalculatedStyleValue::ResolvedType::Number; },
  75. [](Angle const&) { return CalculatedStyleValue::ResolvedType::Angle; },
  76. [](Frequency const&) { return CalculatedStyleValue::ResolvedType::Frequency; },
  77. [](Length const&) { return CalculatedStyleValue::ResolvedType::Length; },
  78. [](Percentage const&) { return CalculatedStyleValue::ResolvedType::Percentage; },
  79. [](Time const&) { return CalculatedStyleValue::ResolvedType::Time; });
  80. }
  81. bool NumericCalculationNode::contains_percentage() const
  82. {
  83. return m_value.has<Percentage>();
  84. }
  85. CalculatedStyleValue::CalculationResult NumericCalculationNode::resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const
  86. {
  87. return m_value;
  88. }
  89. ErrorOr<void> NumericCalculationNode::dump(StringBuilder& builder, int indent) const
  90. {
  91. return builder.try_appendff("{: >{}}NUMERIC({})\n", "", indent, TRY(m_value.visit([](auto& it) { return it.to_string(); })));
  92. }
  93. ErrorOr<NonnullOwnPtr<SumCalculationNode>> SumCalculationNode::create(Vector<NonnullOwnPtr<CalculationNode>> values)
  94. {
  95. return adopt_nonnull_own_or_enomem(new (nothrow) SumCalculationNode(move(values)));
  96. }
  97. SumCalculationNode::SumCalculationNode(Vector<NonnullOwnPtr<CalculationNode>> values)
  98. : CalculationNode(Type::Sum)
  99. , m_values(move(values))
  100. {
  101. VERIFY(!m_values.is_empty());
  102. }
  103. SumCalculationNode::~SumCalculationNode() = default;
  104. ErrorOr<String> SumCalculationNode::to_string() const
  105. {
  106. bool first = true;
  107. StringBuilder builder;
  108. for (auto& value : m_values) {
  109. if (!first)
  110. TRY(builder.try_append(" + "sv));
  111. TRY(builder.try_append(TRY(value->to_string())));
  112. first = false;
  113. }
  114. return builder.to_string();
  115. }
  116. Optional<CalculatedStyleValue::ResolvedType> SumCalculationNode::resolved_type() const
  117. {
  118. // FIXME: Implement https://www.w3.org/TR/css-values-4/#determine-the-type-of-a-calculation
  119. // For now, this is just ad-hoc, based on the old implementation.
  120. Optional<CalculatedStyleValue::ResolvedType> type;
  121. for (auto const& value : m_values) {
  122. auto maybe_value_type = value->resolved_type();
  123. if (!maybe_value_type.has_value())
  124. return {};
  125. auto value_type = maybe_value_type.value();
  126. if (!type.has_value()) {
  127. type = value_type;
  128. continue;
  129. }
  130. // At + or -, check that both sides have the same type, or that one side is a <number> and the other is an <integer>.
  131. // If both sides are the same type, resolve to that type.
  132. if (value_type == type)
  133. continue;
  134. // If one side is a <number> and the other is an <integer>, resolve to <number>.
  135. if (is_number(*type) && is_number(value_type)) {
  136. type = CalculatedStyleValue::ResolvedType::Number;
  137. continue;
  138. }
  139. // FIXME: calc() handles <percentage> by allowing them to pretend to be whatever <dimension> type is allowed at this location.
  140. // Since we can't easily check what that type is, we just allow <percentage> to combine with any other <dimension> type.
  141. if (type == CalculatedStyleValue::ResolvedType::Percentage && is_dimension(value_type)) {
  142. type = value_type;
  143. continue;
  144. }
  145. if (is_dimension(*type) && value_type == CalculatedStyleValue::ResolvedType::Percentage)
  146. continue;
  147. return {};
  148. }
  149. return type;
  150. }
  151. bool SumCalculationNode::contains_percentage() const
  152. {
  153. for (auto const& value : m_values) {
  154. if (value->contains_percentage())
  155. return true;
  156. }
  157. return false;
  158. }
  159. CalculatedStyleValue::CalculationResult SumCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  160. {
  161. Optional<CalculatedStyleValue::CalculationResult> total;
  162. for (auto& additional_product : m_values) {
  163. auto additional_value = additional_product->resolve(context, percentage_basis);
  164. if (!total.has_value()) {
  165. total = additional_value;
  166. continue;
  167. }
  168. total->add(additional_value, context, percentage_basis);
  169. }
  170. return total.value();
  171. }
  172. ErrorOr<void> SumCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  173. {
  174. for (auto& item : m_values) {
  175. TRY(item->for_each_child_node(callback));
  176. TRY(callback(item));
  177. }
  178. return {};
  179. }
  180. ErrorOr<void> SumCalculationNode::dump(StringBuilder& builder, int indent) const
  181. {
  182. TRY(builder.try_appendff("{: >{}}SUM:\n", "", indent));
  183. for (auto const& item : m_values)
  184. TRY(item->dump(builder, indent + 2));
  185. return {};
  186. }
  187. ErrorOr<NonnullOwnPtr<ProductCalculationNode>> ProductCalculationNode::create(Vector<NonnullOwnPtr<CalculationNode>> values)
  188. {
  189. return adopt_nonnull_own_or_enomem(new (nothrow) ProductCalculationNode(move(values)));
  190. }
  191. ProductCalculationNode::ProductCalculationNode(Vector<NonnullOwnPtr<CalculationNode>> values)
  192. : CalculationNode(Type::Product)
  193. , m_values(move(values))
  194. {
  195. VERIFY(!m_values.is_empty());
  196. }
  197. ProductCalculationNode::~ProductCalculationNode() = default;
  198. ErrorOr<String> ProductCalculationNode::to_string() const
  199. {
  200. bool first = true;
  201. StringBuilder builder;
  202. for (auto& value : m_values) {
  203. if (!first)
  204. TRY(builder.try_append(" * "sv));
  205. TRY(builder.try_append(TRY(value->to_string())));
  206. first = false;
  207. }
  208. return builder.to_string();
  209. }
  210. Optional<CalculatedStyleValue::ResolvedType> ProductCalculationNode::resolved_type() const
  211. {
  212. // FIXME: Implement https://www.w3.org/TR/css-values-4/#determine-the-type-of-a-calculation
  213. // For now, this is just ad-hoc, based on the old implementation.
  214. Optional<CalculatedStyleValue::ResolvedType> type;
  215. for (auto const& value : m_values) {
  216. auto maybe_value_type = value->resolved_type();
  217. if (!maybe_value_type.has_value())
  218. return {};
  219. auto value_type = maybe_value_type.value();
  220. if (!type.has_value()) {
  221. type = value_type;
  222. continue;
  223. }
  224. // At *, check that at least one side is <number>.
  225. if (!(is_number(*type) || is_number(value_type)))
  226. return {};
  227. // If both sides are <integer>, resolve to <integer>.
  228. if (type == CalculatedStyleValue::ResolvedType::Integer && value_type == CalculatedStyleValue::ResolvedType::Integer) {
  229. type = CalculatedStyleValue::ResolvedType::Integer;
  230. } else {
  231. // Otherwise, resolve to the type of the other side.
  232. if (is_number(*type))
  233. type = value_type;
  234. }
  235. }
  236. return type;
  237. }
  238. bool ProductCalculationNode::contains_percentage() const
  239. {
  240. for (auto const& value : m_values) {
  241. if (value->contains_percentage())
  242. return true;
  243. }
  244. return false;
  245. }
  246. CalculatedStyleValue::CalculationResult ProductCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  247. {
  248. Optional<CalculatedStyleValue::CalculationResult> total;
  249. for (auto& additional_product : m_values) {
  250. auto additional_value = additional_product->resolve(context, percentage_basis);
  251. if (!total.has_value()) {
  252. total = additional_value;
  253. continue;
  254. }
  255. total->multiply_by(additional_value, context);
  256. }
  257. return total.value();
  258. }
  259. ErrorOr<void> ProductCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  260. {
  261. for (auto& item : m_values) {
  262. TRY(item->for_each_child_node(callback));
  263. TRY(callback(item));
  264. }
  265. return {};
  266. }
  267. ErrorOr<void> ProductCalculationNode::dump(StringBuilder& builder, int indent) const
  268. {
  269. TRY(builder.try_appendff("{: >{}}PRODUCT:\n", "", indent));
  270. for (auto const& item : m_values)
  271. TRY(item->dump(builder, indent + 2));
  272. return {};
  273. }
  274. ErrorOr<NonnullOwnPtr<NegateCalculationNode>> NegateCalculationNode::create(NonnullOwnPtr<Web::CSS::CalculationNode> value)
  275. {
  276. return adopt_nonnull_own_or_enomem(new (nothrow) NegateCalculationNode(move(value)));
  277. }
  278. NegateCalculationNode::NegateCalculationNode(NonnullOwnPtr<CalculationNode> value)
  279. : CalculationNode(Type::Negate)
  280. , m_value(move(value))
  281. {
  282. }
  283. NegateCalculationNode::~NegateCalculationNode() = default;
  284. ErrorOr<String> NegateCalculationNode::to_string() const
  285. {
  286. return String::formatted("(0 - {})", TRY(m_value->to_string()));
  287. }
  288. Optional<CalculatedStyleValue::ResolvedType> NegateCalculationNode::resolved_type() const
  289. {
  290. return m_value->resolved_type();
  291. }
  292. bool NegateCalculationNode::contains_percentage() const
  293. {
  294. return m_value->contains_percentage();
  295. }
  296. CalculatedStyleValue::CalculationResult NegateCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  297. {
  298. auto child_value = m_value->resolve(context, percentage_basis);
  299. child_value.negate();
  300. return child_value;
  301. }
  302. ErrorOr<void> NegateCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  303. {
  304. TRY(m_value->for_each_child_node(callback));
  305. TRY(callback(m_value));
  306. return {};
  307. }
  308. ErrorOr<void> NegateCalculationNode::dump(StringBuilder& builder, int indent) const
  309. {
  310. TRY(builder.try_appendff("{: >{}}NEGATE:\n", "", indent));
  311. TRY(m_value->dump(builder, indent + 2));
  312. return {};
  313. }
  314. ErrorOr<NonnullOwnPtr<InvertCalculationNode>> InvertCalculationNode::create(NonnullOwnPtr<Web::CSS::CalculationNode> value)
  315. {
  316. return adopt_nonnull_own_or_enomem(new (nothrow) InvertCalculationNode(move(value)));
  317. }
  318. InvertCalculationNode::InvertCalculationNode(NonnullOwnPtr<CalculationNode> value)
  319. : CalculationNode(Type::Invert)
  320. , m_value(move(value))
  321. {
  322. }
  323. InvertCalculationNode::~InvertCalculationNode() = default;
  324. ErrorOr<String> InvertCalculationNode::to_string() const
  325. {
  326. return String::formatted("(1 / {})", TRY(m_value->to_string()));
  327. }
  328. Optional<CalculatedStyleValue::ResolvedType> InvertCalculationNode::resolved_type() const
  329. {
  330. auto type = m_value->resolved_type();
  331. if (type == CalculatedStyleValue::ResolvedType::Integer)
  332. return CalculatedStyleValue::ResolvedType::Number;
  333. return type;
  334. }
  335. bool InvertCalculationNode::contains_percentage() const
  336. {
  337. return m_value->contains_percentage();
  338. }
  339. CalculatedStyleValue::CalculationResult InvertCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  340. {
  341. auto child_value = m_value->resolve(context, percentage_basis);
  342. child_value.invert();
  343. return child_value;
  344. }
  345. ErrorOr<void> InvertCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  346. {
  347. TRY(m_value->for_each_child_node(callback));
  348. TRY(callback(m_value));
  349. return {};
  350. }
  351. ErrorOr<void> InvertCalculationNode::dump(StringBuilder& builder, int indent) const
  352. {
  353. TRY(builder.try_appendff("{: >{}}INVERT:\n", "", indent));
  354. TRY(m_value->dump(builder, indent + 2));
  355. return {};
  356. }
  357. ErrorOr<NonnullOwnPtr<MinCalculationNode>> MinCalculationNode::create(Vector<NonnullOwnPtr<Web::CSS::CalculationNode>> values)
  358. {
  359. return adopt_nonnull_own_or_enomem(new (nothrow) MinCalculationNode(move(values)));
  360. }
  361. MinCalculationNode::MinCalculationNode(Vector<NonnullOwnPtr<CalculationNode>> values)
  362. : CalculationNode(Type::Min)
  363. , m_values(move(values))
  364. {
  365. }
  366. MinCalculationNode::~MinCalculationNode() = default;
  367. ErrorOr<String> MinCalculationNode::to_string() const
  368. {
  369. StringBuilder builder;
  370. TRY(builder.try_append("min("sv));
  371. for (size_t i = 0; i < m_values.size(); ++i) {
  372. if (i != 0)
  373. TRY(builder.try_append(", "sv));
  374. TRY(builder.try_append(TRY(m_values[i]->to_string())));
  375. }
  376. TRY(builder.try_append(")"sv));
  377. return builder.to_string();
  378. }
  379. Optional<CalculatedStyleValue::ResolvedType> MinCalculationNode::resolved_type() const
  380. {
  381. // NOTE: We check during parsing that all values have the same type.
  382. return m_values[0]->resolved_type();
  383. }
  384. bool MinCalculationNode::contains_percentage() const
  385. {
  386. for (auto const& value : m_values) {
  387. if (value->contains_percentage())
  388. return true;
  389. }
  390. return false;
  391. }
  392. CalculatedStyleValue::CalculationResult MinCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  393. {
  394. CalculatedStyleValue::CalculationResult smallest_node = m_values.first()->resolve(context, percentage_basis);
  395. auto smallest_value = resolve_value(smallest_node.value(), context);
  396. for (size_t i = 1; i < m_values.size(); i++) {
  397. auto child_resolved = m_values[i]->resolve(context, percentage_basis);
  398. auto child_value = resolve_value(child_resolved.value(), context);
  399. if (child_value < smallest_value) {
  400. smallest_value = child_value;
  401. smallest_node = child_resolved;
  402. }
  403. }
  404. return smallest_node;
  405. }
  406. ErrorOr<void> MinCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  407. {
  408. for (auto& value : m_values) {
  409. TRY(value->for_each_child_node(callback));
  410. TRY(callback(value));
  411. }
  412. return {};
  413. }
  414. ErrorOr<void> MinCalculationNode::dump(StringBuilder& builder, int indent) const
  415. {
  416. TRY(builder.try_appendff("{: >{}}MIN:\n", "", indent));
  417. for (auto const& value : m_values)
  418. TRY(value->dump(builder, indent + 2));
  419. return {};
  420. }
  421. ErrorOr<NonnullOwnPtr<MaxCalculationNode>> MaxCalculationNode::create(Vector<NonnullOwnPtr<Web::CSS::CalculationNode>> values)
  422. {
  423. return adopt_nonnull_own_or_enomem(new (nothrow) MaxCalculationNode(move(values)));
  424. }
  425. MaxCalculationNode::MaxCalculationNode(Vector<NonnullOwnPtr<CalculationNode>> values)
  426. : CalculationNode(Type::Max)
  427. , m_values(move(values))
  428. {
  429. }
  430. MaxCalculationNode::~MaxCalculationNode() = default;
  431. ErrorOr<String> MaxCalculationNode::to_string() const
  432. {
  433. StringBuilder builder;
  434. TRY(builder.try_append("max("sv));
  435. for (size_t i = 0; i < m_values.size(); ++i) {
  436. if (i != 0)
  437. TRY(builder.try_append(", "sv));
  438. TRY(builder.try_append(TRY(m_values[i]->to_string())));
  439. }
  440. TRY(builder.try_append(")"sv));
  441. return builder.to_string();
  442. }
  443. Optional<CalculatedStyleValue::ResolvedType> MaxCalculationNode::resolved_type() const
  444. {
  445. // NOTE: We check during parsing that all values have the same type.
  446. return m_values[0]->resolved_type();
  447. }
  448. bool MaxCalculationNode::contains_percentage() const
  449. {
  450. for (auto const& value : m_values) {
  451. if (value->contains_percentage())
  452. return true;
  453. }
  454. return false;
  455. }
  456. CalculatedStyleValue::CalculationResult MaxCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  457. {
  458. CalculatedStyleValue::CalculationResult largest_node = m_values.first()->resolve(context, percentage_basis);
  459. auto largest_value = resolve_value(largest_node.value(), context);
  460. for (size_t i = 1; i < m_values.size(); i++) {
  461. auto child_resolved = m_values[i]->resolve(context, percentage_basis);
  462. auto child_value = resolve_value(child_resolved.value(), context);
  463. if (child_value > largest_value) {
  464. largest_value = child_value;
  465. largest_node = child_resolved;
  466. }
  467. }
  468. return largest_node;
  469. }
  470. ErrorOr<void> MaxCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  471. {
  472. for (auto& value : m_values) {
  473. TRY(value->for_each_child_node(callback));
  474. TRY(callback(value));
  475. }
  476. return {};
  477. }
  478. ErrorOr<void> MaxCalculationNode::dump(StringBuilder& builder, int indent) const
  479. {
  480. TRY(builder.try_appendff("{: >{}}MAX:\n", "", indent));
  481. for (auto const& value : m_values)
  482. TRY(value->dump(builder, indent + 2));
  483. return {};
  484. }
  485. ErrorOr<NonnullOwnPtr<ClampCalculationNode>> ClampCalculationNode::create(NonnullOwnPtr<CalculationNode> min, NonnullOwnPtr<CalculationNode> center, NonnullOwnPtr<CalculationNode> max)
  486. {
  487. return adopt_nonnull_own_or_enomem(new (nothrow) ClampCalculationNode(move(min), move(center), move(max)));
  488. }
  489. ClampCalculationNode::ClampCalculationNode(NonnullOwnPtr<CalculationNode> min, NonnullOwnPtr<CalculationNode> center, NonnullOwnPtr<CalculationNode> max)
  490. : CalculationNode(Type::Clamp)
  491. , m_min_value(move(min))
  492. , m_center_value(move(center))
  493. , m_max_value(move(max))
  494. {
  495. }
  496. ClampCalculationNode::~ClampCalculationNode() = default;
  497. ErrorOr<String> ClampCalculationNode::to_string() const
  498. {
  499. StringBuilder builder;
  500. TRY(builder.try_append("clamp("sv));
  501. TRY(builder.try_append(TRY(m_min_value->to_string())));
  502. TRY(builder.try_append(", "sv));
  503. TRY(builder.try_append(TRY(m_center_value->to_string())));
  504. TRY(builder.try_append(", "sv));
  505. TRY(builder.try_append(TRY(m_max_value->to_string())));
  506. TRY(builder.try_append(")"sv));
  507. return builder.to_string();
  508. }
  509. Optional<CalculatedStyleValue::ResolvedType> ClampCalculationNode::resolved_type() const
  510. {
  511. // NOTE: We check during parsing that all values have the same type.
  512. return m_min_value->resolved_type();
  513. }
  514. bool ClampCalculationNode::contains_percentage() const
  515. {
  516. return m_min_value->contains_percentage() || m_center_value->contains_percentage() || m_max_value->contains_percentage();
  517. }
  518. CalculatedStyleValue::CalculationResult ClampCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  519. {
  520. auto min_node = m_min_value->resolve(context, percentage_basis);
  521. auto center_node = m_center_value->resolve(context, percentage_basis);
  522. auto max_node = m_max_value->resolve(context, percentage_basis);
  523. auto min_value = resolve_value(min_node.value(), context);
  524. auto center_value = resolve_value(center_node.value(), context);
  525. auto max_value = resolve_value(max_node.value(), context);
  526. // NOTE: The value should be returned as "max(MIN, min(VAL, MAX))"
  527. auto chosen_value = max(min_value, min(center_value, max_value));
  528. if (chosen_value == min_value)
  529. return min_node;
  530. if (chosen_value == center_value)
  531. return center_node;
  532. if (chosen_value == max_value)
  533. return max_node;
  534. VERIFY_NOT_REACHED();
  535. }
  536. ErrorOr<void> ClampCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  537. {
  538. TRY(m_min_value->for_each_child_node(callback));
  539. TRY(m_center_value->for_each_child_node(callback));
  540. TRY(m_max_value->for_each_child_node(callback));
  541. TRY(callback(m_min_value));
  542. TRY(callback(m_center_value));
  543. TRY(callback(m_max_value));
  544. return {};
  545. }
  546. ErrorOr<void> ClampCalculationNode::dump(StringBuilder& builder, int indent) const
  547. {
  548. TRY(builder.try_appendff("{: >{}}CLAMP:\n", "", indent));
  549. TRY(m_min_value->dump(builder, indent + 2));
  550. TRY(m_center_value->dump(builder, indent + 2));
  551. TRY(m_max_value->dump(builder, indent + 2));
  552. return {};
  553. }
  554. ErrorOr<NonnullOwnPtr<AbsCalculationNode>> AbsCalculationNode::create(NonnullOwnPtr<CalculationNode> value)
  555. {
  556. return adopt_nonnull_own_or_enomem(new (nothrow) AbsCalculationNode(move(value)));
  557. }
  558. AbsCalculationNode::AbsCalculationNode(NonnullOwnPtr<CalculationNode> value)
  559. : CalculationNode(Type::Abs)
  560. , m_value(move(value))
  561. {
  562. }
  563. AbsCalculationNode::~AbsCalculationNode() = default;
  564. ErrorOr<String> AbsCalculationNode::to_string() const
  565. {
  566. StringBuilder builder;
  567. builder.append("abs("sv);
  568. builder.append(TRY(m_value->to_string()));
  569. builder.append(")"sv);
  570. return builder.to_string();
  571. }
  572. Optional<CalculatedStyleValue::ResolvedType> AbsCalculationNode::resolved_type() const
  573. {
  574. return m_value->resolved_type();
  575. }
  576. bool AbsCalculationNode::contains_percentage() const
  577. {
  578. return m_value->contains_percentage();
  579. }
  580. CalculatedStyleValue::CalculationResult AbsCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  581. {
  582. auto resolved_type = m_value->resolved_type().value();
  583. auto node_a = m_value->resolve(context, percentage_basis);
  584. auto node_a_value = resolve_value(node_a.value(), context);
  585. if (node_a_value < 0)
  586. return to_resolved_type(resolved_type, -node_a_value);
  587. return node_a;
  588. }
  589. ErrorOr<void> AbsCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  590. {
  591. TRY(m_value->for_each_child_node(callback));
  592. TRY(callback(m_value));
  593. return {};
  594. }
  595. ErrorOr<void> AbsCalculationNode::dump(StringBuilder& builder, int indent) const
  596. {
  597. TRY(builder.try_appendff("{: >{}}ABS: {}\n", "", indent, TRY(to_string())));
  598. return {};
  599. }
  600. ErrorOr<NonnullOwnPtr<SignCalculationNode>> SignCalculationNode::create(NonnullOwnPtr<CalculationNode> value)
  601. {
  602. return adopt_nonnull_own_or_enomem(new (nothrow) SignCalculationNode(move(value)));
  603. }
  604. SignCalculationNode::SignCalculationNode(NonnullOwnPtr<CalculationNode> value)
  605. : CalculationNode(Type::Sign)
  606. , m_value(move(value))
  607. {
  608. }
  609. SignCalculationNode::~SignCalculationNode() = default;
  610. ErrorOr<String> SignCalculationNode::to_string() const
  611. {
  612. StringBuilder builder;
  613. builder.append("sign("sv);
  614. builder.append(TRY(m_value->to_string()));
  615. builder.append(")"sv);
  616. return builder.to_string();
  617. }
  618. Optional<CalculatedStyleValue::ResolvedType> SignCalculationNode::resolved_type() const
  619. {
  620. return CalculatedStyleValue::ResolvedType::Integer;
  621. }
  622. bool SignCalculationNode::contains_percentage() const
  623. {
  624. return m_value->contains_percentage();
  625. }
  626. CalculatedStyleValue::CalculationResult SignCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  627. {
  628. auto node_a = m_value->resolve(context, percentage_basis);
  629. auto node_a_value = resolve_value(node_a.value(), context);
  630. if (node_a_value < 0)
  631. return { Number(Number::Type::Integer, -1) };
  632. if (node_a_value > 0)
  633. return { Number(Number::Type::Integer, 1) };
  634. return { Number(Number::Type::Integer, 0) };
  635. }
  636. ErrorOr<void> SignCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
  637. {
  638. TRY(m_value->for_each_child_node(callback));
  639. TRY(callback(m_value));
  640. return {};
  641. }
  642. ErrorOr<void> SignCalculationNode::dump(StringBuilder& builder, int indent) const
  643. {
  644. TRY(builder.try_appendff("{: >{}}SIGN: {}\n", "", indent, TRY(to_string())));
  645. return {};
  646. }
  647. void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  648. {
  649. add_or_subtract_internal(SumOperation::Add, other, context, percentage_basis);
  650. }
  651. void CalculatedStyleValue::CalculationResult::subtract(CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  652. {
  653. add_or_subtract_internal(SumOperation::Subtract, other, context, percentage_basis);
  654. }
  655. void CalculatedStyleValue::CalculationResult::add_or_subtract_internal(SumOperation op, CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  656. {
  657. // 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>".
  658. // Though, having the same type may mean that one side is a <dimension> and the other a <percentage>.
  659. // Note: This is almost identical to ::add()
  660. m_value.visit(
  661. [&](Number const& number) {
  662. auto other_number = other.m_value.get<Number>();
  663. if (op == SumOperation::Add) {
  664. m_value = number + other_number;
  665. } else {
  666. m_value = number - other_number;
  667. }
  668. },
  669. [&](Angle const& angle) {
  670. auto this_degrees = angle.to_degrees();
  671. if (other.m_value.has<Angle>()) {
  672. auto other_degrees = other.m_value.get<Angle>().to_degrees();
  673. if (op == SumOperation::Add)
  674. m_value = Angle::make_degrees(this_degrees + other_degrees);
  675. else
  676. m_value = Angle::make_degrees(this_degrees - other_degrees);
  677. } else {
  678. VERIFY(percentage_basis.has<Angle>());
  679. auto other_degrees = percentage_basis.get<Angle>().percentage_of(other.m_value.get<Percentage>()).to_degrees();
  680. if (op == SumOperation::Add)
  681. m_value = Angle::make_degrees(this_degrees + other_degrees);
  682. else
  683. m_value = Angle::make_degrees(this_degrees - other_degrees);
  684. }
  685. },
  686. [&](Frequency const& frequency) {
  687. auto this_hertz = frequency.to_hertz();
  688. if (other.m_value.has<Frequency>()) {
  689. auto other_hertz = other.m_value.get<Frequency>().to_hertz();
  690. if (op == SumOperation::Add)
  691. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  692. else
  693. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  694. } else {
  695. VERIFY(percentage_basis.has<Frequency>());
  696. auto other_hertz = percentage_basis.get<Frequency>().percentage_of(other.m_value.get<Percentage>()).to_hertz();
  697. if (op == SumOperation::Add)
  698. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  699. else
  700. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  701. }
  702. },
  703. [&](Length const& length) {
  704. auto this_px = length.to_px(*context);
  705. if (other.m_value.has<Length>()) {
  706. auto other_px = other.m_value.get<Length>().to_px(*context);
  707. if (op == SumOperation::Add)
  708. m_value = Length::make_px(this_px + other_px);
  709. else
  710. m_value = Length::make_px(this_px - other_px);
  711. } else {
  712. VERIFY(percentage_basis.has<Length>());
  713. auto other_px = percentage_basis.get<Length>().percentage_of(other.m_value.get<Percentage>()).to_px(*context);
  714. if (op == SumOperation::Add)
  715. m_value = Length::make_px(this_px + other_px);
  716. else
  717. m_value = Length::make_px(this_px - other_px);
  718. }
  719. },
  720. [&](Time const& time) {
  721. auto this_seconds = time.to_seconds();
  722. if (other.m_value.has<Time>()) {
  723. auto other_seconds = other.m_value.get<Time>().to_seconds();
  724. if (op == SumOperation::Add)
  725. m_value = Time::make_seconds(this_seconds + other_seconds);
  726. else
  727. m_value = Time::make_seconds(this_seconds - other_seconds);
  728. } else {
  729. VERIFY(percentage_basis.has<Time>());
  730. auto other_seconds = percentage_basis.get<Time>().percentage_of(other.m_value.get<Percentage>()).to_seconds();
  731. if (op == SumOperation::Add)
  732. m_value = Time::make_seconds(this_seconds + other_seconds);
  733. else
  734. m_value = Time::make_seconds(this_seconds - other_seconds);
  735. }
  736. },
  737. [&](Percentage const& percentage) {
  738. if (other.m_value.has<Percentage>()) {
  739. if (op == SumOperation::Add)
  740. m_value = Percentage { percentage.value() + other.m_value.get<Percentage>().value() };
  741. else
  742. m_value = Percentage { percentage.value() - other.m_value.get<Percentage>().value() };
  743. return;
  744. }
  745. // 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`.
  746. CalculationResult new_value = other;
  747. if (op == SumOperation::Add) {
  748. new_value.add(*this, context, percentage_basis);
  749. } else {
  750. // Turn 'this - other' into '-other + this', as 'A + B == B + A', but 'A - B != B - A'
  751. new_value.multiply_by({ Number { Number::Type::Integer, -1.0f } }, context);
  752. new_value.add(*this, context, percentage_basis);
  753. }
  754. *this = new_value;
  755. });
  756. }
  757. void CalculatedStyleValue::CalculationResult::multiply_by(CalculationResult const& other, Optional<Length::ResolutionContext const&> context)
  758. {
  759. // We know from validation when resolving the type, that at least one side must be a <number> or <integer>.
  760. // Both of these are represented as a double.
  761. VERIFY(m_value.has<Number>() || other.m_value.has<Number>());
  762. bool other_is_number = other.m_value.has<Number>();
  763. m_value.visit(
  764. [&](Number const& number) {
  765. if (other_is_number) {
  766. m_value = number * other.m_value.get<Number>();
  767. } else {
  768. // Avoid duplicating all the logic by swapping `this` and `other`.
  769. CalculationResult new_value = other;
  770. new_value.multiply_by(*this, context);
  771. *this = new_value;
  772. }
  773. },
  774. [&](Angle const& angle) {
  775. m_value = Angle::make_degrees(angle.to_degrees() * other.m_value.get<Number>().value());
  776. },
  777. [&](Frequency const& frequency) {
  778. m_value = Frequency::make_hertz(frequency.to_hertz() * other.m_value.get<Number>().value());
  779. },
  780. [&](Length const& length) {
  781. m_value = Length::make_px(length.to_px(*context) * static_cast<double>(other.m_value.get<Number>().value()));
  782. },
  783. [&](Time const& time) {
  784. m_value = Time::make_seconds(time.to_seconds() * other.m_value.get<Number>().value());
  785. },
  786. [&](Percentage const& percentage) {
  787. m_value = Percentage { percentage.value() * other.m_value.get<Number>().value() };
  788. });
  789. }
  790. void CalculatedStyleValue::CalculationResult::divide_by(CalculationResult const& other, Optional<Length::ResolutionContext const&> context)
  791. {
  792. // We know from validation when resolving the type, that `other` must be a <number> or <integer>.
  793. // Both of these are represented as a Number.
  794. auto denominator = other.m_value.get<Number>().value();
  795. // FIXME: Dividing by 0 is invalid, and should be caught during parsing.
  796. VERIFY(denominator != 0.0);
  797. m_value.visit(
  798. [&](Number const& number) {
  799. m_value = Number {
  800. Number::Type::Number,
  801. number.value() / denominator
  802. };
  803. },
  804. [&](Angle const& angle) {
  805. m_value = Angle::make_degrees(angle.to_degrees() / denominator);
  806. },
  807. [&](Frequency const& frequency) {
  808. m_value = Frequency::make_hertz(frequency.to_hertz() / denominator);
  809. },
  810. [&](Length const& length) {
  811. m_value = Length::make_px(length.to_px(*context) / static_cast<double>(denominator));
  812. },
  813. [&](Time const& time) {
  814. m_value = Time::make_seconds(time.to_seconds() / denominator);
  815. },
  816. [&](Percentage const& percentage) {
  817. m_value = Percentage { percentage.value() / denominator };
  818. });
  819. }
  820. void CalculatedStyleValue::CalculationResult::negate()
  821. {
  822. m_value.visit(
  823. [&](Number const& number) {
  824. m_value = Number { number.type(), 0 - number.value() };
  825. },
  826. [&](Angle const& angle) {
  827. m_value = Angle { 0 - angle.raw_value(), angle.type() };
  828. },
  829. [&](Frequency const& frequency) {
  830. m_value = Frequency { 0 - frequency.raw_value(), frequency.type() };
  831. },
  832. [&](Length const& length) {
  833. m_value = Length { 0 - length.raw_value(), length.type() };
  834. },
  835. [&](Time const& time) {
  836. m_value = Time { 0 - time.raw_value(), time.type() };
  837. },
  838. [&](Percentage const& percentage) {
  839. m_value = Percentage { 0 - percentage.value() };
  840. });
  841. }
  842. void CalculatedStyleValue::CalculationResult::invert()
  843. {
  844. // FIXME: Correctly handle division by zero.
  845. m_value.visit(
  846. [&](Number const& number) {
  847. m_value = Number { Number::Type::Number, 1 / number.value() };
  848. },
  849. [&](Angle const& angle) {
  850. m_value = Angle { 1 / angle.raw_value(), angle.type() };
  851. },
  852. [&](Frequency const& frequency) {
  853. m_value = Frequency { 1 / frequency.raw_value(), frequency.type() };
  854. },
  855. [&](Length const& length) {
  856. m_value = Length { 1 / length.raw_value(), length.type() };
  857. },
  858. [&](Time const& time) {
  859. m_value = Time { 1 / time.raw_value(), time.type() };
  860. },
  861. [&](Percentage const& percentage) {
  862. m_value = Percentage { 1 / percentage.value() };
  863. });
  864. }
  865. ErrorOr<String> CalculatedStyleValue::to_string() const
  866. {
  867. // FIXME: Implement this according to https://www.w3.org/TR/css-values-4/#calc-serialize once that stabilizes.
  868. return String::formatted("calc({})", TRY(m_calculation->to_string()));
  869. }
  870. bool CalculatedStyleValue::equals(StyleValue const& other) const
  871. {
  872. if (type() != other.type())
  873. return false;
  874. // This is a case where comparing the strings actually makes sense.
  875. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  876. }
  877. Optional<Angle> CalculatedStyleValue::resolve_angle() const
  878. {
  879. auto result = m_calculation->resolve({}, {});
  880. if (result.value().has<Angle>())
  881. return result.value().get<Angle>();
  882. return {};
  883. }
  884. Optional<Angle> CalculatedStyleValue::resolve_angle_percentage(Angle const& percentage_basis) const
  885. {
  886. auto result = m_calculation->resolve({}, percentage_basis);
  887. return result.value().visit(
  888. [&](Angle const& angle) -> Optional<Angle> {
  889. return angle;
  890. },
  891. [&](Percentage const& percentage) -> Optional<Angle> {
  892. return percentage_basis.percentage_of(percentage);
  893. },
  894. [&](auto const&) -> Optional<Angle> {
  895. return {};
  896. });
  897. }
  898. Optional<Frequency> CalculatedStyleValue::resolve_frequency() const
  899. {
  900. auto result = m_calculation->resolve({}, {});
  901. if (result.value().has<Frequency>())
  902. return result.value().get<Frequency>();
  903. return {};
  904. }
  905. Optional<Frequency> CalculatedStyleValue::resolve_frequency_percentage(Frequency const& percentage_basis) const
  906. {
  907. auto result = m_calculation->resolve({}, percentage_basis);
  908. return result.value().visit(
  909. [&](Frequency const& frequency) -> Optional<Frequency> {
  910. return frequency;
  911. },
  912. [&](Percentage const& percentage) -> Optional<Frequency> {
  913. return percentage_basis.percentage_of(percentage);
  914. },
  915. [&](auto const&) -> Optional<Frequency> {
  916. return {};
  917. });
  918. }
  919. Optional<Length> CalculatedStyleValue::resolve_length(Length::ResolutionContext const& context) const
  920. {
  921. auto result = m_calculation->resolve(context, {});
  922. if (result.value().has<Length>())
  923. return result.value().get<Length>();
  924. return {};
  925. }
  926. Optional<Length> CalculatedStyleValue::resolve_length(Layout::Node const& layout_node) const
  927. {
  928. return resolve_length(Length::ResolutionContext::for_layout_node(layout_node));
  929. }
  930. Optional<Length> CalculatedStyleValue::resolve_length_percentage(Layout::Node const& layout_node, Length const& percentage_basis) const
  931. {
  932. auto result = m_calculation->resolve(Length::ResolutionContext::for_layout_node(layout_node), percentage_basis);
  933. return result.value().visit(
  934. [&](Length const& length) -> Optional<Length> {
  935. return length;
  936. },
  937. [&](Percentage const& percentage) -> Optional<Length> {
  938. return percentage_basis.percentage_of(percentage);
  939. },
  940. [&](auto const&) -> Optional<Length> {
  941. return {};
  942. });
  943. }
  944. Optional<Percentage> CalculatedStyleValue::resolve_percentage() const
  945. {
  946. auto result = m_calculation->resolve({}, {});
  947. if (result.value().has<Percentage>())
  948. return result.value().get<Percentage>();
  949. return {};
  950. }
  951. Optional<Time> CalculatedStyleValue::resolve_time() const
  952. {
  953. auto result = m_calculation->resolve({}, {});
  954. if (result.value().has<Time>())
  955. return result.value().get<Time>();
  956. return {};
  957. }
  958. Optional<Time> CalculatedStyleValue::resolve_time_percentage(Time const& percentage_basis) const
  959. {
  960. auto result = m_calculation->resolve({}, percentage_basis);
  961. return result.value().visit(
  962. [&](Time const& time) -> Optional<Time> {
  963. return time;
  964. },
  965. [&](auto const&) -> Optional<Time> {
  966. return {};
  967. });
  968. }
  969. Optional<double> CalculatedStyleValue::resolve_number() const
  970. {
  971. auto result = m_calculation->resolve({}, {});
  972. if (result.value().has<Number>())
  973. return result.value().get<Number>().value();
  974. return {};
  975. }
  976. Optional<i64> CalculatedStyleValue::resolve_integer()
  977. {
  978. auto result = m_calculation->resolve({}, {});
  979. if (result.value().has<Number>())
  980. return result.value().get<Number>().integer_value();
  981. return {};
  982. }
  983. bool CalculatedStyleValue::contains_percentage() const
  984. {
  985. return m_calculation->contains_percentage();
  986. }
  987. }