CalculatedStyleValue.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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, Layout::Node const* layout_node)
  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. [layout_node](Length const& length) { return length.to_px(*layout_node).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(Layout::Node 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(Layout::Node const* layout_node, 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(layout_node, percentage_basis);
  144. if (!total.has_value()) {
  145. total = additional_value;
  146. continue;
  147. }
  148. total->add(additional_value, layout_node, 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(Layout::Node const* layout_node, 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(layout_node, percentage_basis);
  231. if (!total.has_value()) {
  232. total = additional_value;
  233. continue;
  234. }
  235. total->multiply_by(additional_value, layout_node);
  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(Layout::Node const* layout_node, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  277. {
  278. auto child_value = m_value->resolve(layout_node, 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(Layout::Node const* layout_node, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  320. {
  321. auto child_value = m_value->resolve(layout_node, 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(Layout::Node const* layout_node, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  373. {
  374. CalculatedStyleValue::CalculationResult smallest_node = m_values.first()->resolve(layout_node, percentage_basis);
  375. auto smallest_value = resolve_value(smallest_node.value(), layout_node);
  376. for (size_t i = 1; i < m_values.size(); i++) {
  377. auto child_resolved = m_values[i]->resolve(layout_node, percentage_basis);
  378. auto child_value = resolve_value(child_resolved.value(), layout_node);
  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(Layout::Node const* layout_node, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
  437. {
  438. CalculatedStyleValue::CalculationResult largest_node = m_values.first()->resolve(layout_node, percentage_basis);
  439. auto largest_value = resolve_value(largest_node.value(), layout_node);
  440. for (size_t i = 1; i < m_values.size(); i++) {
  441. auto child_resolved = m_values[i]->resolve(layout_node, percentage_basis);
  442. auto child_value = resolve_value(child_resolved.value(), layout_node);
  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. void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  466. {
  467. add_or_subtract_internal(SumOperation::Add, other, layout_node, percentage_basis);
  468. }
  469. void CalculatedStyleValue::CalculationResult::subtract(CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  470. {
  471. add_or_subtract_internal(SumOperation::Subtract, other, layout_node, percentage_basis);
  472. }
  473. void CalculatedStyleValue::CalculationResult::add_or_subtract_internal(SumOperation op, CalculationResult const& other, Layout::Node const* layout_node, PercentageBasis const& percentage_basis)
  474. {
  475. // 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>".
  476. // Though, having the same type may mean that one side is a <dimension> and the other a <percentage>.
  477. // Note: This is almost identical to ::add()
  478. m_value.visit(
  479. [&](Number const& number) {
  480. auto other_number = other.m_value.get<Number>();
  481. if (op == SumOperation::Add) {
  482. m_value = number + other_number;
  483. } else {
  484. m_value = number - other_number;
  485. }
  486. },
  487. [&](Angle const& angle) {
  488. auto this_degrees = angle.to_degrees();
  489. if (other.m_value.has<Angle>()) {
  490. auto other_degrees = other.m_value.get<Angle>().to_degrees();
  491. if (op == SumOperation::Add)
  492. m_value = Angle::make_degrees(this_degrees + other_degrees);
  493. else
  494. m_value = Angle::make_degrees(this_degrees - other_degrees);
  495. } else {
  496. VERIFY(percentage_basis.has<Angle>());
  497. auto other_degrees = percentage_basis.get<Angle>().percentage_of(other.m_value.get<Percentage>()).to_degrees();
  498. if (op == SumOperation::Add)
  499. m_value = Angle::make_degrees(this_degrees + other_degrees);
  500. else
  501. m_value = Angle::make_degrees(this_degrees - other_degrees);
  502. }
  503. },
  504. [&](Frequency const& frequency) {
  505. auto this_hertz = frequency.to_hertz();
  506. if (other.m_value.has<Frequency>()) {
  507. auto other_hertz = other.m_value.get<Frequency>().to_hertz();
  508. if (op == SumOperation::Add)
  509. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  510. else
  511. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  512. } else {
  513. VERIFY(percentage_basis.has<Frequency>());
  514. auto other_hertz = percentage_basis.get<Frequency>().percentage_of(other.m_value.get<Percentage>()).to_hertz();
  515. if (op == SumOperation::Add)
  516. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  517. else
  518. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  519. }
  520. },
  521. [&](Length const& length) {
  522. auto this_px = length.to_px(*layout_node);
  523. if (other.m_value.has<Length>()) {
  524. auto other_px = other.m_value.get<Length>().to_px(*layout_node);
  525. if (op == SumOperation::Add)
  526. m_value = Length::make_px(this_px + other_px);
  527. else
  528. m_value = Length::make_px(this_px - other_px);
  529. } else {
  530. VERIFY(percentage_basis.has<Length>());
  531. auto other_px = percentage_basis.get<Length>().percentage_of(other.m_value.get<Percentage>()).to_px(*layout_node);
  532. if (op == SumOperation::Add)
  533. m_value = Length::make_px(this_px + other_px);
  534. else
  535. m_value = Length::make_px(this_px - other_px);
  536. }
  537. },
  538. [&](Time const& time) {
  539. auto this_seconds = time.to_seconds();
  540. if (other.m_value.has<Time>()) {
  541. auto other_seconds = other.m_value.get<Time>().to_seconds();
  542. if (op == SumOperation::Add)
  543. m_value = Time::make_seconds(this_seconds + other_seconds);
  544. else
  545. m_value = Time::make_seconds(this_seconds - other_seconds);
  546. } else {
  547. VERIFY(percentage_basis.has<Time>());
  548. auto other_seconds = percentage_basis.get<Time>().percentage_of(other.m_value.get<Percentage>()).to_seconds();
  549. if (op == SumOperation::Add)
  550. m_value = Time::make_seconds(this_seconds + other_seconds);
  551. else
  552. m_value = Time::make_seconds(this_seconds - other_seconds);
  553. }
  554. },
  555. [&](Percentage const& percentage) {
  556. if (other.m_value.has<Percentage>()) {
  557. if (op == SumOperation::Add)
  558. m_value = Percentage { percentage.value() + other.m_value.get<Percentage>().value() };
  559. else
  560. m_value = Percentage { percentage.value() - other.m_value.get<Percentage>().value() };
  561. return;
  562. }
  563. // 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`.
  564. CalculationResult new_value = other;
  565. if (op == SumOperation::Add) {
  566. new_value.add(*this, layout_node, percentage_basis);
  567. } else {
  568. // Turn 'this - other' into '-other + this', as 'A + B == B + A', but 'A - B != B - A'
  569. new_value.multiply_by({ Number { Number::Type::Integer, -1.0f } }, layout_node);
  570. new_value.add(*this, layout_node, percentage_basis);
  571. }
  572. *this = new_value;
  573. });
  574. }
  575. void CalculatedStyleValue::CalculationResult::multiply_by(CalculationResult const& other, Layout::Node const* layout_node)
  576. {
  577. // We know from validation when resolving the type, that at least one side must be a <number> or <integer>.
  578. // Both of these are represented as a double.
  579. VERIFY(m_value.has<Number>() || other.m_value.has<Number>());
  580. bool other_is_number = other.m_value.has<Number>();
  581. m_value.visit(
  582. [&](Number const& number) {
  583. if (other_is_number) {
  584. m_value = number * other.m_value.get<Number>();
  585. } else {
  586. // Avoid duplicating all the logic by swapping `this` and `other`.
  587. CalculationResult new_value = other;
  588. new_value.multiply_by(*this, layout_node);
  589. *this = new_value;
  590. }
  591. },
  592. [&](Angle const& angle) {
  593. m_value = Angle::make_degrees(angle.to_degrees() * other.m_value.get<Number>().value());
  594. },
  595. [&](Frequency const& frequency) {
  596. m_value = Frequency::make_hertz(frequency.to_hertz() * other.m_value.get<Number>().value());
  597. },
  598. [&](Length const& length) {
  599. VERIFY(layout_node);
  600. m_value = Length::make_px(length.to_px(*layout_node) * static_cast<double>(other.m_value.get<Number>().value()));
  601. },
  602. [&](Time const& time) {
  603. m_value = Time::make_seconds(time.to_seconds() * other.m_value.get<Number>().value());
  604. },
  605. [&](Percentage const& percentage) {
  606. m_value = Percentage { percentage.value() * other.m_value.get<Number>().value() };
  607. });
  608. }
  609. void CalculatedStyleValue::CalculationResult::divide_by(CalculationResult const& other, Layout::Node const* layout_node)
  610. {
  611. // We know from validation when resolving the type, that `other` must be a <number> or <integer>.
  612. // Both of these are represented as a Number.
  613. auto denominator = other.m_value.get<Number>().value();
  614. // FIXME: Dividing by 0 is invalid, and should be caught during parsing.
  615. VERIFY(denominator != 0.0);
  616. m_value.visit(
  617. [&](Number const& number) {
  618. m_value = Number {
  619. Number::Type::Number,
  620. number.value() / denominator
  621. };
  622. },
  623. [&](Angle const& angle) {
  624. m_value = Angle::make_degrees(angle.to_degrees() / denominator);
  625. },
  626. [&](Frequency const& frequency) {
  627. m_value = Frequency::make_hertz(frequency.to_hertz() / denominator);
  628. },
  629. [&](Length const& length) {
  630. VERIFY(layout_node);
  631. m_value = Length::make_px(length.to_px(*layout_node) / static_cast<double>(denominator));
  632. },
  633. [&](Time const& time) {
  634. m_value = Time::make_seconds(time.to_seconds() / denominator);
  635. },
  636. [&](Percentage const& percentage) {
  637. m_value = Percentage { percentage.value() / denominator };
  638. });
  639. }
  640. void CalculatedStyleValue::CalculationResult::negate()
  641. {
  642. m_value.visit(
  643. [&](Number const& number) {
  644. m_value = Number { number.type(), 0 - number.value() };
  645. },
  646. [&](Angle const& angle) {
  647. m_value = Angle { 0 - angle.raw_value(), angle.type() };
  648. },
  649. [&](Frequency const& frequency) {
  650. m_value = Frequency { 0 - frequency.raw_value(), frequency.type() };
  651. },
  652. [&](Length const& length) {
  653. m_value = Length { 0 - length.raw_value(), length.type() };
  654. },
  655. [&](Time const& time) {
  656. m_value = Time { 0 - time.raw_value(), time.type() };
  657. },
  658. [&](Percentage const& percentage) {
  659. m_value = Percentage { 0 - percentage.value() };
  660. });
  661. }
  662. void CalculatedStyleValue::CalculationResult::invert()
  663. {
  664. // FIXME: Correctly handle division by zero.
  665. m_value.visit(
  666. [&](Number const& number) {
  667. m_value = Number { Number::Type::Number, 1 / number.value() };
  668. },
  669. [&](Angle const& angle) {
  670. m_value = Angle { 1 / angle.raw_value(), angle.type() };
  671. },
  672. [&](Frequency const& frequency) {
  673. m_value = Frequency { 1 / frequency.raw_value(), frequency.type() };
  674. },
  675. [&](Length const& length) {
  676. m_value = Length { 1 / length.raw_value(), length.type() };
  677. },
  678. [&](Time const& time) {
  679. m_value = Time { 1 / time.raw_value(), time.type() };
  680. },
  681. [&](Percentage const& percentage) {
  682. m_value = Percentage { 1 / percentage.value() };
  683. });
  684. }
  685. ErrorOr<String> CalculatedStyleValue::to_string() const
  686. {
  687. // FIXME: Implement this according to https://www.w3.org/TR/css-values-4/#calc-serialize once that stabilizes.
  688. return String::formatted("calc({})", TRY(m_calculation->to_string()));
  689. }
  690. bool CalculatedStyleValue::equals(StyleValue const& other) const
  691. {
  692. if (type() != other.type())
  693. return false;
  694. // This is a case where comparing the strings actually makes sense.
  695. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  696. }
  697. Optional<Angle> CalculatedStyleValue::resolve_angle() const
  698. {
  699. auto result = m_calculation->resolve(nullptr, {});
  700. if (result.value().has<Angle>())
  701. return result.value().get<Angle>();
  702. return {};
  703. }
  704. Optional<Angle> CalculatedStyleValue::resolve_angle_percentage(Angle const& percentage_basis) const
  705. {
  706. auto result = m_calculation->resolve(nullptr, percentage_basis);
  707. return result.value().visit(
  708. [&](Angle const& angle) -> Optional<Angle> {
  709. return angle;
  710. },
  711. [&](Percentage const& percentage) -> Optional<Angle> {
  712. return percentage_basis.percentage_of(percentage);
  713. },
  714. [&](auto const&) -> Optional<Angle> {
  715. return {};
  716. });
  717. }
  718. Optional<Frequency> CalculatedStyleValue::resolve_frequency() const
  719. {
  720. auto result = m_calculation->resolve(nullptr, {});
  721. if (result.value().has<Frequency>())
  722. return result.value().get<Frequency>();
  723. return {};
  724. }
  725. Optional<Frequency> CalculatedStyleValue::resolve_frequency_percentage(Frequency const& percentage_basis) const
  726. {
  727. auto result = m_calculation->resolve(nullptr, percentage_basis);
  728. return result.value().visit(
  729. [&](Frequency const& frequency) -> Optional<Frequency> {
  730. return frequency;
  731. },
  732. [&](Percentage const& percentage) -> Optional<Frequency> {
  733. return percentage_basis.percentage_of(percentage);
  734. },
  735. [&](auto const&) -> Optional<Frequency> {
  736. return {};
  737. });
  738. }
  739. Optional<Length> CalculatedStyleValue::resolve_length(Layout::Node const& layout_node) const
  740. {
  741. auto result = m_calculation->resolve(&layout_node, {});
  742. if (result.value().has<Length>())
  743. return result.value().get<Length>();
  744. return {};
  745. }
  746. Optional<Length> CalculatedStyleValue::resolve_length_percentage(Layout::Node const& layout_node, Length const& percentage_basis) const
  747. {
  748. auto result = m_calculation->resolve(&layout_node, percentage_basis);
  749. return result.value().visit(
  750. [&](Length const& length) -> Optional<Length> {
  751. return length;
  752. },
  753. [&](Percentage const& percentage) -> Optional<Length> {
  754. return percentage_basis.percentage_of(percentage);
  755. },
  756. [&](auto const&) -> Optional<Length> {
  757. return {};
  758. });
  759. }
  760. Optional<Percentage> CalculatedStyleValue::resolve_percentage() const
  761. {
  762. auto result = m_calculation->resolve(nullptr, {});
  763. if (result.value().has<Percentage>())
  764. return result.value().get<Percentage>();
  765. return {};
  766. }
  767. Optional<Time> CalculatedStyleValue::resolve_time() const
  768. {
  769. auto result = m_calculation->resolve(nullptr, {});
  770. if (result.value().has<Time>())
  771. return result.value().get<Time>();
  772. return {};
  773. }
  774. Optional<Time> CalculatedStyleValue::resolve_time_percentage(Time const& percentage_basis) const
  775. {
  776. auto result = m_calculation->resolve(nullptr, percentage_basis);
  777. return result.value().visit(
  778. [&](Time const& time) -> Optional<Time> {
  779. return time;
  780. },
  781. [&](auto const&) -> Optional<Time> {
  782. return {};
  783. });
  784. }
  785. Optional<double> CalculatedStyleValue::resolve_number() const
  786. {
  787. auto result = m_calculation->resolve(nullptr, {});
  788. if (result.value().has<Number>())
  789. return result.value().get<Number>().value();
  790. return {};
  791. }
  792. Optional<i64> CalculatedStyleValue::resolve_integer()
  793. {
  794. auto result = m_calculation->resolve(nullptr, {});
  795. if (result.value().has<Number>())
  796. return result.value().get<Number>().integer_value();
  797. return {};
  798. }
  799. bool CalculatedStyleValue::contains_percentage() const
  800. {
  801. return m_calculation->contains_percentage();
  802. }
  803. }