CalculatedStyleValue.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  601. {
  602. add_or_subtract_internal(SumOperation::Add, other, context, percentage_basis);
  603. }
  604. void CalculatedStyleValue::CalculationResult::subtract(CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  605. {
  606. add_or_subtract_internal(SumOperation::Subtract, other, context, percentage_basis);
  607. }
  608. void CalculatedStyleValue::CalculationResult::add_or_subtract_internal(SumOperation op, CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
  609. {
  610. // 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>".
  611. // Though, having the same type may mean that one side is a <dimension> and the other a <percentage>.
  612. // Note: This is almost identical to ::add()
  613. m_value.visit(
  614. [&](Number const& number) {
  615. auto other_number = other.m_value.get<Number>();
  616. if (op == SumOperation::Add) {
  617. m_value = number + other_number;
  618. } else {
  619. m_value = number - other_number;
  620. }
  621. },
  622. [&](Angle const& angle) {
  623. auto this_degrees = angle.to_degrees();
  624. if (other.m_value.has<Angle>()) {
  625. auto other_degrees = other.m_value.get<Angle>().to_degrees();
  626. if (op == SumOperation::Add)
  627. m_value = Angle::make_degrees(this_degrees + other_degrees);
  628. else
  629. m_value = Angle::make_degrees(this_degrees - other_degrees);
  630. } else {
  631. VERIFY(percentage_basis.has<Angle>());
  632. auto other_degrees = percentage_basis.get<Angle>().percentage_of(other.m_value.get<Percentage>()).to_degrees();
  633. if (op == SumOperation::Add)
  634. m_value = Angle::make_degrees(this_degrees + other_degrees);
  635. else
  636. m_value = Angle::make_degrees(this_degrees - other_degrees);
  637. }
  638. },
  639. [&](Frequency const& frequency) {
  640. auto this_hertz = frequency.to_hertz();
  641. if (other.m_value.has<Frequency>()) {
  642. auto other_hertz = other.m_value.get<Frequency>().to_hertz();
  643. if (op == SumOperation::Add)
  644. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  645. else
  646. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  647. } else {
  648. VERIFY(percentage_basis.has<Frequency>());
  649. auto other_hertz = percentage_basis.get<Frequency>().percentage_of(other.m_value.get<Percentage>()).to_hertz();
  650. if (op == SumOperation::Add)
  651. m_value = Frequency::make_hertz(this_hertz + other_hertz);
  652. else
  653. m_value = Frequency::make_hertz(this_hertz - other_hertz);
  654. }
  655. },
  656. [&](Length const& length) {
  657. auto this_px = length.to_px(*context);
  658. if (other.m_value.has<Length>()) {
  659. auto other_px = other.m_value.get<Length>().to_px(*context);
  660. if (op == SumOperation::Add)
  661. m_value = Length::make_px(this_px + other_px);
  662. else
  663. m_value = Length::make_px(this_px - other_px);
  664. } else {
  665. VERIFY(percentage_basis.has<Length>());
  666. auto other_px = percentage_basis.get<Length>().percentage_of(other.m_value.get<Percentage>()).to_px(*context);
  667. if (op == SumOperation::Add)
  668. m_value = Length::make_px(this_px + other_px);
  669. else
  670. m_value = Length::make_px(this_px - other_px);
  671. }
  672. },
  673. [&](Time const& time) {
  674. auto this_seconds = time.to_seconds();
  675. if (other.m_value.has<Time>()) {
  676. auto other_seconds = other.m_value.get<Time>().to_seconds();
  677. if (op == SumOperation::Add)
  678. m_value = Time::make_seconds(this_seconds + other_seconds);
  679. else
  680. m_value = Time::make_seconds(this_seconds - other_seconds);
  681. } else {
  682. VERIFY(percentage_basis.has<Time>());
  683. auto other_seconds = percentage_basis.get<Time>().percentage_of(other.m_value.get<Percentage>()).to_seconds();
  684. if (op == SumOperation::Add)
  685. m_value = Time::make_seconds(this_seconds + other_seconds);
  686. else
  687. m_value = Time::make_seconds(this_seconds - other_seconds);
  688. }
  689. },
  690. [&](Percentage const& percentage) {
  691. if (other.m_value.has<Percentage>()) {
  692. if (op == SumOperation::Add)
  693. m_value = Percentage { percentage.value() + other.m_value.get<Percentage>().value() };
  694. else
  695. m_value = Percentage { percentage.value() - other.m_value.get<Percentage>().value() };
  696. return;
  697. }
  698. // 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`.
  699. CalculationResult new_value = other;
  700. if (op == SumOperation::Add) {
  701. new_value.add(*this, context, percentage_basis);
  702. } else {
  703. // Turn 'this - other' into '-other + this', as 'A + B == B + A', but 'A - B != B - A'
  704. new_value.multiply_by({ Number { Number::Type::Integer, -1.0f } }, context);
  705. new_value.add(*this, context, percentage_basis);
  706. }
  707. *this = new_value;
  708. });
  709. }
  710. void CalculatedStyleValue::CalculationResult::multiply_by(CalculationResult const& other, Optional<Length::ResolutionContext const&> context)
  711. {
  712. // We know from validation when resolving the type, that at least one side must be a <number> or <integer>.
  713. // Both of these are represented as a double.
  714. VERIFY(m_value.has<Number>() || other.m_value.has<Number>());
  715. bool other_is_number = other.m_value.has<Number>();
  716. m_value.visit(
  717. [&](Number const& number) {
  718. if (other_is_number) {
  719. m_value = number * other.m_value.get<Number>();
  720. } else {
  721. // Avoid duplicating all the logic by swapping `this` and `other`.
  722. CalculationResult new_value = other;
  723. new_value.multiply_by(*this, context);
  724. *this = new_value;
  725. }
  726. },
  727. [&](Angle const& angle) {
  728. m_value = Angle::make_degrees(angle.to_degrees() * other.m_value.get<Number>().value());
  729. },
  730. [&](Frequency const& frequency) {
  731. m_value = Frequency::make_hertz(frequency.to_hertz() * other.m_value.get<Number>().value());
  732. },
  733. [&](Length const& length) {
  734. m_value = Length::make_px(length.to_px(*context) * static_cast<double>(other.m_value.get<Number>().value()));
  735. },
  736. [&](Time const& time) {
  737. m_value = Time::make_seconds(time.to_seconds() * other.m_value.get<Number>().value());
  738. },
  739. [&](Percentage const& percentage) {
  740. m_value = Percentage { percentage.value() * other.m_value.get<Number>().value() };
  741. });
  742. }
  743. void CalculatedStyleValue::CalculationResult::divide_by(CalculationResult const& other, Optional<Length::ResolutionContext const&> context)
  744. {
  745. // We know from validation when resolving the type, that `other` must be a <number> or <integer>.
  746. // Both of these are represented as a Number.
  747. auto denominator = other.m_value.get<Number>().value();
  748. // FIXME: Dividing by 0 is invalid, and should be caught during parsing.
  749. VERIFY(denominator != 0.0);
  750. m_value.visit(
  751. [&](Number const& number) {
  752. m_value = Number {
  753. Number::Type::Number,
  754. number.value() / denominator
  755. };
  756. },
  757. [&](Angle const& angle) {
  758. m_value = Angle::make_degrees(angle.to_degrees() / denominator);
  759. },
  760. [&](Frequency const& frequency) {
  761. m_value = Frequency::make_hertz(frequency.to_hertz() / denominator);
  762. },
  763. [&](Length const& length) {
  764. m_value = Length::make_px(length.to_px(*context) / static_cast<double>(denominator));
  765. },
  766. [&](Time const& time) {
  767. m_value = Time::make_seconds(time.to_seconds() / denominator);
  768. },
  769. [&](Percentage const& percentage) {
  770. m_value = Percentage { percentage.value() / denominator };
  771. });
  772. }
  773. void CalculatedStyleValue::CalculationResult::negate()
  774. {
  775. m_value.visit(
  776. [&](Number const& number) {
  777. m_value = Number { number.type(), 0 - number.value() };
  778. },
  779. [&](Angle const& angle) {
  780. m_value = Angle { 0 - angle.raw_value(), angle.type() };
  781. },
  782. [&](Frequency const& frequency) {
  783. m_value = Frequency { 0 - frequency.raw_value(), frequency.type() };
  784. },
  785. [&](Length const& length) {
  786. m_value = Length { 0 - length.raw_value(), length.type() };
  787. },
  788. [&](Time const& time) {
  789. m_value = Time { 0 - time.raw_value(), time.type() };
  790. },
  791. [&](Percentage const& percentage) {
  792. m_value = Percentage { 0 - percentage.value() };
  793. });
  794. }
  795. void CalculatedStyleValue::CalculationResult::invert()
  796. {
  797. // FIXME: Correctly handle division by zero.
  798. m_value.visit(
  799. [&](Number const& number) {
  800. m_value = Number { Number::Type::Number, 1 / number.value() };
  801. },
  802. [&](Angle const& angle) {
  803. m_value = Angle { 1 / angle.raw_value(), angle.type() };
  804. },
  805. [&](Frequency const& frequency) {
  806. m_value = Frequency { 1 / frequency.raw_value(), frequency.type() };
  807. },
  808. [&](Length const& length) {
  809. m_value = Length { 1 / length.raw_value(), length.type() };
  810. },
  811. [&](Time const& time) {
  812. m_value = Time { 1 / time.raw_value(), time.type() };
  813. },
  814. [&](Percentage const& percentage) {
  815. m_value = Percentage { 1 / percentage.value() };
  816. });
  817. }
  818. ErrorOr<String> CalculatedStyleValue::to_string() const
  819. {
  820. // FIXME: Implement this according to https://www.w3.org/TR/css-values-4/#calc-serialize once that stabilizes.
  821. return String::formatted("calc({})", TRY(m_calculation->to_string()));
  822. }
  823. bool CalculatedStyleValue::equals(StyleValue const& other) const
  824. {
  825. if (type() != other.type())
  826. return false;
  827. // This is a case where comparing the strings actually makes sense.
  828. return to_string().release_value_but_fixme_should_propagate_errors() == other.to_string().release_value_but_fixme_should_propagate_errors();
  829. }
  830. Optional<Angle> CalculatedStyleValue::resolve_angle() const
  831. {
  832. auto result = m_calculation->resolve({}, {});
  833. if (result.value().has<Angle>())
  834. return result.value().get<Angle>();
  835. return {};
  836. }
  837. Optional<Angle> CalculatedStyleValue::resolve_angle_percentage(Angle const& percentage_basis) const
  838. {
  839. auto result = m_calculation->resolve({}, percentage_basis);
  840. return result.value().visit(
  841. [&](Angle const& angle) -> Optional<Angle> {
  842. return angle;
  843. },
  844. [&](Percentage const& percentage) -> Optional<Angle> {
  845. return percentage_basis.percentage_of(percentage);
  846. },
  847. [&](auto const&) -> Optional<Angle> {
  848. return {};
  849. });
  850. }
  851. Optional<Frequency> CalculatedStyleValue::resolve_frequency() const
  852. {
  853. auto result = m_calculation->resolve({}, {});
  854. if (result.value().has<Frequency>())
  855. return result.value().get<Frequency>();
  856. return {};
  857. }
  858. Optional<Frequency> CalculatedStyleValue::resolve_frequency_percentage(Frequency const& percentage_basis) const
  859. {
  860. auto result = m_calculation->resolve({}, percentage_basis);
  861. return result.value().visit(
  862. [&](Frequency const& frequency) -> Optional<Frequency> {
  863. return frequency;
  864. },
  865. [&](Percentage const& percentage) -> Optional<Frequency> {
  866. return percentage_basis.percentage_of(percentage);
  867. },
  868. [&](auto const&) -> Optional<Frequency> {
  869. return {};
  870. });
  871. }
  872. Optional<Length> CalculatedStyleValue::resolve_length(Length::ResolutionContext const& context) const
  873. {
  874. auto result = m_calculation->resolve(context, {});
  875. if (result.value().has<Length>())
  876. return result.value().get<Length>();
  877. return {};
  878. }
  879. Optional<Length> CalculatedStyleValue::resolve_length(Layout::Node const& layout_node) const
  880. {
  881. return resolve_length(Length::ResolutionContext::for_layout_node(layout_node));
  882. }
  883. Optional<Length> CalculatedStyleValue::resolve_length_percentage(Layout::Node const& layout_node, Length const& percentage_basis) const
  884. {
  885. auto result = m_calculation->resolve(Length::ResolutionContext::for_layout_node(layout_node), percentage_basis);
  886. return result.value().visit(
  887. [&](Length const& length) -> Optional<Length> {
  888. return length;
  889. },
  890. [&](Percentage const& percentage) -> Optional<Length> {
  891. return percentage_basis.percentage_of(percentage);
  892. },
  893. [&](auto const&) -> Optional<Length> {
  894. return {};
  895. });
  896. }
  897. Optional<Percentage> CalculatedStyleValue::resolve_percentage() const
  898. {
  899. auto result = m_calculation->resolve({}, {});
  900. if (result.value().has<Percentage>())
  901. return result.value().get<Percentage>();
  902. return {};
  903. }
  904. Optional<Time> CalculatedStyleValue::resolve_time() const
  905. {
  906. auto result = m_calculation->resolve({}, {});
  907. if (result.value().has<Time>())
  908. return result.value().get<Time>();
  909. return {};
  910. }
  911. Optional<Time> CalculatedStyleValue::resolve_time_percentage(Time const& percentage_basis) const
  912. {
  913. auto result = m_calculation->resolve({}, percentage_basis);
  914. return result.value().visit(
  915. [&](Time const& time) -> Optional<Time> {
  916. return time;
  917. },
  918. [&](auto const&) -> Optional<Time> {
  919. return {};
  920. });
  921. }
  922. Optional<double> CalculatedStyleValue::resolve_number() const
  923. {
  924. auto result = m_calculation->resolve({}, {});
  925. if (result.value().has<Number>())
  926. return result.value().get<Number>().value();
  927. return {};
  928. }
  929. Optional<i64> CalculatedStyleValue::resolve_integer()
  930. {
  931. auto result = m_calculation->resolve({}, {});
  932. if (result.value().has<Number>())
  933. return result.value().get<Number>().integer_value();
  934. return {};
  935. }
  936. bool CalculatedStyleValue::contains_percentage() const
  937. {
  938. return m_calculation->contains_percentage();
  939. }
  940. }