CalculatedStyleValue.cpp 36 KB

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